1.路由
使用route()装饰器把一个函数绑定到URL上,可以动态的构造URL的特定部分,也可在一个函数上附加多个规则。
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello():
return 'Hello World'
2.变量规则
用<variable_name>
给URL添加变量部分,这部分作为命名参数传递到函数。规则可用<converter:variable_name>
指定转换器
@app.route('/user/<username>')
def show_user_profile(username):
return 'User %s' %username
@app.route('/post/<int:post_id>')
def show_post(post_id):
return 'Post %d' %post_id
转换器 | 接受参数 |
---|---|
string | 接受任何没有斜杠“/”文本(默认) |
int | 整型 |
float | 同int一样,但是还包括浮点数 |
path | 和string相似,但也接受斜杠“/” |
uuid | 只接受UUID字符串 |
any | 可以制定多种路径,但是需要传递参数 |
@app.route('/<any(a,b):page_name>/')
访问/a/和/b/都符合这个规则,page_name对应的就是a或b。
3.唯一URL和重定向行为
以下两个为例:
@app.route('/projects/')
def projects():
return 'The project page'
@app.route('/about')
def about():
return 'The about page'
它们结尾斜线的使用在 URL 定义 中不同。 第一种情况中,指向 projects 的规范 URL 尾端有一个斜线。这种感觉很像在文件系统中的文件夹。访问一个结尾不带斜线的 URL 会被 Flask 重定向到带斜线的规范 URL 去。
然而,第二种情况的 URL 结尾不带斜线,类似 UNIX-like 系统下的文件的路径名。访问结尾带斜线的 URL 会产生一个 404 “Not Found” 错误。
4.构造URL
url_for()
可以给指定的函数构造URL。
接受函数名作为第一个参数,也接受对应URL规则的变量部分的命名参数。未知变量会添加到URL末尾作为查询参数。
环境局部变量
一段依赖请求对象的代码,因没有请求对象而无法运行。
解决方案:自行创建一个请求对象,并绑定到环境中。单元测试中最简单的使用
test_request_context()
环境管理器
from flask import request
with app.test_request_context('/hello',method='POST'):
assert request.method=='POST'
assert request.path=='/hello'
另外一种可能,传递整个WSGI环境request_context()方法
from flask import request
with app.request_context(environ):
assert request.method=='POST'
5.重定向和错误
redirect(location,code=301)
函数把用户重新定向到其他地方,和url_for()
结合使用。abort()
放弃请求并返回错误码
from flask import abort,url_for,redirect
@app.route('/')
def index():
retuen redirect(url_for('login'))
@app.route('/login')
def login():
abort(401)
this_is_never_execute()
定制错误页面,使用errorhandler()
装饰器
from flask import render_template
@app.errorhandler(404)
def page_not_found(error):
return render_template('page_not_found.html'),404
实例
from flask import Flask,request,redirect,abort,url_for,render_template
app=Flask(__name__)
app.config.from_object("config")
@app.route('/people/')
def people():
name=request.args.get("name")
if not name:
return redirect(url_for("login"))
user_agent=request.headers.get("User-Agent")
return "Name:{0};UA:{1}".format(name,user_agent)
@app.route('/login/',methods=["GET","POST"])
def login():
if request.method=="POST":
user_id=request.form.get("user_id")
return "User:{} login".format(user_id)
else:
return render_template('login.html')
@app.route('/secret/')
def secret():
abort(401)
print('This is never execute!')
if __name__ == '__main__':
app.run()
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="../static/css/bootstrap.min.css" />
<title>登录</title>
</head>
<body>
<form class="form-inline" method="post">
<div class="form-group">
<lable>用户名</lable>
<input type="text" name="user_id" class="form-control" />
</div>
<div class="form-group">
<lable>密码</lable>
<input type="password" name="pw" class="form-control" />
</div>
<div class="form-group">
<input type="submit" class="form-control" value="登录" />
</div>
</form>
<script src="../static/js/jquery-3.3.1.min.js"></script>
<script src="../static/js/bootstrap.min.js"></script>
</body>
</html>
网友评论