Passed
Push — master ( 4b6ab6...72d98f )
by Randy
02:02
created

libs.callback.WSHandler.open()   A

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nop 1
1
import json
2
from abc import ABC
3
4
from tornado.httpserver import HTTPServer
5
from tornado.ioloop import IOLoop
6
from tornado.web import Application, RequestHandler
7
from tornado.websocket import WebSocketHandler
8
9
"""
10
    Copyright (c) 2020 Star Inc.(https://starinc.xyz)
11
12
    This Source Code Form is subject to the terms of the Mozilla Public
13
    License, v. 2.0. If a copy of the MPL was not distributed with this
14
    file, You can obtain one at http://mozilla.org/MPL/2.0/.
15
"""
16
17
response_handle = ()
18
19
hello_msg = '''
20
<b>PBP API Server</b>
21
<br>The security project for Internet.
22
<hr>(c)2020 <a href="https://github.com/supersonictw">SuperSonic</a>.
23
'''
24
25
26
class HttpHandler(RequestHandler, ABC):
27
    """
28
    Http Handle
29
    ---
30
    Default URL:
31
        http://localhost:2020/
32
    """
33
34
    async def get(self):
35
        self.write(hello_msg)
36
        await self.finish()
37
38
    async def post(self):
39
        req_body = self.request.body
40
        req_str = req_body.decode('utf8')
41
        result = {"status": 202}
42
        for handle in response_handle:
43
            result = await handle(req_str)
44
        self.write(json.dumps(result))
45
        await self.finish()
46
47
48
class WSHandler(WebSocketHandler, ABC):
49
    """
50
    WebSocket handle
51
    ---
52
    Default URL:
53
        http://localhost:2020/ws
54
    """
55
56
    def check_origin(self, origin):
57
        return True
58
59
    def open(self):
60
        self.write_message(json.dumps({
61
            "status": 201,
62
            "msg": hello_msg
63
        }))
64
65
    async def on_message(self, message):
66
        result = {"status": 202}
67
        for handle in response_handle:
68
            result = await handle(message)
69
        await self.write_message(json.dumps(result))
70
71
    def on_close(self):
72
        pass
73
74
75
class WebServer:
76
    """
77
    Web service of API protocol
78
    """
79
80
    def __init__(self, pbp_handle):
81
        global response_handle
82
        response_handle = (pbp_handle.server_response,)
83
84
    @staticmethod
85
    def listen(port: int):
86
        """
87
        Start listen on web services
88
89
        :return:
90
        """
91
        app = Application([
92
            ('/', HttpHandler),
93
            ('/ws', WSHandler)
94
        ])
95
        server = HTTPServer(app)
96
        server.listen(port)
97
        server.start(0)
98
        IOLoop.current().start()
99