我正在尝试在Flask中创建一个简单的api,第一步是获取POST json数据。 (我现在只想打印它)这是我的代码,当我用json数据请求/ api时,它返回500错误。有关为何发生这种情况的任何想法?
from flask import Flask, request, Response
app = Flask(__name__)
@app.route('/')
def root_response():
return "Hello World."
@app.route('/api', methods=['POST', 'GET'])
def api_response():
if request.method == 'POST':
return request.json
if __name__ == '__main__':
app.run()
curl命令:
$ curl -H "Content-Type: application/json" --data @body.json http://127.0.0.1:5000/api
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>
body.json:
{
"please": "print",
"me": "now"
}
答案 0 :(得分:29)
首先,您要做的是启用调试模式,以便Flask实际上会告诉您错误是什么。 (每次修改代码时,您都可以获得烧瓶重新加载的额外好处!)
if __name__ == '__main__':
app.debug = True
app.run()
然后我们找出错误:
TypeError: 'dict' object is not callable
你要返回request.json,这是一本字典。您需要先将其转换为字符串。这很容易做到:
def api_response():
from flask import jsonify
if request.method == 'POST':
return jsonify(**request.json)
你有! :)
答案 1 :(得分:2)
服务器过载,因为默认端口(5000)或用户明确提到的端口(例如:app.run(port = 7000))可能在后台使用了其他进程,因此我们需要终止进程该端口正在使用的端口。
通过使用以下命令,您可以查看正在使用该端口的进程ID(PIDS): 在命令提示符下 netstat -o -a *查看端口的相应PID
然后使用以下命令杀死要使用的端口的所有进程(PIDS): Taskkill / PID 30832 / F 在这里,我将PID 30832用于端口127.0.0.1:7000,它给出了过载错误。 问题解决之后。
答案 2 :(得分:-1)
1. 第一:
if __name__ == '__main__':
app.run(debug=TRUE)
2。服务器(defaut)正在处理中,首先在该服务器上终止该过程:
通过使用以下命令,您可以查看正在使用该端口的进程ID(PIDS) 命令:在命令提示符下 netstat -o -a 。 Enter here to see sample 查看端口的相应PID。
然后使用以下命令杀死要使用的端口的所有进程(PIDS):Taskkill /PID 10324 /F
在这里,我将 PID 10324 用于端口127.0.0.1: 5000 ,这将导致过载错误。 该问题解决后。