Flask路由规则都是基于Werkzeug的路由模块的,它还提供了很多强大的功能。

两种添加路由的方式

方式一:
@app.route('/xxxx') # @decorator
def index():
return "Index"
方式二:
def index():
return "Index"
app.add_url_rule('/xxx', "n1", index) #n1是别名

@app.route和app.add_url_rule参数

@app.route和app.add_url_rule参数:
rule, URL规则
view_func, 视图函数名称
defaults=None, 默认值,当URL中无参数,函数需要参数时,使用defaults={'k':'v'}为函数提供参数
endpoint=None, 名称,用于反向生成URL,即: url_for('名称')
methods=None, 允许的请求方式,如:["GET","POST"] strict_slashes=None, 对URL最后的 / 符号是否严格要求,
如:
@app.route('/index',strict_slashes=False),
访问 http://www.xx.com/index/ 或 http://www.xx.com/index均可
@app.route('/index',strict_slashes=True)
仅访问 http://www.xx.com/index
redirect_to=None, 重定向到指定地址
如:
@app.route('/index/<int:nid>', redirect_to='/home/<nid>')

def func(adapter, nid):
return "/home/888"
@app.route('/index/<int:nid>', redirect_to=func)

举例使用

# ============对url最后的/符号是否严格要求=========
@app.route('/test',strict_slashes=True) #当为True时,url后面必须不加斜杠
def test():
return "aaa"
@app.route('/test',strict_slashes=False) #当为False时,url上加不加斜杠都行
def test():
return "aaa" @app.route("/json_test/<int:age>" ,defaults={'age':66})
def json_test(age):
ret_dic = {'name': 'xiaowang', 'age': age}
return jsonify(ret_dic) # 转换json形式

带参数的路由

@app.route('/hello/<name>')
def hello(name):
return 'Hello %s' % name @app.route('/hello/<name>_<age>_<sex>') # 多个参数
def hello(name,age,sex):
return 'Hello %s,%s,%s' %(name,age,sex)

在浏览器的地址栏中输入http://localhost:5000/hello/Joh,你将在页面上看到”Hello Joh”的字样。

URL路径中/hello/后面的参数被作为hello()函数的name参数传了进来。

多个参数

# 动态路由参数
@app.route("/json_param/<int:age>" ,strict_slashes=False)
def json_param(age):
ret_dic = {'name': 'xiaowang', 'age': age}
return jsonify(ret_dic)

endpoint

当请求传来一个url的时候,会先通过rule找到endpoint(url_map),然后再根据endpoint再找到对应的view_func(view_functions)。通常,endpoint的名字都和视图函数名一样。
实际上这个endpoint就是一个Identifier,每个视图函数都有一个endpoint,
当有请求来到的时候,用它来知道到底使用哪一个视图函数
endpoint可以解决视图函数重名的情况

Flask中装饰器多次使用
# 验证用户装饰器
def wrapper(func):
@wraps(func)
def inner(*args, **kwargs):
if not session.get("user_info"):
return redirect("/login")
ret = func(*args, **kwargs)
return ret
return inner @app.route("/login", methods=("GET", "POST"))
def login():
# 模板渲染
# print(request.path)
# print(request.url)
# print(request.headers)
if request.method == "GET":
print(request.args.get("id"))
text_tag = "<p>你看见了吗test:<input type='text' name='test'></p>"
text_tag = Markup(text_tag)
return render_template("login.html", msg=text_tag) # sum = add_sum)
else: # print(request.form)
# print(request.values.to_dict()) # 这个里面什么都有,相当于body
# print(request.json) # application/json
# print(request.data)
username = request.form.get("username")
password = request.form.get("password")
if username == "alex" and password == "123":
session["user_info"] = username
# session.pop("user_info") #删除session
return "登录成功"
else:
return render_template("login.html", msg="用户名或者密码错误") # endpoint可以解决视图函数重名的情况
@app.route("/detail", endpoint="detail")
@wrapper # f = route(wrapper(detail))
def detail():
print(url_for("detail"))
return render_template("detail.html", **STUDENT) @app.route("/detail_list", endpoint="detail_list")
@wrapper # f = route(wrapper(detail_list))
def detail_list():
return render_template("detail_list.html", stu_list=STUDENT_LIST) @app.route("/detail_dict")
def detail_dict():
if not session.get("user_info"):
return redirect("/login")
return render_template("detail_dict.html", stu_dict=STUDENT_DICT)

反向生成URL: url_for

endpoint("name")   #别名

@app.route('/index',endpoint="xxx")  #endpoint是别名
def index():
v = url_for("xxx")
print(v)
return "index"

静态文件位置

一个Web应用的静态文件包括了JS, CSS, 图片等,Flask的风格是将所有静态文件放在”static”子目录下。并且在代码或模板中,使用url_for('static')来获取静态文件目录

app = Flask(__name__,template_folder='templates',static_url_path='/xxxxxx')

<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
<div class="page">
{% block body %}
{% endblock %}
</div>

两个常用函数

