运行1
如果是.py文件,使用下面的语句:
$ set FLASK_APP=hello.py
$ flask run
如果是文件夹,则为:
$ set FLASK_APP=hello
$ flask run
如果使用调试模式,在flask run
前添加:
$ set FLASK_ENV=development
使服务器对外可见
Externally Visible Server If you run the server you will notice that
the server is only accessible from your own computer, not from any
other in the network. This is the default because in debugging mode a
user of the application can execute arbitrary Python code on your
computer.If you have the debugger disabled or trust the users on your network,
you can make the server publicly available simply by adding
–host=0.0.0.0 to the command line:$ flask run --host=0.0.0.0 This tells your operating system to listen
on all public IPs.
更多信息
关于部署,可以参考Deployment Options。
开发服务器的更多参数在Development Server。
关于调试器,可以参考Werkzeug documentation。
路由
使用route()
装饰器来将函数绑定到URL上。
@app.route('/xxx/<var>')
def func():
return 'hello'
URL可以是动态的。<var>
中的内容可以被用作参数,对其类型转换的操作如下。
类型转换
使用<converter:variable_name>
来指定参数的类型。可指定的类型如下表:
type | description |
---|---|
string |
(default) accepts any text without a slash |
int |
accepts positive integers |
float |
accepts positives floating point values |
path |
like string but also accepts slashes |
uuid |
accepts UUID strings |
url_for()
使用url_for()
来将一个指向一个函数的URL。
也可以通过下面的方式指向一个静态文件。静态文件存放在static文件夹中,并作为url_for
的endpoint
参数。
url_for('static', filename='style.css')
HTTP方法
通常情况下,路由回应GET request。在app.route()
中添加methods
参数来处理不同的HTTP方法。例如:
from flask import request
@app.route('/login', methods=['GET', 'POST'])
def login():