Created
May 25, 2011 12:36
-
-
Save namlook/990874 to your computer and use it in GitHub Desktop.
flask, celery and global g
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask | |
app = Flask(__name__) | |
from flaskext.celery import Celery | |
celery = Celery(app) | |
def process_global(glob_obj): | |
g.db = app.config['MONGO_DATABASE'] # get the unpickle-izable database | |
for k,v in glob_obj.iteritems(): | |
setattr(g, k, v) | |
@app.before_request | |
def before_request(): | |
g.db = app.config['MONGO_CONNECTION'][settings.DATABASE_NAME] | |
g.user = ... # do stuff | |
# here we define all global variables for "celeried" functions | |
# everything in the dict should be pickle-izable | |
g.glob_obj = {} | |
g.glob_obj['user'] = user |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from myapp import celery | |
from myapp import process_global | |
from flask import Module | |
views = Module(__name__) | |
# | |
# let's see how it works | |
# | |
def foo(bar, baz): | |
obj = g.db... # do stuff | |
@celery.task(name="myapp.foo") | |
def queued_foo(glob_obj, args): | |
process_global(glob_obj) | |
return foo(*args) | |
# let's use our "celeried" function foo | |
@views.route('/foo') | |
def view_foo(): | |
bar, baz = 1,2 | |
# all arguments passed should be pickle-izable | |
queued_foo.apply_sync([g.obj_glob, (bar, baz)]) | |
return "in process" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment