在请求上下文之外设置Jinja环境全局变量

时间:2017-05-25 12:19:23

标签: python flask

我有一个名为generate_csrf_token的函数,它位于包commons.formsecurity中,包含以下代码。

import random
import string
from flask import session


def generate_csrf_token():
    if '_csrf_token' not in session:
        state = ''.join(random.choice(string.ascii_uppercase + string.digits)
                        for x in xrange(32))
        session['_csrf_token'] = state
    return session['_csrf_token']

我在create_app函数中调用它。

from flask import Flask
from routes_manager import configure_blueprints
from error_handling import configure_error_handling
from flask import session
from flask.ext.session import Session
from commons.formsecurity import generate_csrf_token

def create_app():
    """Create the Flask App"""
    app = Flask(__name__)
    app.secret_key = 'lalalalalala'
    app.jinja_env.globals['csrf_token'] = generate_csrf_token()
    configure_blueprints(app)
    configure_error_handling(app)
    return app

从main.py

调用create_app
from app import create_app

app = create_app()

"""Run the clients"""
if __name__ == '__main__':

    app.run(debug=True)

当我运行Flask应用程序时。我收到以下错误。

ERROR    2017-05-25 12:12:50,720 wsgi.py:263] 
Traceback (most recent call last):
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 240, in Handle
    handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 299, in _LoadHandler
    handler, path, err = LoadObject(self._handler)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 85, in LoadObject
    obj = __import__(path[0])
  File "C:\Code\App-Engine\cfc-melbourne-website\main.py", line 3, in <module>
    app = create_app()
  File "C:\Code\App-Engine\cfc-melbourne-website\app\__init__.py", line 12, in create_app
    app.jinja_env.globals['csrf_token'] = generate_csrf_token()
  File "C:\Code\App-Engine\cfc-melbourne-website\app\commons\formsecurity.py", line 7, in generate_csrf_token
    if '_csrf_token' not in session:
  File "lib\werkzeug\local.py", line 379, in <lambda>
    __contains__ = lambda x, i: i in x._get_current_object()
  File "lib\werkzeug\local.py", line 306, in _get_current_object
    return self.__local()
  File "lib\flask\globals.py", line 37, in _lookup_req_object
    raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.

在哪里拨打以下内容的最佳地点

app.jinja_env.globals['csrf_token'] = generate_csrf_token()

1 个答案:

答案 0 :(得分:0)

如果你没有调用generate_csrf_token()函数,而是存储对函数的引用,你可以在Jinja模板中调用它(这将在请求可用的上下文中)。

所以替换

app.jinja_env.globals['csrf_token'] = generate_csrf_token()

使用

app.jinja_env.globals['csrf_token'] = generate_csrf_token

在您的模板中,使用:

<input name=_csrf_token type=hidden value="{{ csrf_token() }}">