Why my POST method from a web service refuses my json data?

时间:2017-03-02 23:32:34

标签: python json flask

I want to build a web service in python using flask library but I got stuck at the beginning. I managed to succeed with Get methods but I am having some trouble with my POST method. The problem I am having is that when I send a Json data with the POST method my program crashes with the following error: "ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

During handling of the above exception, another exception occurred:" If I send the request without the data everything works fine.

Below is the code for the method POST from the server. I kept it basic so I could find the error easier.

class End_Point(Resource):
    def POST(self):
        return 1

api.add_resource(End_Point,'/end_point')

Here is how I make the request that crashes my program:

url = 'http://127.0.0.1:5000/end_point'
response = requests.post(url, data=json.dumps("123"), headers=headers)

Do you have any idea what am I doing wrong?

1 个答案:

答案 0 :(得分:1)

You need to send it as an object/dictionary so you can actually access the value by a name on the server.

server:

from flask import Flask, request
from flask_restful import Resource, Api, reqparse

app = Flask(__name__)
api = Api(app)

parser = reqparse.RequestParser()
parser.add_argument('mynum', type=int, help='mynum is a number')

class EndPoint(Resource):

  def post(self):
    args = parser.parse_args()
    return {"status": "ok", "mynum": args['mynum']}

api.add_resource(EndPoint, '/end_point')

if __name__ == '__main__':
    app.run(debug=True)

client:

import requests
import json

headers = {'content-type': 'application/json'}
url = 'http://localhost:5000/end_point'
response = requests.post(url, data=json.dumps(dict(mynum=123)), headers=headers)
print('response', response.text)