Skip to content

Instantly share code, notes, and snippets.

@allenyang79
Created February 22, 2018 09:38
Show Gist options
  • Save allenyang79/42e7e8e32209723f91dd6a039b495a12 to your computer and use it in GitHub Desktop.
Save allenyang79/42e7e8e32209723f91dd6a039b495a12 to your computer and use it in GitHub Desktop.
import time
import gevent
import gevent.monkey
from flask import Flask, copy_current_request_context, g, request, _request_ctx_stack
import logging
gevent.monkey.patch_all()
logging.basicConfig(level=0) # logging.DEBUG)
logger = logging.getLogger()
app = Flask(__name__)
@app.route('/')
def index():
ts = time.time()
ctx = _request_ctx_stack.top
ctx.ts = ts
logger.info('ts: %s', ctx.ts)
logger.info('ts: %s', getattr(ctx, 'ts', None))
gevent.spawn(copy_current_request_context(background_job))
# @copy_current_request_context
# def do_something():
# logger.info("oops")
# with open('now.ts', 'w') as fp:
# fp.write(str(time.time()))
#
#gevent.spawn(do_something)
# logger.info(glet)
# print(dir(glet))
# glet.join()
return "ok: %s" % ts
def background_job():
for i in range(0, 2):
logger.info("sleep...%s" % i)
gevent.sleep(1)
logger.info("done")
ctx = _request_ctx_stack.top
logger.info('ctx: %s', ctx)
logger.info('ts: %s', getattr(ctx, 'ts', None))
#logger.info(_request_ctx_stack)
#ctx = _request_ctx_stack.top
#logger.info(ctx)
#logger.info('ts: %s background', ctx.ts)
#logger.info("done, %s" % g.ts)
#logger.info(g)
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment