flask系列---反转函数url_for与重定向redirect(二)

50 篇文章 23 订阅

flask系列---第一个Flask程序、DEBUG模式及URL传参(一)


在flask中,我们导入url_forredirect两个函数。

from flask import Flask, url_for, redirect   

首先看url_for,简单来说,这个函数接受视图函数的名字(字符串形式)作为参数,返回视图函数对应的url,例如:

@app.route('/')
def hello_world():
    print(url_for('index'))  # /index/
    return 'Hello World'

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

hello_world函数中使用print(url_for('index')),将会打印出/index/
有传参的视图函数怎么办?同样将函数名字符串作为第一个参数,将参数以key=value的形式写在后面,如:

@app.route('/')
def hello_world():
    print(url_for('hello',name='harp'))
    return 'Hello World'

@app.route('/<name>/')
def hello(name):
    return 'Hello %s' % name

打印结果为/harp/


redirect则更简单,功能就是跳转到指定的url,大部分情况下,我们都是和url_for一起使用的,例如:

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


@app.route('/<name>/')
def hello(name):
    if name == 'Harp':
        return 'Hello %s' % name
    else:
        return redirect(url_for('hello_world'))

hello这个视图函数中,如果url传入的参数是Harp(即请求的网址是http://127.0.0.1:5000/Harp/),则返回'Hello Harp',其他情况则重定向到hello_world这个视图函数对应的网址'/'


flask系列---render_template渲染模板及jinja2(三)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值