非常感谢您的帮助!我是Flask的初学者,正在玩它来构建API。
执行以下代码段并在vs-code终端中运行代码时,它似乎在http://127.0.0.1:5000/上运行了该应用程序。
但是,当我在终端中单击URL时-在浏览器中启动URL并期望显示“ Hello World”时-它会在页面上显示“内部服务器错误”。然后在“ / [GET]”上显示“应用程序中的错误:异常”。
代码:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
print('Hello World!')
app.run(port=5000)
端子:
WKMGB0671549:REST-APIs josshepp$ python3 app_copy.py
* Serving Flask app "app_copy" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Hello World!
[2019-07-11 08:51:50,920] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
return self.finalize_request(rv)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask/app.py", line 1967, in finalize_request
response = self.make_response(rv)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask/app.py", line 2097, in make_response
"The view function did not return a valid response. The"
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
127.0.0.1 - - [11/Jul/2019 08:51:50] "GET / HTTP/1.1" 500 -
答案 0 :(得分:2)
您的视图函数未返回有效的响应。简而言之,返回“ Hello World!”而不是打印它:
@app.route('/')
def home():
return 'Hello World!'
Flask会自动为您将几种类型的返回值转换为Response,但是您可以阅读它们如何转换(link):
视图函数的返回值将自动转换为您的响应对象。如果返回值为字符串,则将其转换为响应对象,并以字符串作为响应正文,200 OK状态代码和text / html mimetype。
如果术语视图功能令人困惑,则烧瓶将其描述为(link):
视图功能是您编写的用于响应对应用程序请求的代码。 Flask使用模式将传入的请求URL与应该处理它的视图进行匹配。该视图返回的数据将Flask转换为外发响应。