zoukankan      html  css  js  c++  java
  • 有关flask的endpoint

    前情提要:

    如果你使用google,搜索关键字“flask的endpoint”,前五个链接中,一个是英文的,另外四个是中文的,而后者无不是前者的翻译版本。但由于英文原版的答案已经有6年的历史了,所以如果你想尝试,里面的例子其实是根本运行不出来的。

    这是我写这篇的原因。

    个人理解:

    如果把答案中的例子稍作修改:

    第一个例子

    @app.route('/')
    def index():
        return redirect(url_for('cesuo', name='shit'))
    
    @app.route('/cesuo/<name>')
    def wc(name):
        return 'Hello, {0}!'.format(name)

    你进入界面,然后使用url_for函数,redirect一个叫做“cesuo/shit”的地方,尝试运行,会报错。

    如何正确?两个方法,

    第一个方法(第二个例子):

    把wc函数,改称中文拼音,cesuo。

    @app.route('/')
    def index():
        return redirect(url_for('cesuo', name='shit'))
    
    @app.route('/cesuo/<name>')
    def cesuo(name):
        return 'Hello, {0}!'.format(name)

    第二个方法(第三个例子):

    把url_for的参数,改称wc。

    @app.route('/')
    def index():
        return redirect(url_for('wc', name='shit'))
    
    @app.route('/cesuo/<name>')
    def wc(name):
        return 'Hello, {0}!'.format(name)

    由此,我们能够推断,使用url_for拼接,然后再redirect,会直接奔着函数的名字走(cesuo对cesuo,wc对wc),名字不一样,就找不到位置。

    这时,我们可以在第一个例子的wc函数装饰处,加入endpoint=“cesuo”,即:

    @app.route('/')
    def index():
        return redirect(url_for('cesuo', name='shit'))
    
    @app.route('/cesuo/<name>',endpoint="cesuo")
    def wc(name):
        return 'Hello, {0}!'.format(name)

    这意味着,url_for的参数,其实是找endpoint的,默认是目标view function的函数名,如果找不到,就报错,如果加入endpoint参数,即使你的route地址和函数名瞎改,也能找到厕所,例如:

    @app.route('/')
    def index():
        return redirect(url_for('cesuo', name='shit'))
    
    @app.route('/what_are_you_doing/<name>',endpoint="cesuo")
    def wc(name):
        return 'Hello, {0}!'.format(name)
  • 相关阅读:
    数据的图表统计highcharts
    spring文件的上传和下载
    项目随笔@Service("testService")-------第二篇
    spring的四种数据源配置
    spring之interceptor篇
    spring过滤器篇
    SecurityManager篇
    Apache shiro篇
    日期工具方法
    定时器CronExpression配置说明详解
  • 原文地址:https://www.cnblogs.com/kykai/p/13456233.html
Copyright © 2011-2022 走看看