Posts Tagged ‘sqlalchemy’

Pyramid top level route issue

Wednesday, November 16th, 2011

I found this issue when I was developing an application that needed to use top level urls.

__init__.py

config.add_route('profile_view', '/:id')

views.py

@view_config(route_name='profile_view', renderer='profile/view.jinja2')
def view(request):
    profile = AuthUser.get_by_id(request.matchdict.get('id'))
    return {
        'profile': profile,
    }

On every page load I was getting the following error:

/var/www/pyramid/lib/python2.6/site-packages/SQLAlchemy-0.7.3-py2.6-linux-x86_64.egg/sqlalchemy/engine/default.py:330: Warning: Truncated incorrect DOUBLE value: 'favicon.ico'

I didn’t think too much about this error, I was running a testing version of Apex, where we changed the request.user object from a ContextFound subscriber to a Request Factory, so I figured it might have been a bug.

I started to debug Apex when I found the issue. The issue was that any request that was requesting any top level route would match my route, including the favicon.ico.

 

There are a few fixes to this problem.

You can add a regex condition to your route so it will only match on numerical values.

config.add_route('profile_view', '/{id:\d+}')

or

Add a route and a corresponding view that would match favicon.ico. The following code sample can be found at: http://docs.pylonsproject.org/projects/pyramid/dev/narr/assets.html#registering-a-view-callable-to-serve-a-static-asset

__init__.py

config.add_route('favicon', '/favicon.ico')

views.py

import os
from pyramid.response import Response   

@view_config(route_name='favicon')
def favicon(request):
    here = os.path.dirname(__file__)
    icon = open(os.path.join(here, 'static', 'images', 'favicon.ico'))
    return Response(content_type='image/x-icon', app_iter=icon)  

This code really shouldn’t be used in production, you should use something like Apache’s Alias method to alias the favicon.