mkogg.py: Fix 'self.get_mp4_metadata(self, source)'
[blog.git] / posts / SCGI.mdwn
1 [[!meta  title="Simple Common Gateway Interface"]]
2
3 Basic [[CGI]] starts a new process to handle each request.  This is
4 simple, but resource hungry.  To make things more efficient, a number
5 of protocols have developed that keep a CGI server running in the
6 background.  The frontend webserver then passes requests back to the
7 CGI server for processing without having to fire up a new program.
8
9 [FastCGI][] is the original CGI server protocol, but here we'll focus
10 on it's simpler cousin [SCGI][].  I write most of my scripts in
11 [[Python]], so I use the handy [scgi module][module] to write the
12 server (`www-apps/scgi` on [[Gentoo]]).  There's a great article on
13 [Linux Journal][LJ] to walk you through things, but in short, you need
14 something like:
15
16     import scgi
17     import scgi.scgi_server
18     import urlparse
19
20     class YourHandler(scgi.scgi_server.SCGIHandler):
21         def produce(self, env, bodysize, input, output):
22             url = env.get('DOCUMENT_URI', None)
23                         if url is None:  # fall back to the request URI                         
24                 url = env.get('REQUEST_URI', None)
25             data = urlparse.parse_qs(env.get('QUERY_STRING', ''))
26             output.write('Status: 200 OK\r\n')
27             output.write('Content-type: text/plain; charset=UTF-8\r\n')
28             output.write('\r\n')
29             output.write('URI: {}\n'.format(url))
30             output.write('data: {}\n'.format(data))
31
32     if __name__ == '__main__':
33         server = scgi.scgi_server.SCGIServer(
34             handler_class=YourHandler, host='localhost', port=4000)
35         server.serve()
36
37 Fire this script up, point your server at `localhost:4000`, and you're
38 good to go!
39
40 I've written up a little script to test your SCGI server from the
41 command line: [[scgi-test.py]]:
42
43     $ scgi-test.py /your/uri/
44     Status: 200 OK
45     Content-type: text/html; charset=UTF-8
46     
47     <!DOCTYPE html>
48     …
49
50 Configuring your frontend webserver to point to the SCGI server is
51 beyond the scope of this post.  I give an [[Nginx example|Nginx]] in
52 my Nginx post.
53
54
55 [FastCGI]: http://en.wikipedia.org/wiki/FastCGI
56 [SCGI]: http://en.wikipedia.org/wiki/Simple_Common_Gateway_Interface
57 [module]: http://python.ca/scgi/
58 [LJ]: http://www.linuxjournal.com/article/9310
59
60 [[!tag tags/tools]]
61 [[!tag tags/web]]