]> git.phdru.name Git - xsetbg.git/blob - xsetbg-wsgi.py
Style: Fix `flake8` error E402 module level import not at top of file
[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
10 from xsetbg_conf import xsetbg_conf
11 from xsetbg import change as _change
12
13 simple_server.ServerHandler = SimpleHandler  # Stop logging to stdout
14
15 # get httpd settings from config
16 if xsetbg_conf.has_option("httpd", "host"):
17     host = xsetbg_conf.get("httpd", "host")
18 else:
19     host = 'localhost'
20
21 if xsetbg_conf.has_option("httpd", "port"):
22     port = xsetbg_conf.getint("httpd", "port")
23 else:
24     error("Config must specify a port to listen. Abort.")
25
26
27 commands = {}
28
29
30 def published(func):
31     commands[func.__name__] = func
32     return func
33
34
35 @published
36 def change(force=False):
37     _change()
38
39
40 @published
41 def force():
42     _change(force=True)
43
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
58 def app(env, start_response):
59     command = env['PATH_INFO'][1:]  # Remove the leading slash
60     if command not in commands:
61         status = '404 Not found'
62         response_headers = [('Content-type', 'text/plain')]
63         start_response(status, response_headers)
64         return ['The command was not found.\n']
65
66     try:
67         commands[command]()
68     except:
69         status = '500 Error'
70         response_headers = [('Content-type', 'text/plain')]
71         start_response(status, response_headers)
72         return ['Error occured!\n']
73
74     status = '200 OK'
75     response_headers = [('Content-type', 'text/plain')]
76     start_response(status, response_headers)
77     return ['Ok\n']
78
79
80 force()
81 httpd = make_server(host, port, app, server_class=QuitWSGIServer)
82 httpd.serve_forever()