Python – Pylons Custom Middleware return 404

pasterpylonspythonwsgi

I have the following code as a middleware in an pylons application:

import testing.model as model
import re
from pylons.controllers.util import abort

class SubdomainCheckMiddleware(object):
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        if 'subdomaincheck' in environ:
            return self.app(environ, start_response)

        p = re.compile('([a-z0-9\-]+)', re.IGNORECASE)
        subdomain = p.match(environ['HTTP_HOST']).group(0)
        query = "SELECT \"nspname\" FROM \"pg_namespace\" WHERE \"nspname\" = '%s';" % subdomain
        result = model.meta.Session.execute(query)
        for row in result:
            if row['nspname'] == subdomain:
                environ['subdomaincheck'] = 'done'
                return self.app(environ, start_response)

What it basicly does is checking if a schema in postgresql is present with the given subdomain, but I need it to return 404 not found if the schema is not present, how can I do that?

Best Solution

It's pretty straightforward to return a basic 404 in a WSGI app:

if error:
    start_response("404 Not Found", [('Content-type', 'text/plain')])
    return ['Page not found']

If you want something more elaborate you could use some other middleware to handle errors for you. It actually looks like Pylons comes with a StatusCodeRedirect middleware that might help you out here if you wanted it.

Related Question