Skip to content

Instantly share code, notes, and snippets.

@menecio
Last active September 7, 2019 10:15
Show Gist options
  • Save menecio/64585e9cf106aa7495f7de71cbf86a1b to your computer and use it in GitHub Desktop.
Save menecio/64585e9cf106aa7495f7de71cbf86a1b to your computer and use it in GitHub Desktop.
from aiohttp import web
from django.apps import apps
from django.core.serializers import serialize
from mymoviedb.utils import database_sync_to_async
routes = web.RouteTableDef()
@routes.view('/movies')
class MoviesListView(web.View):
model = 'movies.Movie'
async def get_queryset(self, **kwargs):
'''
We use .get_model() to avoid importing directly the model
otherwise Django's ORM won't be ready and will crash when our
aiohttp app is starting up.
'''
model = apps.get_model(self.model)
return await database_sync_to_async(model.objects.all)()
async def get(self):
queryset = await self.get_queryset()
text = serialize('json', queryset)
return web.json_response(text=text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment