烧瓶参数在render_template [英] flask argument in render_template

查看:175
本文介绍了烧瓶参数在render_template的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为hello函数参数的名字被赋值为None,但是为什么render_template中的名字会在url中提供名称的值呢?基本上我的问题是Python如何知道哪个名字是None,并且在URL中给出了哪个名字?

  from flask import render_template 
@ app.route('/ hello')
@ app.route('/ hello /< name>)
def hello(name = None):
return render_template 'hello.html',name = name)

hello.html是:

 <!doctype html> 
< title>来自Flask的问候< / title>
{%if name name%}
< h1> Hello {{name}}!< / h1>
{%else%}
< h1> Hello,World!< / h1>
{%endif%}


解决方案

一个框架,后台有很多代码(特别是 werkzeug ),它会处理所有的请求,然后调用你的view函数,然后准备一个完整的响应。所以答案是,Python不知道URL,但Flask使用名称来调用你的视图函数(覆盖默认的 None )或者没有它。
$ b

name 视图函数的变量被传递给同名的模板。这是这两行中的 name s:

  return render_template 'hello.html',name = name)


The name as an argument to hello function is assigned None, but why the name in render_template will take the value of the name if provided in the url? Basically my question is how Python knows which name is None and which name is given in the url?

 from flask import render_template
 @app.route('/hello')
 @app.route('/hello/<name>')
 def hello(name=None):
      return render_template('hello.html', name=name)

the hello.html is:

<!doctype html>
<title>Hello from Flask</title>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello, World!</h1>
{% endif %}

解决方案

Flask is a framework and there is a lot of code behind the scenes (especially werkzeug) which does all the request processing, then it calls your view function and then it prepares a complete response.

So the answer is, that Python does not know the URL, but Flask does and calls your view function either with the name (overwriting the default None) or without it.

The name variable of the view function is passed to the template under the same name. That are the two names in this line:

return render_template('hello.html', name=name)

这篇关于烧瓶参数在render_template的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