Skip to content

Instantly share code, notes, and snippets.

@1st1
Last active August 29, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 1st1/10923339 to your computer and use it in GitHub Desktop.
Save 1st1/10923339 to your computer and use it in GitHub Desktop.
class Local:
def __getattr__(self, attr):
# finds 'attr' stored for the current Task.context_id
def __setattr__(self, attr, val):
# stores value for the current Task.context_id
local = Local()
@contextmanager
def trace(msg):
# ... time a code block, and store results
# somewhere
def get_traces(context_id):
# return accumulated traces for the current Task.context_id
class HttpProtocol(Protocol):
def connection_made(self, transport):
request_id = uuid.uuid4()
self._worker = asyncio.Task(self.on_request(),
context_id=request_id)
self._worker.add_done_callback(submit_traces, request_id)
def submit_traces(self, request_id):
traces = get_traces(request_id)
submit_traces_to_newrelic(traces)
@coroutine
def on_request(self):
local.transport_info = transport.get_extra_info(...)
with trace('http request pasing'):
request = yield from parse_request()
response = HttpResponse()
yield from self.dispatch_request(request, response)
@coroutine
def dispatch_request(self, request, response):
# ... route `request` & `response` objects to an
# http request handler
class DBConnection:
@coroutine
def query(self, query, **args):
with trace('db query'):
# bunch of `yield from`s to DB driver
class Template:
def render(self, *args):
with trace('template rendering'):
# some template engine stuff
ip = local.transport_info.remote_addr
# render user's IP address
# ...
return rendered_html
@app.route('/')
@coroutine
def index(request, response):
db = DBConnection()
result = yield from db.query('select 1')
html = template.render(result)
response.add_header('content-type', 'html')
return html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment