说明、复习
一、路由
192.168.1.10:8080
@qpp.route('/index')
def index():
return ''
URL :http://127.0.0.1:8080/index
def route(self, rule: str, **options: t.Any) -> t.Callable:
"""Decorate a view function to register it with the given URL
rule and options. Calls :meth:`add_url_rule`, which has more
details about the implementation.
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如何实现,明白路由与装饰器的关系
二、路由的变量规则
在路由中允许出现变量,变量不同,结果不同。
# @Author : 二帆
# @File : app3.py
# @Software : PyCharm
from flask import Flask
import settings
app =Flask(__name__)
app.config.from_object(settings)
data = {'a':'北京','b':'上海'}
@app.route('/')
def index1():
return'我是首页 '
@app.route('/getcity/<key>')
def get_city(key):
print(type(key))
return data.get(key)
if __name__ == '__main__':
app.run(port=8080,debug=True) #在设置端口号,启动之前修改好
http://127.0.0.1:8080/getcity/b
http://127.0.0.1:8080/getcity/a
http://127.0.0.1:8080/
key是变量,str型
str
# -*- codeing = utf-8 -*-
# @Time : 2021/8/17 13:25
# @Author : 二帆
# @File : app3.py
# @Software : PyCharm
from flask import Flask
import settings
app =Flask(__name__)
app.config.from_object(settings)
data = {'a':'北京','b':'上海'}
@app.route('/')
def index1():
return'我是首页 '
@app.route('/getcity/<key>') #key变量名,str类型
def get_city(key):
print(type(key))
return data.get(key)
@app.route('/add/<int:num>') #key变量名
def add(num):
result = num +10
return result
if __name__ == '__main__':
app.run(port=8080,debug=True) #在设置端口号,启动之前修改好
加入int的转换类型,我们发现报错,如下图
int
ruturn 不能是整型,我们转化以下类型
#修改
@app.route('/add/<int:num>') #key变量名
def add(num):
result = num +10
return str(result) #转化为str类型
float
@app.route('/add1/<float:money>')
def add1(money):
print('------>',type(money))
return str(money)
path
@app.route('/index/<path:p>')
def get_path(p):
print('------>',type(p))
print(p)
return p
uuid
@app.route('/test/<uuid:uid>') #uuid类型
def test(uid):
#print('-----!!!--->',type(uid))
return '获取唯一的标识码'
唯一的URL/重定向行为
以下两条规则的不同之处在于是否使用尾部的斜杠。:
#路由中定义/,无论请求的URL是否带有/。如果请求的是没有/,浏览器就做了一次重定向
@app.route('/projects/')
def projects():
return 'The project page'
@app.route('/about')
def about():
return 'The about page'
请求没加/
不建议用/来区别
所有的路由搜索规则都是自上而下搜索,在写路由的是有定义的路由是唯一的
# -*- codeing = utf-8 -*-
# @Time : 2021/8/17 14:33
# @Author : 二帆
# @File : app4.py
# @Software : PyCharm
from flask import Flask
import settings
app =Flask(__name__)
app.config.from_object(settings)
@app.route('/index')
def index():
return {'a':'北京','b':'上海','上海':'深圳'}
if __name__ == '__main__':
app.run(port=8080,debug=True) #在设置端口号,启动之前修改好
元组
@app.route('/index1') #元组
def index1():
return {'北京','上海','深圳'}
@app.route('/index2')
def index2():
return Response('今天学习有些慢啊 ') #这时候返回的是Response对象
上面这些返回的字符串,其实也是做了一个response对象的封装,最终的返回结果还是response对象。