Passed
Push — master ( d8b378...61284a )
by Alexander
01:02
created

things3_to_kanban_server   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 48
dl 0
loc 69
rs 10
c 0
b 0
f 0

3 Functions

Rating   Name   Duplication   Size   Complexity  
A kanban_server() 0 14 2
A handler() 0 5 1
A open_browser() 0 4 1
1
#!/usr/bin/env python3
2
# -*- coding: utf-8 -*-
3
4
"""KanbanView Server for KanbanView for Things 3."""
5
6
from __future__ import print_function
7
8
__author__ = "Alexander Willner"
9
__copyright__ = "Copyright 2020 Alexander Willner"
10
__credits__ = ["Alexander Willner"]
11
__license__ = "MIT"
12
__version__ = "1.1.0"
13
__maintainer__ = "Alexander Willner"
14
__email__ = "[email protected]"
15
__status__ = "Development"
16
17
from io import StringIO
18
from os.path import dirname, realpath
19
from os import system
20
from signal import signal, SIGINT
21
from threading import Thread
22
from time import sleep
23
import sys
24
import webbrowser
25
from wsgiref.simple_server import make_server
26
import things3_to_kanban
27
28
FILE = 'kanban.html'
29
PATH = '/../resources/'
30
PORT = 8080
31
HTTPD = None
32
33
34
def handler(signal_received, frame):
35
    """Handle any cleanup here."""
36
    print("Shutting down...: " + str(signal_received) + " / " + str(frame))
37
    HTTPD.server_close()
38
    sys.exit(0)
39
40
41
def kanban_server(environ, start_response):
42
    """Serving generated HTML tables via AJAX."""
43
44
    if environ['REQUEST_METHOD'] == 'POST':
45
        start_response('200 OK', [('Content-type', 'text/plain')])
46
        output = StringIO()
47
        things3_to_kanban.write_html_columns(output)
48
        return [output.getvalue().encode()]
49
50
    filename = environ['PATH_INFO'][1:]
51
    filename = dirname(realpath(__file__)) + PATH + filename
52
    response_body = open(filename, 'rb').read()
53
    start_response('200 OK', [('Content-Length', str(len(response_body)))])
54
    return [response_body]
55
56
def open_browser():
57
    """Delay opening the browser."""
58
    sleep(1)
59
    webbrowser.open('http://localhost:%s/%s' % (PORT, FILE))
60
61
if __name__ == "__main__":
62
    signal(SIGINT, handler)
63
    # kill possible zombie processes; can't use psutil in py2app context
64
    system('lsof -nti:' + str(PORT) + ' | xargs kill -9 ; sleep 1')
65
66
    HTTPD = make_server("", PORT, kanban_server)
67
    Thread(target=open_browser).start()
68
    HTTPD.serve_forever()
69