FLASK Restful API 无法使用 PUT 添加

FLASK Restful API not able to add using PUT

我正在使用这个文档:来自 FLASK Restful

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

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

todos = {}

class TodoSimple(Resource):
    def get(self, todo_id):
        return {todo_id: todos[todo_id]}

    def put(self, todo_id):
        todos[todo_id] = request.form['data']
        return {todo_id: todos[todo_id]}

api.add_resource(TodoSimple, '/<string:todo_id>')

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

为了补充 新的待办事项,他们在 python 上调用以下命令:

from requests import put, get
put('http://localhost:5000/todo1', data={'data': 'Remember the milk'}).json()

数据来自json对象{'data':'.....} 并在此处检索到:request.form['data']

我想用我的 data2 对象替换 'Remember the milk':

data2 = {'ALTNUM':'noalt', 'CUSTTYPE': 'O',
'LASTNAME':'lnamedata2', 'FIRSTNAME':'fndata2', 'ADDR':'1254 data 2 address',
'ADDR2':'apt 3', 'CITY':'los angeles', 
'COUNTY':'011', 'STATE':'CA', 
'ZIPCODE':'90293', 'COUNTRY':'001', 
'ADDR_TYPE':'O','PHONE':'4254658029',
'PHONE2':'3442567777', 
'EMAIL':'test2@test2.com'}

并调用:print put('http://localhost:5000/newcustomer', data={'data':data2}).json()

我的 API 资源:

class New_Customer(Resource):
    def put(self):
        q = PHQuery()
        data = request.form['data']
        print(data)
        return data

调用这些时出现以下错误:

print put('http://localhost:5000/newcustomer', data=data2).json()
print put('http://localhost:5000/newcustomer', data={'data':data2}).json()
print put('http://localhost:5000/newcustomer', data=data2).json()
print put('http://localhost:5000/newcustomer', data=data2)



{u'message': u'The browser (or proxy) sent a request that this server could not understand.'}
CUSTTYPE
{u'message': u'The browser (or proxy) sent a request that this server could not understand.'}
<Response [400]>

我做错了什么? @foslock 应该是 data = request.json['data'] 吗?因为它是一个对象而不是表单数据?

返回 JSON,而不是 str

看起来您的 API 路由正在 returning 资源对象的原始字符串转换版本。相反,你想 return 它们作为 JSON,烧瓶可以用 jsonify 方法为你做。

import flask

class New_Customer(Resource):
    def put(self):
        q = PHQuery()
        data = request.get_json()
        new_cust = q.create_cust(data)
        return flask.jsonify(new_cust)

请注意在 Python 中,本地字典的字符串表示形式与 JSON 版本并不完全相同:

>>> dct = {'Hey': 'some value'}
>>> print(dct)
{'Hey': 'some value'}
>>> print(json.dumps(dct))
{"Hey": "some value"}

PUT/POST

发送 JSON

当使用 requests 库发送 PUT/POST 请求时,您默认以表单编码(具体为 application/x-www-form-urlencoded )格式发送请求正文, which is explained here。这种格式不适用于嵌套的结构化数据,例如您尝试发送的数据。相反,您可以使用 json 关键字参数发送 JSON 编码 (application/json) 的数据。

requests.put(url, json=data2)

旁注:如果您正在尝试创建新客户,您可能需要使用 POST 代替它可能被认为更多 RESTful,因为 PUT 通常用于 更新 现有资源,but this is up to you.

PUT/POST 数据中提取值

由于我们现在将请求正文作为 JSON 发送,因此我们需要在 API 服务器中将其反序列化。您可以在上面的以下行中看到这种情况:

data = request.get_json()

关于在 Flask 中正确地从 HTTP 请求中提取数据,您可以参考 this answer for more information