V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Gescript
V2EX  ›  Flask

模板变量传递一直失败 没看出来问题在哪里

  •  1
     
  •   Gescript · 2016-07-27 15:16:26 +08:00 · 2666 次点击
    这是一个创建于 2832 天前的主题,其中的信息可能已经有所发展或是发生改变。
    #python
    from flask import Flask,render_template,request

    app = Flask(__name__)

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

    @app.route('/')
    def User_Agent():
    UserAgentString = request.headers.get('User-Agent')
    return render_template('index.html', UserAgentString=UserAgentString)
    if __name__ == '__main__':
    app.run(debug=True)

    #HTML

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <title>Cololi's blog</title>
    <link href="/static/css/bootstrap.min.css" rel="stylesheet">
    <link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
    </head>
    <body background="/static/BGP.jpg">
    <ul><li><strong>User-Agent: </strong>{{ User_AgentString }}</li></ul>
    </body>
    </html>
    12 条回复    2016-07-28 09:47:20 +08:00
    Gescript
        1
    Gescript  
    OP
       2016-07-27 15:17:09 +08:00
    debug 正常 HTTP 200
    lxy
        2
    lxy  
       2016-07-27 15:19:53 +08:00
    变量名没写对
    armoni
        4
    armoni  
       2016-07-27 15:23:23 +08:00
    你页面里的变量是 User_AgentString , 你服务端的变量是 UserAgentString ,名字对不上
    Gescript
        6
    Gescript  
    OP
       2016-07-27 15:28:38 +08:00
    oroge
        7
    oroge  
       2016-07-27 15:34:11 +08:00 via iPad
    为什么有两个 @app.route ('/')?
    Gescript
        8
    Gescript  
    OP
       2016-07-27 15:36:35 +08:00
    @oroge 忘记删掉了。。
    cloverstd
        9
    cloverstd  
       2016-07-27 15:37:32 +08:00
    你在 / 上绑定了俩个 view ,说明你访问的是第一个
    Gescript
        10
    Gescript  
    OP
       2016-07-27 15:43:10 +08:00
    @cloverstd
    @app.route('/')
    def index():
    return render_template('index.html')

    def User_Agent():
    UserAgentString = request.headers.get('User-Agent')
    return render_template('index.html', UserAgentString=UserAgentString)
    这样写也不行的样子一直不能在 html 上显示
    cloverstd
        11
    cloverstd  
       2016-07-27 15:49:45 +08:00
    @app.route('/')
    def User_Agent():
    UserAgentString = request.headers.get('User-Agent')
    return render_template('index.html', UserAgentString=UserAgentString)
    qq7171891
        12
    qq7171891  
       2016-07-28 09:47:20 +08:00
    错误 1 :一个 @app.route('/') 不能绑定两个函数。
    解决办法:可以用一个函数,里面加 if ,根据传入的参数加载不同逻辑。

    错误 2 :变量名用错,后端传的是 UserAgentString ,前端又是 User_AgentString ,不一致。
    解决办法:统一命名
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5469 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 08:53 · PVG 16:53 · LAX 01:53 · JFK 04:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.