即使遵循这里和那里的许多示例,我也无法在 POST 方法中让我的 API 工作。
这是关于它的代码:
from flask import Flask, jsonify, request
@app.route('/api/v1/lists', methods=['POST'])
def add_entry():
print("p0")
content = request.get_json()
appname = content.get('title')
print(content)
print(appname)
当我使用curl查询时(我在Windows上运行它):
curl.exe -i -H“内容类型:application/json”-X POST -d '{“title”:“titi”}'http://localhost:5000/api/v1/lists http://localhost:5000/api/v1/lists
curl.exe -i -H "Content-Type: application/json" -X POST -d "{"""title""":"""读一本书"""}"http://localhost:5000/api/v1/lists http://localhost:5000/api/v1/lists
我总是返回 400 错误:
HTTP/1.0 400 错误请求
内容类型:text/html
内容长度:192
服务器:Werkzeug/0.12.1 Python/3.6.0
日期:2017 年 4 月 4 日,星期二 21:55:29 GMT
400 错误请求
错误的请求
浏览器(或代理)发送了该服务器无法理解的请求。
我不明白错误在哪里。
感谢您的帮助。
即使使用“工作”代码,如果 if 块失败(当value1
and value2
is None
)会导致同样的错误,因为你没有处理else
if 块的一部分。更正后的应该是:
@app.route('/api/v1/list', methods=['POST'])
def add_entry():
print("p0")
request_json = request.get_json()
value1 = request_json.get('First_Name')
value2 = request_json.get('Last_Name')
response_content = None
if value1 is not None and value2 is not None:
print("p3")
cursor.execute("INSERT INTO person (first_name,last_name) VALUES (%s,%s)", (value1, value2))
response_content = conn.commit()
return jsonify(response_content)
当然,您可能想要比这更好的东西None
作为回应。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)