]> git.phdru.name Git - xsetbg.git/blob - xsetbg-wsgi.py
Style: Fix `flake8` errors E302,E305 expected 2 blank lines, found 1
[xsetbg.git] / xsetbg-wsgi.py
1 #! /usr/bin/env python
2 """XSetBg (WSGI version)
3
4 """
5
6 from wsgiref import simple_server
7 from wsgiref.handlers import SimpleHandler
8 from wsgiref.simple_server import WSGIServer, make_server
9 simple_server.ServerHandler = SimpleHandler  # Stop logging to stdout
10
11 from xsetbg_conf import xsetbg_conf
12 from xsetbg import change as _change
13
14 # get httpd settings from config
15 if xsetbg_conf.has_option("httpd", "host"):
16     host = xsetbg_conf.get("httpd", "host")
17 else:
18     host = 'localhost'
19
20 if xsetbg_conf.has_option("httpd", "port"):
21     port = xsetbg_conf.getint("httpd", "port")
22 else:
23     error("Config must specify a port to listen. Abort.")
24
25
26 commands = {}
27
28
29 def published(func):
30     commands[func.__name__] = func
31     return func
32
33
34 @published
35 def change(force=False):
36     _change()
37
38
39 @published
40 def force():
41     _change(force=True)
42
43
44 @published
45 def stop():
46     QuitWSGIServer._quit_flag = True
47
48
49 class QuitWSGIServer(WSGIServer):
50     _quit_flag = False
51
52     def serve_forever(self):
53         while not self._quit_flag:
54             self.handle_request()
55
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
79 force()
80 httpd = make_server(host, port, app, server_class=QuitWSGIServer)
81 httpd.serve_forever()