Created
August 30, 2016 15:37
-
-
Save iffy/8fce34b064c02e05ee7f764fb8d27aa3 to your computer and use it in GitHub Desktop.
This file contains 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
import time | |
from uuid import uuid4 | |
from twisted.internet import threads | |
from crochet import run_in_reactor, setup | |
setup() | |
import structlog | |
logger = structlog.get_logger() | |
from flask import Flask, session, g, request | |
app = Flask(__name__) | |
structlog.configure( | |
processors=[ | |
structlog.processors.KeyValueRenderer( | |
key_order=['reqid', 'event'], | |
), | |
], | |
context_class=structlog.threadlocal.wrap_dict(dict), | |
) | |
def run_async(func, *args, **kwargs): | |
""" | |
Run a function in another thread. | |
""" | |
@run_in_reactor | |
def run_func(): | |
# XXX Set up the logger so that you can tie what | |
# happens inside this function back to the request | |
# that started it. | |
d = threads.deferToThread(func, *args, **kwargs) | |
def eb(err): | |
logger.exception('error processing async func', exc_info=err) | |
return | |
d.addErrback(eb) | |
run_func() | |
@app.before_request | |
def before_request(): | |
log = logger.new(reqid=str(uuid4())) | |
log.bind(path=request.path) | |
g.user_id = session.get('user_id', None) | |
if g.user_id: | |
log.bind(user_id=g.user_id) | |
def send_an_email(email): | |
# pretend to send an email | |
logger.info('preparing to send an email', email=email) | |
time.sleep(2) | |
logger.info('email sent', email=email) | |
@app.route('/') | |
def root(): | |
logger.info('request started') | |
run_async(send_an_email, 'foo@foo.com') | |
return 'I sent an email' | |
app.run('127.0.0.1', 5000) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment