【问题标题】:Flask session variable cannot be shared between functionsFlask 会话变量不能在函数之间共享
【发布时间】:2020-05-14 23:12:20
【问题描述】:

变量session['article']好像不能在函数之间共享,用下面的代码,我不明白为什么。目标是从函数def game() 访问变量session['article'],以便能够通过变量messagegame.html 中呈现它。 这是我的 python Flask 后端:

from flask import Flask, render_template, session, request, redirect, flash
from getpage import getPage

app = Flask(__name__)

app.secret_key = b'TwIsTeR@9458'

@app.route('/', methods=['GET','POST'])
def index():
    return render_template('index.html', message="Bonjour, monde !")

@app.route('/new_game', methods=['GET','POST'])
def new_game():  
    if request.method == 'POST':
        session['article'] = request.form['name']
        return redirect(url_for('game'))

@app.route('/game', methods=['GET','POST'])
def game():    
    d = session['article']
    return render_template('game.html', message=d)

# récupération du titre
# 
# Si vous définissez de nouvelles routes, faites-le ici

if __name__ == '__main__':
    app.run(debug=True)

这是我的index.html,如下:

<!DOCTYPE html>
<html lang="fr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="/static/style.css">
    <title>Tous les chemins mènent à la philosophie</title>
  </head>
  <body>
    {% block body %}
      {# Début du bloc "body", dont vous devez modifier le contenu #}
      <p>{{ message }}</p>
      <form action="/new_game" method="post">
        <input type="text" id="name" name="name" required minlength="4" maxlength="8" size="10">
        <input type="submit" name="submit_button" value="valider">
      </form>
      {# Fin du bloc "body" #}
    {% endblock %}
  </body>
</html>

还有我的game.html:

<!DOCTYPE html>
<html lang="fr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="/static/style.css">
    <title>Game rendering</title>
  </head>
  <body>
        {% extends "index.html" %}
          {% block body %}
          {{ message }}
        {% endblock %}
  </body>
</html>

点击“验证器”按钮后,我收到以下消息:

KeyError
KeyError: 'article'

Traceback (most recent call last)
File "/opt/anaconda3/lib/python3.7/site-packages/flask/app.py", line 2463, in __call__
return self.wsgi_app(environ, start_response)
File "/opt/anaconda3/lib/python3.7/site-packages/flask/app.py", line 2449, in wsgi_app
response = self.handle_exception(e)
File "/opt/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1866, in handle_exception
reraise(exc_type, exc_value, tb)
File "/opt/anaconda3/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/opt/anaconda3/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "/opt/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/opt/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/opt/anaconda3/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/opt/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/opt/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/twister/Desktop/MesCours/INF344HTTPWEB/TP2 à rendre/philosophie/philosophie.py", line 26, in game
d = session['article']
File "/opt/anaconda3/lib/python3.7/site-packages/werkzeug/local.py", line 378, in <lambda>
__getitem__ = lambda x, i: x._get_current_object()[i]
File "/opt/anaconda3/lib/python3.7/site-packages/flask/sessions.py", line 84, in __getitem__
return super(SecureCookieSession, self).__getitem__(key)
KeyError: 'article'

【问题讨论】:

    标签: python session flask


    【解决方案1】:

    我找到了解决问题的方法: return redirect(url_for('game')) 是错误的,而是我输入了 return redirect('/game')。我从def game() 中删除了d = session['article']message = d。最后,我将{{session.article}} 保留在我的“game.html”中。

    就是这样。 谢谢

    【讨论】:

      猜你喜欢
      • 2014-08-15
      • 1970-01-01
      • 2014-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-09
      相关资源
      最近更新 更多