Flask路由和HTTP请求方式处理

路由

使用route()装饰器将函数绑定到URL。

@app.route('/')
def index():
    return 'Index Page'

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

您也可以将URL的一部分动态化并将多个规则附加到函数

变量规则

您可以通过使用标记部分向URL添加变量部分 <variable_name>。然后,您的函数将接收<variable_name> 作为关键字参数。或者,您可以使用转换器指定参数的类型<converter:variable_name>

@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

@app.route('/path/<path:subpath>')
def show_subpath(subpath):
    # show the subpath after /path/
    return 'Subpath %s' % subpath

转换器类型:

类型说明
string(默认值)接受任何没有斜杠的文本
int接受正整数
float接受正浮点值
path可接受字符串或者带斜杠的文本
uuid接受UUID字符串

URL构建

路由生成:{{ url_for(“模块名.视图名”) }}
url重定向: redirect(‘/home/login’)
redirect(url_for(“home.home_login”))

HTTP方法

默认情况下,路由仅响应get请求,可以使用route()装饰器中methods参数来处理不同的HTTP方法

from flask import request

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return do_the_login()
    else:
        return show_the_login_form()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值