flask で gevent 使用時に greenlet に g が引き継げない時
copy_current_request_context
の AppContext版。
普通にやると flask.g
が空になっちゃうので。
usage
from flask import g
@copy_current_app_context
def hoge():
print g.__dict__
gevent.spawn(hoge)
用途とかはこのへんを参考に。
http://flask.pocoo.org/docs/0.10/api/#flask.copy_current_request_context
copy_current_app_context.py
import copy
import flask
from functools import update_wrapper
def copy_current_app_context(f):
top = flask._app_ctx_stack.top
if top is None:
raise RuntimeError('This decorator can only be used at local scopes '
'when a app context is on the stack. For instance within '
'view functions.')
reqctx = copy.copy(top)
def wrapper(*args, **kwargs):
with reqctx:
return f(*args, **kwargs)
return update_wrapper(wrapper, f)