Skip to content

Improvements to static routes #468

@playpauseandstop

Description

@playpauseandstop

I got into two problems with static routes recently,

  1. There are no default ability to enable HEAD requests to static routes
  2. Sometimes we need to serve lone static files as routes instead of serving static files inside of static dir

Workaround to 1st problem,

app.router.add_static('/static/', static_dir, name='static')
route = web.StaticRoute(None, '/static/', static_dir)
route._method = 'HEAD'
app.router.register_route(route)

Not very elegant solution, IMO


Workaround to 2nd problem,

def view_factory(url, path):
    async def static_view(request):
        prefix = url.rsplit('/', 1)[0] or '/'
        route = web.StaticRoute(None, prefix, static_dir)

        request.match_info['filename'] = path
        return await route.handle(request)
    return static_view

view = static_view('/', 'pages/index.html')
app.router.add_route('GET', '/', view_factory('/', 'pages/index.html'))
app.router.add_route('GET', 
                     '/favicon.ico', 
                     view_factory('/favicon.ico', 'favicon/favicon.ico'))

In total, I propose imrpove static routes by,

  • Adding ability to setup routing HEAD requests to the static files on adding static route
  • Adding shortcut or refactor Static Route to be able serve separate files

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions