-
Notifications
You must be signed in to change notification settings - Fork 828
/
risk_server.py
60 lines (44 loc) · 1.76 KB
/
risk_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
# coding=utf8
"""A http server which offers two uri: query and report"""
import cgi
from gevent import monkey
monkey.patch_all() # noqa
import json
from cgi import FieldStorage
from gevent.pywsgi import WSGIServer
from server import query_handler, report_handler
from config import RISK_SERVER_HOST, RISK_SERVER_PORT
URL_2_HANDLERS = {
"/query/": query_handler,
"/report/": report_handler,
}
def __parse_post_body(environ, ignore_get=False):
post_data = {}
content_type = environ["CONTENT_TYPE"] if "CONTENT_TYPE" in environ else None
if content_type is not None:
mimetype, options = cgi.parse_header(content_type)
# accept post json
if mimetype == "application/json" and environ["REQUEST_METHOD"] == "POST":
storage = environ['wsgi.input'].read()
if storage:
return json.loads(storage)
storage = FieldStorage(environ['wsgi.input'], environ=environ, keep_blank_values=True)
# accept get querystring
if not ignore_get:
for k in storage.keys():
post_data[k] = storage.getvalue(k)
return post_data
def application(environ, start_response):
if environ['PATH_INFO'] not in URL_2_HANDLERS:
response = json.dumps({"ec": 0, "error": "invalid uri"})
start_response('200 OK', [('Content-Type', 'application/json')])
return [response.encode()]
handler = URL_2_HANDLERS[environ['PATH_INFO']]
post_data = __parse_post_body(environ, ignore_get=False)
response = handler(post_data)
start_response('200 OK', [('Content-Type', 'application/json')])
return [str(response).encode()]
def serve_forever():
WSGIServer((RISK_SERVER_HOST, RISK_SERVER_PORT), application).serve_forever()
if __name__ == "__main__":
serve_forever()