Correct way to return JSON response from POST request with web.py

最后都变了- 提交于 2019-12-12 04:06:14

问题


I have a web.py server.

I handle post requests like this:

class Endpoint(object):
    def POST(self):
        received_payload = web.data()
        # Do things with the payload (a JSON) --- I receive the payload correctly
        response = {"Response": "Good"}
        # I also tried returning the dictionary directly and building my own requests.Response object
        return json.dumps(response)

I am able to correctly receive and process the payload I send to the server, but I do not receive the response.

On the client side, I do this:

s = requests.Session()
s.headers.update({ 'Content-Type': 'application/json' })
response = s.post(url=url, json=payload)

The request reaches the server, and delivers the payload correctly. However, I get this error:

    response = s.post(url=url, json=payload)
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 511, in post
    return self.request('POST', url, data=data, json=json, **kwargs)
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 468, in request
    resp = self.send(prep, **send_kwargs)
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 576, in send
    r = adapter.send(request, **kwargs)
  File "/Library/Python/2.7/site-packages/requests/adapters.py", line 426, in send
    raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', BadStatusLine("''",))

I did some research, finding this and this

I tried the approach suggested in the first link, but I get the same error. It might be because I am using Python 2.7 while the original post is about Python 3. I also tried, based on the second link, to set the output field in web.ctx however, I get the same error.


What is the correct way to return a JSON as a response to a POST request?

来源:https://stackoverflow.com/questions/36092395/correct-way-to-return-json-response-from-post-request-with-web-py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!