这是我参与8月更文挑战的第10天,活动详情查看:8月更文挑战
前文创建了一个简单的flask的应用,本文就以上文Flask入门的代码的基础在上面修改并进行讲解flask中的路由。
route()装饰器
flask中的route()装饰器告诉Flask哪个URL才能触发我们的函数。route()中有三个参数:
- rule:string类型的URL地址。
- endpoint:“endpoint” 是用于确定 Request 该由代码的哪个逻辑单元来处理。 通常情况下,endpoint 只是一个视图函数的名称。
- options:是一个请求方法的列表。如:GET、POST、PUT等,默认为GET。
在route()下定义一个函数,该函数名也是用来给特定函数生成URLs,并且返回我们想要显示在用户浏览器上的信息。
路由
现代的web应用几乎都有其特定的URLs,这方便人们记忆。具体是通过route()装饰器实现。例子如下:
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello():
return 'Hello World'
当然这只是最基础的路由,你可以进一步利用路由进行传参,比如:
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
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 'Post %d' % post_id
上述例子中,<username>和<int:post_id>是可以作为参数传入函数的字段,具体的格式<converter:variable_name>其中converter是类型,后面是参数名。
存在如下转换器:
唯一URLs/重定向行为:
Flask 的 URL 规则是基于 Werkzeug 的 routing 模块。 该模块背后的想法是基于 Apache 和早期的 HTTP 服务器定下先例确保优雅和唯一的 URL。
例子:
@app.route('/projects/')
def projects():
return 'The project page'
@app.route('/about')
def about():
return 'The about page'
虽然它们看起来确实相似,但它们结尾斜线的使用在 URL 定义 中不同。 第一种情况中,规范的 URL 指向 projects 尾端有一个斜线。 这种感觉很像在文件系统中的文件夹。访问一个结尾不带斜线的 URL 会被 Flask 重定向到带斜线的规范URL去。
然而,第二种情况的 URL 结尾不带斜线,类似 UNIX-like 系统下的文件的路径名。 访问结尾带斜线的 URL 会产生一个 404 “Not Found” 错误。
当用户访问页面时忘记结尾斜线时,这个行为允许关联的 URL 继续工作, 并且与 Apache 和其它的服务器的行为一致。另外,URL 会保持唯一,有助于避免搜索引擎索引同一个页面两次。
多URL的路由
一个函数上可以设施多个URL路由规则
@app.route('/hello')
@app.route('/hello/<name>')
def hello(name=None):
if name is None:
name = 'World'
return 'Hello %s' % name
上面这个例子接受两种URL规则,一个带参数的一个不带参数的,然后下面函数根据函数规则返回不同的值。