Skip to content

Instantly share code, notes, and snippets.

@rrader
Last active August 29, 2015 14:24
Show Gist options
  • Select an option

  • Save rrader/13fb4de7ddfcb7e4fc54 to your computer and use it in GitHub Desktop.

Select an option

Save rrader/13fb4de7ddfcb7e4fc54 to your computer and use it in GitHub Desktop.
Static content serving via aiohttp for development purposes with JSX support

Default aiohttp static handler doesn't support any modification on the fly.

This handler helps to serve static files from directory ./static as is and convert JSX for ReactJS if needed.

import asyncio
import logging
from aiohttp import web
import os
from react import jsx


logger = logging.getLogger('static')


@asyncio.coroutine
def static_handler(request):
    path = request.match_info['path']
    full_path = os.path.join(os.path.dirname(__file__), 'static', path)
    content = open(full_path, 'br').read()
    if full_path.endswith('.jsx'):
        logger.debug("JSX->JS conversion of {} ({})".format(path, full_path))
        transformer = jsx.JSXTransformer()
        content = transformer.transform_string(content.decode()).encode()

    return web.Response(body=content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment