我正在使用此文档:来自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']吗?既然它是一个对象而不是表单数据?
答案 0 :(得分:1)
str
看起来您的API路由正在返回资源对象的原始字符串转换版本。你想把它们作为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
使用requests
库发送PUT / POST请求时,您默认以表单编码(application/x-www-form-urlencoded
为特定)格式发送请求正文{{3 }}。这种格式对于嵌套的结构化数据(如您尝试发送的内容)并不是很好。相反,您可以使用application/json
关键字参数发送JSON编码的数据(json
)。
requests.put(url, json=data2)
旁注:如果您尝试创建新客户,则可能需要使用 POST ,因为它可能被视为更加RESTful,因为 PUT 通常用于更新现有资源which is explained here。
PUT/POST
数据由于我们现在以JSON的身份发送请求正文,因此我们需要在API服务器中对其进行反序列化。您可以在以下行中看到上述情况:
data = request.get_json()
您可以参考but this is up to you,在Flask中正确地从HTTP请求中提取数据。