Python之flask框架
授课:林德尧(泉舟时代-未来城市技术总监)
Flask是一个Python编写的Web 微框架,让我们可以使用Python语言快速实现一个网站或Web服务。本文参考自Flask官方文档,大部分代码引用自官方文档。
我们修改代码中的输出,然后查看浏览器上是否有变化。如果你照做的话,可以看到什么变化都没有。其实Flask内置了调试模式,可以自动重载代码并显示调试信息。这需要我们开启调试模式,方法很简单,设置FLASK_DEBUG环境变量,并将值设置为1。或者设置app.debug=True
调用模式
from flask import Flask
app = Flask(__name__)
app.debug=True
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/login')
def login():
return 'Login'
if __name__ == '__main__':
app.run()
然后再次运行程序,会看到有这样的输出。这时候如果再次修改代码,会发现这次Flask会自动重启
* Restarting with stat
* Debugger is active!
* Debugger PIN: 157-063-180
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
路由
在上面的例子里可以看到路由的使用。如果了解Spring Web MVC的话,应该对路由很熟悉。路由通过使用Flask的app.route装饰器来设置,这类似Java的注解。
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello():
return 'Hello, World'
路径变量
如果希望获取/article/1这样的路径参数,就需要使用路径变量。路径变量的语法是/path/converter:varname。在路径变量前还可以使用可选的转换器,有以下几种转换器。
转换器 作用
string 默认选项,接受除了斜杠之外的字符串
int 接受整数
float 接受浮点数
path 和string类似,不过可以接受带斜杠的字符串
any 匹配任何一种转换器
uuid 接受UUID字符串
下面是Flask官方的例子。
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % username
@app.route('/post/<int:post_id>')
def show_post(post_id):
# show the post with the given id, the id is an integer
return 'Post %d' % post_id
构造URL
在Web程序中常常需要获取某个页面的URL,在Flask中需要使用url_for(‘方法名’)来构造对应方法的URL。下面是Flask官方的例子。
>>> from flask import Flask, url_for
>>> app = Flask(__name__)
>>> @app.route('/')
... def index(): pass
...
>>> @app.route('/login')
... def login(): pass
...
>>> @app.route(