@app.route('/')
def hello_world():
return "hello world"
#等价于
def hello_world():
return 'hello world'
app.add_url_rule('/',view_func=hello_world)
- 实际上都是通过add_url_rule()将规则与视图函数进行绑定
- 路由的变量规则:允许url中出现变量,变量不同,拿到的结果可能就是不同的
data = {'a':'北京','b':'上海','c':'深圳'}
@app.route('/getcity/')
def get_city(cityname):
return data[cityname]
就是一个变量,同时定义视图函数时,必须将这个变量传给视图函数
变量默认是字符串类型的,也可以在前面加上一个转换器,指定变量的类型
转换器类型
| string | (缺省值接受任何不包含斜杠的文本) |
|---|---|
| int | 接受正整数 |
| float | 接受正浮点数 |
| path | 类似string,但可以包含斜杠 |
| uuid | 接受UUID字符串 |
例如
@app.route('/add/')
def add(number):
result = number + 10
return str(result)
- 路由搜索规则从上往下搜索的,如果有两个相同的规则,只会执行第一个视图函数。所以尽量保持写路由规则的时候定义路由是唯一的。
- 视图函数不止可以返回字符串,也可以返回字典
@app.route('/index')
def index():
return {'a':'北京','b':'上海','c':'广州'}
但是因为没有声明编码方式,所以在网页上展示的中文是unicode编码方式,返回的格式是json格式(查看返回格式,看response headers里面的Content-Type:告诉浏览器返回值的类型,浏览器对此进行翻译即可)
- 视图函数还可以返回元组和Response实例
@app.route('/index')
def index():
return '北京'
用上面的方式时,实际上底层也会把这个字符串传到Response对象中,最终返回结果还是Response对象
@app.route('index')
def index():
return Response('北京')
- 视图函数返回元组,第一个是返回的值,第二个是状态码
@app.route('/index2')
def index2():
return 'sorry,the file is not found',404
- make_response()方法生成response对象,并且可以添加额外的响应头信息。
@app.route('/index')
def index():
content = '''
首页
div{
width: 100%;
height: 100px;
border: 2px solid red;
}
欢迎来到京东购物网站
- hello
- abc
- world
'''
response = make_response(content)
response.headers['mytest'] = '123abc'
response.headers['hello'] = 'world'
return response
可以在网页的响应头中查看添加的额外的响应头信息
- Response类
@app.route('/index')
def index():
response = Response('你好')
print(response.content_type)
print(response.headers)
print(response.status_code)
print(response.status)
response.set_cookie('name','苹苹')
return response
- request对象,注意是对象
@app.route('/index')
def index():
print(request.headers)
return 'hello'
- app.py与模板的结合使用
在templates文件夹下创建register.html
首页
欢迎注册京东用户
- hello
- abc
- world
再利用render_template()将模板与视图函数结合
@app.route('/register')
def register():
return render_template('register.html')
Jinjia2模板引擎,负责将render_template(‘register.html’)中的html文件找到并转换成字符串(从模板文件夹中的文件找到)
- print(app.url_map),可以查看路由规则表



