Skip to main content

Global request for aiohttp server

Project description

info:

Global request for aiohttp server

https://travis-ci.org/hellysmile/aiohttp_request.svg?branch=master https://img.shields.io/pypi/v/aiohttp_request.svg https://codecov.io/gh/hellysmile/aiohttp_request/branch/master/graph/badge.svg

Installation

pip install aiohttp_request

Usage

import asyncio

from aiohttp import web
from aiohttp_request import ThreadContext, middleware_factory, grequest, get_request


def thread():
    assert grequest['sense'] == 42


async def task():
    # grequest is `lazy` version of request
    assert grequest['sense'] == 42

    loop = asyncio.get_event_loop()
    # works for threads as well with ThreadContext
    await loop.run_in_executor(None, ThreadContext(thread))


async def hello(request):
    # get_request is on-demand function to get current request
    assert get_request() is request

    request['sense'] = 42

    # asyncio.Task is supported
    await asyncio.ensure_future(task())

    return web.Response(text="Hello, world")


app = web.Application(middlewares=[middleware_factory()])
app.add_routes([web.get('/', hello)])
web.run_app(app)

Python 3.7+ is required, there is no way to support older python versions!!!

Notes

The library relies on PEP 567 and its asyncio support

aiohttp-request works nicely with threads via contextvars_executor , no ThreadContext is needed

import asyncio

from aiohttp import web
from aiohttp_request import middleware_factory, grequest
from contextvars_executor import ContextVarExecutor


def thread():
    assert grequest['sense'] == 42


async def hello(request):
    request['sense'] = 42

    loop = asyncio.get_event_loop()
    await loop.run_in_executor(None, thread)

    return web.Response(text="Hello, world")


loop = asyncio.get_event_loop()
loop.set_default_executor(ContextVarExecutor())
app = web.Application(middlewares=[middleware_factory()])
app.add_routes([web.get('/', hello)])
web.run_app(app)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aiohttp_request-0.0.2.tar.gz (2.9 kB view hashes)

Uploaded Source

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page