当前位置:网站首页>Flask之路由(app.route)详解
Flask之路由(app.route)详解
2022-07-30 09:16:00 【m0_54850467】
目录
在讲创建路由之前先了解大致流程,工作本质
在 route 源码中
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.
.. code-block:: python
@app.route("/")
def index():
return "Hello, World!"
See :ref:`url-route-registrations`.
The endpoint name for the route defaults to the name of the view
function if the ``endpoint`` parameter isn't passed.
The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and
``OPTIONS`` are added automatically.
:param rule: The URL rule string.
:param options: Extra options passed to the
:class:`~werkzeug.routing.Rule` object.
"""
def decorator(f: t.Callable) -> t.Callable:
endpoint = options.pop("endpoint", None)
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator
这一部分
解释一下就是
程序从上往下 首先进入app.route路由部分然后 执行了 decorator
这里的 def decorator()就相当于将 app.route赋给 decorator
decorator = app.route(‘/index’,methods=[‘GET’,‘POST’])
@decorator
- decoratoe ( 函数名 )
创建路由的两种方式
方式一
别忘了导包 和 创建一个实例
from flask import Flask
app = Flask(__name__)
@app.route('/one',methods=['GET','POST'])
def one():
return "创建路由的方法一,返回值为: one"
运行 :
方式二
使用 add_url_rule
同样别忘记了导包和创建实例
def two():
return "创建路由的方法二,返回值为: two"
app.add_url_rule('/two',view_func=two)
运行 :
反向生成URL
endpoint 相当于创建了一个别名
在反向生成的时候 需要从 flask 里面导入 url_for
from flask import url_for
用于反向生成的时候才写别名
如果不起别名,则默认是其函数名
@app.route('/index',methods=['GET','POST'],endpoint="first")
def index():
h1 = url_for("first")
h2 = url_for("login") # 不起别名 使用默认名
h3 = url_for("logout") # 不起别名 使用默认名
print(h1,h2,h3)
return "index"
@app.route('/login',methods=['GET','POST'])
def login():
return "login"
@app.route('/logout',methods=['GET','POST'])
def logout():
return "logout"
注意事项 !!!
在我第一遍做简单flask的时候出现的一个问题
做到第二个项目的时候页面出现的却是第一个项目的结果
也就是在我想运行 反向生成URL.py 文件的时候 输入了我设置的新rule 可是网页一直显示 Not Found 并且输入第一个项目的rule可以正常显示
原因 :
1. 要么是你的上一个项目运行没有终止
2.要么是端口(12.0.0.1:5000)被占用了
解决 :
如果是你上一项目没有终止,正常情况下可以点击红色方块结束程序运行,终止掉程序运行
当建立多个项目时,127.0.0.1:5000这个端口被反复占用,导致pycharm无法杀掉上一个项目的进程,这时需要手动杀死进程
快捷键 Win + R 打开 cmd
在你的终端命令行输入
netstat -ano|findstr “5000”
然后杀掉对应 pid
结束进程
taskkill /pid 52824 /f
再次运行你的 .py 文件就可以正常显示了
总结 :
在运行 flask 程序时
通常大部分人操作时和python文件一样运行 右击然后run
右击run程序出来的结果
容易忘记停止并且可能会出现端口堵塞等问题
有一种改进方式
在下方有一个 Terminal (终端) 的标识
用终端去运行,点击它
Ctrl + C 快捷键结束
自定义路由转换器
@app.route('/index/<int:nid>',methods=['GET','POST'])
def index(nid):
print("int类型: ", nid)
return "返回结果是: int类型的nid"
运行 :
重定向
这个在很多场景都可以使用
打个比方
现在公司里有了一个用了很久的一个网站,
然后让公司里的程序员去对这个网站做一个优化改进
可是原来的网站网址被公司员工已经用了N多边了,网址都已经刻入DNA里了
现在优化好的新的网站网址告诉公司员工们,
为了避免一些员工习惯性的登入旧网站网址,
程序员要对旧网站网址增添一个重定向,也就是说 如果有员工习惯性的登入旧网站网址,那么这个重定向就起作用了,它会跳转到i新网站网址上去
@app.route('/old',methods=['GET','POST'],redirect_to='/new')
def old():
return "老功能"
@app.route('/new',methods=['GET','POST'])
def new():
return "新功能"
运行 :
输入 old 会自动跳转到 new 网页上
先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦
边栏推荐
- debian10 install djando
- The use of qsort function and its analog implementation
- ThreadLocal内存泄漏是伪命题?
- 【无标题】
- leetcode 剑指 Offer 52. 两个链表的第一个公共节点
- An article to understand service governance in distributed development
- 九九乘法表
- A near-perfect Unity full-platform hot update solution
- Re18:读论文 GCI Everything Has a Cause: Leveraging Causal Inference in Legal Text Analysis
- 百度paddleocr检测训练
猜你喜欢
微软 SQL 服务器被黑,带宽遭到破坏
20220728使用电脑上的蓝牙和汇承科技的蓝牙模块HC-05配对蓝牙串口传输
20220728 Use the bluetooth on the computer and the bluetooth module HC-05 of Huicheng Technology to pair the bluetooth serial port transmission
shell脚本
快解析结合泛微OA
leetcode 剑指 Offer 48. 最长不含重复字符的子字符串
hcip06 ospf特殊区域综合实验
快解析结合用友时空
A near-perfect Unity full-platform hot update solution
Kotlin value class - value class
随机推荐
leetcode 剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
利用R语言读取csv文件入一个数据框,然后查看各列的属性。
宝塔搭建DM企业建站系统源码实测
水电表预付费系统
Re18:读论文 GCI Everything Has a Cause: Leveraging Causal Inference in Legal Text Analysis
Detailed description of iperf3 parameter options
【 HMS core 】 【 】 the FAQ HMS Toolkit collection of typical questions 1
MySQL Explain usage and parameter detailed explanation
Integral Topic Notes - Path Independent Conditions
CSDN21天学习挑战赛
2022/07/29 Study Notes (day19) Exception Handling
Shell系统学习之数组
A new generation of free open source terminal tool, so cool
Apache DolphinScheduler新一代分布式工作流任务调度平台实战-上
C# 之 $ – 字符串内插
Unreal Engine Graphic Notes: could not be compiled. Try rebuilding from source manually. Problem solving
企业数字化建设,自研还是采购?
Determine whether a tree is a complete binary tree - video explanation!!!
leetcode 剑指 Offer 10- I. 斐波那契数列
元宇宙改变人类工作模式的四种方式