@app.route("/bo")
def bo():
# return render_template("bo.html")
return send_file("s1.py") # 发送文件(可以是图像或声音文件) @app.route("/json_test/<int:age>" ,defaults={'age':66})
def json_test(age):
ret_dic = {'name': 'xiaowang', 'age': age}
return jsonify(ret_dic) # 转换json形式,帮助转换为json字符串, 并且设置响应头Content-Type: application/json

  

Flask 学习(三)路由介绍的更多相关文章

  1. Flask 学习之 路由

    一.路由的基本定义 # 指定访问路径为 demo1 @app.route('/demo1') def demo1(): return 'demo1' 二.常用路由设置方式 @app.route('/u ...

  2. flask 学习(三)

    继续flask的学习.尝试了使用程序context这一部分: 而在hello.py文档的旁边发现新出现了hello.pyc,看来运行过程中也被编译成字节码文件了,也不清楚是在哪个步骤的,留着后面研究. ...

  3. Jenkins学习三:介绍一些Jenkins的常用功能

    Jenkins其实就是一个工具,这个工具的作用就是调用各种其他的工具来达成你的目的. 1.备份.迁移.恢复jenkins 首先找到JENKINS_HOME,因为Jenkins的所有的数据都是以文件的形 ...

  4. Flask学习 三 web表单

    web表单 pip install flask-wtf 实现csrf保护 app.config['SECRET_KEY']='hard to guess string' # 可以用来存储框架,扩展,程 ...

  5. flask学习(三):flask入门(URL)

    一. flask简介 flask是一款非常流行的python web框架,出生于2010年,作者是Armin Ronacher,本来这个项目只是作者在愚人节的一个玩笑,后来由于非常受欢迎,进而成为一个 ...

  6. Spring整合Jms学习(三)_MessageConverter介绍

    1.4     消息转换器MessageConverter MessageConverter的作用主要有双方面,一方面它能够把我们的非标准化Message对象转换成我们的目标Message对象,这主要 ...

  7. Flask 学习(三)模板

    Flask 学习(三)模板 Flask 为你配置 Jinja2 模板引擎.使用 render_template() 方法可以渲染模板,只需提供模板名称和需要作为参数传递给模板的变量就可简单执行. 至于 ...

  8. Flask 学习(二)路由

    Flask  路由 在说明什么是 Flask 路由之前,详细阐述下 Flask “Hello World” 这一 最小应用的代码. Flask “Hello World” from flask imp ...

  9. Django基础学习三_路由系统

    今天主要来学习一下Django的路由系统,视频中只学了一些皮毛,但是也做下总结,主要分为静态路由.动态路由.二级路由 一.先来看下静态路由 1.需要在project中的urls文件中做配置,然后将匹配 ...

  10. Flask 学习(一)简单介绍

    Flask介绍(轻量级的框架) Flask是一个基于Python开发并且依赖jinja2模板和Werkzeug WSGI服务的一个微型框架,对于Werkzeug本质是Socket服务端,其用于接收ht ...

随机推荐

  1. C语言结构体变量字节对齐问题总结

    结构体字节对齐 在用sizeof运算符求算某结构体所占空间时,并不是简单地将结构体中所有元素各自占的空间相加,这里涉及到内存字节对齐的问题.从理论上讲,对于任何 变量的访问都可以从任何地址开始访问,但 ...

  2. Nuxt 学习资料

    Nuxt 学习资料 网址 官方网站 https://zh.nuxtjs.org/guide/installation

  3. 搭建unity客户端

    1.新建个unity的项目ChatClient 2.在unity的Main Camera下挂载个脚本PhotonServerEngine做为与服务器端通信的脚本 3.在PhotonServerEngi ...

  4. 27、shutil文件操作、xml、subprocess运行子程序模块(了解)

    一.shutil模块(了解):高级的文件.文件夹.压缩包处理模块. import shutil # shutil.copyfileobj(fsrc, fdst[, length]),将文件内容拷贝到另 ...

  5. extern与头文件(*.h)的区别和联系

    原文网址为:http://lpy999.blog.163.com/blog/static/117372061201182051413310/ 个人认为有一些道理:所以转过来学习了. 用#include ...

  6. 实现:API实现创建用户并且添加至管理员

    参考文章:https://www.cnblogs.com/17bdw/p/6790197.html#_label0 利用的API函数: 1.NetUserAdd 2.NetLocalGroupAddM ...

  7. HttpClient学习研究---第二章:连接管理

    第二章.Connection management连接管理2.1. 2.1.Connection persistence连接持久性The process of establishing a conne ...

  8. 22-1 web传输视频 Opencv+usb摄像头 树莓派+Flask实现视频流媒体WEB服务器

    第一篇 讲解原理 https://blog.miguelgrinberg.com/post/video-streaming-with-flask 第二篇 加入多线程可以直接用 https://gith ...

  9. Bounding Box回归

    简介 Bounding Box非常重要,在rcnn, fast rcnn, faster rcnn, yolo, r-fcn, ssd,到今年cvpr最新的yolo9000都会用到. 先看图 对于上图 ...

  10. MongoDB 实现多key group by 并实现 having

    1.group by多个key db.testcol.aggregate(    {"$group": {_id:{card:"$card",account:& ...