-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.py
157 lines (117 loc) · 4.01 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import argparse, os, json, logging, config
from commandsmanager import CommandsManager
from flask import Flask, request, make_response
from urllib.parse import urlparse
from pprint import pprint
from time import time
from util import get_version
app = Flask(__name__)
cache = None
commands = None
IGNORED_URLS = ("/favicon.ico")
VERSION = get_version()
def json_response(data):
if 'pretty' in request.args:
respdata = json.dumps(data, indent = 4)
else:
respdata = json.dumps(data)
resp = make_response(respdata)
resp.headers["Access-Control-Allow-Origin"] = "*"
resp.headers["Content-Type"] = "application/json; charset=UTF-8"
return resp
def get_urlpath(url):
parts = urlparse(url)
if parts.query != "":
return "%s/?%s" % (parts.path, parts.query)
else:
return parts.path
def ignore_url(url):
return url in IGNORED_URLS
def run_command(name, method = None):
# Get time for request when debug is on
if config.DEBUG:
start = time()
url = get_urlpath(request.url)
logging.debug("Request: " + url)
if ignore_url(url):
return False
params = request.args.to_dict()
if config.CACHING.get("enabled", False) and url in cache:
return cache[url]
cmd, response = commands.run(
cmdname = name,
cmdmethod = method,
params = params
)
cacheable = getattr(cmd, "CACHEABLE", False)
logging.debug("Command cacheable: " + str(cacheable))
if not response["error"] and config.CACHING.get("enabled", False) and cacheable:
# We also need to check if this cache is only for specific methods
if isinstance(cmd.CACHEABLE, tuple):
if method in cmd.CACHEABLE:
cache[url] = response
else:
# Not specific, simply cache this
cache[url] = response
if config.DEBUG:
response_time = time() - start
response["debug"] = {
"response_time" : response_time
}
return response
@app.route('/')
def root():
return open(config.PATH + "/static/index.html").read()
@app.route('/_commands')
def list_commands():
logging.debug("Listing all commands")
return json_response(commands.listall())
@app.route('/<cmdname>/<cmdmethod>')
def command_with_method(cmdname, cmdmethod):
response = run_command(cmdname, cmdmethod)
return json_response(response)
@app.route('/<cmdname>')
def command(cmdname):
response = run_command(cmdname)
return json_response(response)
def get_cache():
if not config.CACHING.get("enabled", False):
return False
cachemodule = __import__(config.CACHING['type'])
return cachemodule.Cache(expires = config.CACHING['expires'])
def create_app():
global cache, commands
cache = get_cache()
commands = CommandsManager()
return app
def main():
global cache, commands
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--debug', action="store_true")
parser.add_argument('-nc', '--no-cache', action="store_true")
parser.add_argument('-t', '--timeout', type=int, default=config.HTTP_TIMEOUT)
parser.add_argument(
'-c',
'--cachingtype',
choices=('memorycache', 'rediscache'),
default = config.CACHING["type"]
)
args = parser.parse_args()
config.DEBUG = args.debug
if args.no_cache:
config.CACHING["enabled"] = False
if args.cachingtype:
config.CACHING["type"] = args.cachingtype
config.HTTP_TIMEOUT = args.timeout
app.debug = config.DEBUG
if config.DEBUG:
logging.getLogger().setLevel(logging.DEBUG)
logging.info(f"Starting Chantek server v{VERSION}")
logging.info("Cache configuration: %s" % json.dumps(config.CACHING))
logging.info("Cache enabled: %s" % config.CACHING.get("enabled", False))
cache = get_cache()
commands = CommandsManager()
logging.info("Going to run a server on %s:%s" %(config.HOST, config.PORT))
app.run(port = config.PORT, host = config.HOST)
if __name__ == "__main__":
main()