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