flask路由与视图映射与传参规则

  1. 1. 一、路由与视图映射
  2. 2. 二、传参规则
  3. 3. 三、GET方式传参

一、路由与视图映射

使用 route()装饰器来把函数绑定到 URL:

1
2
3
4
5
6
7
@app.route('/')
def index():
return 'Index Page'

@app.route('/hello')
def hello():
return 'Hello, World'

二、传参规则

摘自flask中文文档:

通过把 URL 的一部分标记为 就可以在 URL 中添加变量。标记的 部分会作为关键字参数传递给函数。通过使用 converter:variable_name>,可以选择性的加上一个转换器,为变量指定类型,记得函数中也要传参。请看下面的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from markupsafe import escape

@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return f'User {escape(username)}'
#return 'User %s' % username
@app.route('/post/<int:post_id>')
def show_post(post_id):
# show the post with the given id, the id is an integer
return f'Post {post_id}'

@app.route('/path/<path:subpath>')
def show_subpath(subpath):
# show the subpath after /path/
return f'Subpath {escape(subpath)}'

其中:escape函数是为了防止用户传入恶意的数据

转换器类型:

string (缺省值) 接受任何不包含斜杠的文本
int 接受正整数
float 接受正浮点数
path 类似 string ,但可以包含斜杠
uuid 接受 UUID 字符串

三、GET方式传参

使用

1
from flask import request

导入相应库

用接受request.args.get(self,key,default,type)

key为变量名,default为默认访问页面时的传参值,type指定类型

例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/')
def index_page():
return 'index page'

@app.route('/book')
def book_page():
page = request.args.get("page",default=1,type=int)
return f'第{page}页'

if __name__ == '__main__':
app.run();