]> git.phdru.name Git - xsetbg.git/blob - xsetbg-wsgi.py
c90da9258c13df1d2c7b7001c2c1ee389182f1a5
[xsetbg.git] / xsetbg-wsgi.py
1 #! /usr/bin/env python
2 """XSetBg (WSGI version)
3
4 """
5
6 __version__ = "$Revision$"[11:-2]
7 __revision__ = "$Id$"[5:-2]
8 __date__ = "$Date$"[7:-2]
9
10 __author__ = "Oleg Broytman <phd@phdru.name>"
11 __copyright__ = "Copyright (C) 2000-2011 PhiloSoft Design"
12 __license__ = "GNU GPL"
13
14
15 from wsgiref import simple_server
16 from wsgiref.handlers import SimpleHandler
17 from wsgiref.simple_server import WSGIServer, make_server
18 simple_server.ServerHandler = SimpleHandler # Stop logging to stdout
19
20 from xsetbg import host, port, change as _change
21
22
23 def published(func):
24     func._wsgi_published = True
25     return func
26
27 @published
28 def change(force=False):
29     _change()
30
31 @published
32 def force():
33     _change(force=True)
34
35 @published
36 def stop():
37     QuitWSGIServer._quit_flag = True
38
39
40 g = globals().copy()
41 commands = dict([(name, g[name]) for name in g
42     if getattr(g[name], '_wsgi_published', False)])
43 del g
44
45 class QuitWSGIServer(WSGIServer):
46     _quit_flag = False
47
48     def serve_forever(self):
49         while not self._quit_flag:
50             self.handle_request()
51
52 def app(env, start_response):
53     command = env['PATH_INFO'][1:] # Remove the leading slash
54     if command not in commands:
55         status = '404 Not found'
56         response_headers = [('Content-type', 'text/plain')]
57         start_response(status, response_headers)
58         return ['The command was not found.\n']
59
60     try:
61         commands[command]()
62     except:
63         status = '500 Error'
64         response_headers = [('Content-type', 'text/plain')]
65         start_response(status, response_headers)
66         return ['Error occured!\n']
67
68     status = '200 OK'
69     response_headers = [('Content-type', 'text/plain')]
70     start_response(status, response_headers)
71     return ['Ok\n']
72
73 force()
74 httpd = make_server(host, port, app, server_class=QuitWSGIServer)
75 httpd.serve_forever()