Login

Run Django as a FastCGI authorizer

Author:
cme
Posted:
October 23, 2008
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

I use this as the FastCGI script for authorizers with lighttpd (though I guess it should work with little change on any other webserver supporting FastCGI). I point it to the same Django project/settings as the normal responder script.

As I use it to gate access to pages not served by Django, I can include those non-Django URLs in the main urls.py, connected to special authorizer view functions (in another snippet).

The two key parts of the script, compared to the equivalent one for Django in the normal FastCGI Responder role, are:

  1. Pass the FCGI_AUTHORIZER as the role to WSGIServer
  2. Generate a PATH_INFO variable from the REQUEST_URI (FastCGI authorizers aren't given PATH_INFO, but Django needs that to match against the URLconf.)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/usr/bin/python
import sys, os

# Set the DJANGO_SETTINGS_MODULE environment variable.
# Customise this for your setup
os.environ['DJANGO_SETTINGS_MODULE'] = "djsite.settings"

from django.core.handlers.wsgi import WSGIHandler
main_handler = WSGIHandler()

def wrapper(environ, start_response):
    """FastCGI Authorizers don't get PATH_INFO.  Make one from
    REQUEST_URI so that Django can use it in URL matching."""
    if not environ["PATH_INFO"]:
        # Fastcgi doesn't give you PATH_INFO for authorizers
        uri = environ['REQUEST_URI']
        if '?' in uri:
            path, query = environ['REQUEST_URI'].split('?', 1)
        else:
            path, query = uri, ''
        environ['PATH_INFO'] = path

    return main_handler(environ, start_response)

if __name__ == '__main__':
    from flup.server.fcgi import WSGIServer
    from flup.server.fcgi_base import FCGI_AUTHORIZER

    # Django normally uses the FCGI_RESPONDER role and will reject AUTHORIZER
    # requests.
    WSGIServer(wrapper, roles=(FCGI_AUTHORIZER,)).run()

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.