1
|
|
|
"""Handles the HTTP frontend (ie. answers to requests from a |
2
|
|
|
UI).""" |
3
|
|
|
|
4
|
1 |
|
import cgi |
5
|
1 |
|
import json |
6
|
1 |
|
import logging |
7
|
|
|
|
8
|
1 |
|
from ppp_libmodule import HttpRequestHandler as HttpRequestHandler |
9
|
1 |
|
from ppp_libmodule.exceptions import ClientError, InvalidConfig |
10
|
|
|
|
11
|
1 |
|
from .api import Api |
12
|
1 |
|
from .logger import Logger |
13
|
|
|
|
14
|
1 |
|
DOC_URL = 'https://github.com/ProjetPP/PPP-Logger#readme' |
15
|
|
|
|
16
|
1 |
|
class RequestHandler(HttpRequestHandler): |
17
|
|
|
"""Handles one request.""" |
18
|
|
|
|
19
|
1 |
|
def on_bad_method(self): |
20
|
|
|
"""Returns a basic response to GET requests (probably sent by humans |
21
|
|
|
trying to open the link in a web browser.""" |
22
|
1 |
|
text = 'Bad method, only POST is supported. See: ' + DOC_URL |
23
|
1 |
|
return self.make_response('405 Method Not Allowed', |
24
|
|
|
'text/plain; charset=utf-8', |
25
|
|
|
text |
26
|
|
|
) |
27
|
|
|
|
28
|
1 |
|
def on_unknown_uri(self): |
29
|
|
|
"""Returns a basic response to GET requests (probably sent by humans |
30
|
|
|
trying to open the link in a web browser.""" |
31
|
|
|
text = 'URI not found, only / is supported. See: ' + DOC_URL |
32
|
|
|
return self.make_response('404 Not Found', |
33
|
|
|
'text/plain; charset=utf-8', |
34
|
|
|
text |
35
|
|
|
) |
36
|
|
|
|
37
|
1 |
|
def process_request(self, request): |
38
|
|
|
"""Processes a request.""" |
39
|
1 |
|
try: |
40
|
1 |
|
request = json.loads(request.read().decode()) |
41
|
1 |
|
except ValueError: |
42
|
1 |
|
raise ClientError('Data is not valid JSON.') |
43
|
1 |
|
answer = self.router_class(request).answer() |
44
|
1 |
|
return self.make_response('200 OK', |
45
|
|
|
'application/json', |
46
|
|
|
json.dumps(answer) |
47
|
|
|
) |
48
|
|
|
|
49
|
1 |
|
def on_get(self): |
50
|
1 |
|
form = cgi.FieldStorage(fp=self.environ['wsgi.input'], |
51
|
|
|
environ=self.environ.copy()) |
52
|
1 |
|
try: |
53
|
1 |
|
answer = Api(form).answer() |
54
|
1 |
|
except ClientError as e: |
55
|
1 |
|
return self.make_response('405 Client Error', |
56
|
|
|
'text/plain; charset=utf-8', |
57
|
|
|
e.args[0]) |
58
|
1 |
|
return self.make_response('200 OK', |
59
|
|
|
'application/json', |
60
|
|
|
json.dumps(answer)) |
61
|
|
|
|
62
|
|
|
|
63
|
1 |
|
def app(environ, start_response): |
64
|
|
|
"""Function called by the WSGI server.""" |
65
|
|
|
return RequestHandler(environ, start_response, Logger).dispatch() |
66
|
|
|
|