FlaskDay02

flask 的变量规则和响应对象

目录

路由

延续之前所说的:注册路由就是建立 URL 规则和处理函数之间的关联。Flask 框架依赖于路由完成HTTP请求的分发。路由中的函数被称为视图函数,其返回值将作为HTTP响应的正文内容。

@app.route('/index')
def index():
return 'hello world!'

如果这个应用部署在主机根目录下,那么当用户访问:http://127.0.0.1:5000/index,Flask 框架就会调用我们的 index() 函数,其返回结果就传递给 WSGI 服务器发送给访问者。

再仔细研究一下,打开 Flask的中文文档 路由这一部分,点进 route() 函数,再点进一个 add_url_rule() 函数

可以发现另一种等价的写法是使用 Flask 应用实例的 add_url_route()方法:

def index():
return 'hello world!'
app.add_url_rule('/index',view_func = index)

其实,route 装饰器内部也是通过调用 add_url_route() 方法实现的路由注册。 但是显然,使用装饰器使代码看起来更优雅一些。

def route(self, rule: str, **options: t.Any) -> t.Callable:
def decorator(f: t.Callable) -> t.Callable:
endpoint = options.pop("endpoint", None)
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator
# route 装饰器内部也是通过调用 add_url_route() 方法实现的路由注册

变量规则

我们的路由不仅支持引号字符串的格式,还能在 URL 中添加变量,变量不同,响应的结果就不一样,通过一段代码来说明:

from flask import Flask
import settings
# 导入 uuid 模块
import uuid
app = Flask(__name__)
app.config.from_object(settings)
# 创建 data 字典
data = {'a': '北京', 'b': '上海', 'c': '深圳'}
@app.route('/')
def root():
return '欢迎来到主页'
# 默认是变量是字符串类型,这里的 string 可不加,直接写变量名。
@app.route('/getcity/<string:key>')
def get_city(key):
return data.get(key)
# 整型变量,注意与路由绑定的函数默认返回值是字符串类型,所以最后得到的整型结果要进行类型转换
@app.route('/add/<int:num>')
def sum_final(num):
return str(num + 10)
# 浮点型变量,注意与路由绑定的函数默认返回值是字符串类型,所以最后得到的整型结果要进行类型转换
@app.route('/getfloat/<float:num2>')
def sum_float(num2):
return str(num2)
# 本质上 path 也是字符串,但是允许出现斜杠,返回的可以认为是字符串类型的路径,所以不用进行类型转换
@app.route('/index/<path:p>')
def get_path(p):
return p
# uuid 有 uuid 自己的格式,我们不能通过乱传值来达到与上面三个路由同样的结果
# 下面是通过导入 uuid 模块并实例化对象 uid 调用其 uuid.uuid4() 方法去看看 uuid 的格式
@app.route('/getuuid/')
def get_uuid():
uid = uuid.uuid4()
return str(uid)
if __name__ == '__main__':
app.run(port=8056)

唯一的 URL / 重定向行为

来看看官方文档给的两个例子:

@app.route('/projects/')
def projects():
return 'The project page'
@app.route('/about')
def about():
return 'The about page'
  1. 原本路由中有 "/",请求路由有无 "/" 都能显示正常(请求路由无 "/" flask底层机制会自动重定向到有"/"的路由)
  2. 原本路由中无 "/",请求路由中如果添加了 "/",会显示 Not found
Some rights reserved
Except where otherwise noted, content on this page is licensed under a Creative Commons Attribution-NonCommercial 4.0 International license.