简体   繁体   中英

Python Flask Requests 400 Error Code

I'm catching a POST request from requests to flask-rest and I keep getting a 400 error code (Bad Request).

Requests Part:

def send_data(asset_id, data1, data2, data3):
    global _server_api
    headers = {'content-type': 'application/json'}
    complete_url = _server_api + asset_id
    payload = {'d1': data1,'d2': data2,'d3': data3}
    response = requests.post(complete_url, data=json.dumps(payload), headers=headers)

Flask Part:

from flask.ext.restful.representations.json import output_json
from flask import Flask, request
from flask_restful import reqparse, abort, Api, Resource
app = Flask(__name__)
api = Api(app)
assets = {}
class Broker(Resource): 
   def post(self, asset_id):
       assets[asset_id] = dict()
       data1 = request.form['d1']
       data2 = request.form['d2']
       data3 = request.form['d3']
       assets[asset_id]['d1'] = request.form['d1']
       assets[asset_id]['d2'] = request.form['d2']
       assets[asset_id]['d3'] = request.form['d3']
       collector(asset_id, data1, data2, data3) #<--- writes to DB
       return {asset_id: assets[asset_id]}

api.add_resource(Broker, '/api-v1.0/add/<string:asset_id>', methods=['PUT', 'POST', 'GET'])

Error Code:

{u'status': 400, u'message': u'Bad Request'}

I keep getting a 400 Error code when the requests part makes the call to the API.

When changing the request.form to request.get_json I get a error as below .

TypeError: 'instancemethod' object has no attribute '__getitem__'

Any help would be appreciated.

You're sending a JSON request, but the app expects a form. Instead of request.form use request.get_json() in the app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM