-
Notifications
You must be signed in to change notification settings - Fork 832
/
http.py
238 lines (188 loc) · 7.01 KB
/
http.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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import gevent
import logging
import re
import types
from jadi import interface
def url(pattern):
"""
Exposes the decorated method of your :class:`HttpPlugin` via HTTP.
Will be deprecated in favor of new decorators ( @get, @post, ... )
:param pattern: URL regex (``^`` and ``$`` are implicit)
:type pattern: str
:rtype: function
Named capture groups will be fed to function as ``**kwargs``
"""
def decorator(f):
f.url_pattern = re.compile(f'^{pattern}$')
return f
return decorator
def requests_decorator_generator(method):
"""
Factorization to generate request decorators like @get or @post.
:param method: Request method decorator to generate, like get or post
:type method: basestring
:return:
:rtype:
"""
def request_decorator(pattern):
"""
Exposes the decorated method of your :class:`HttpPlugin` via HTTP
:param pattern: URL regex (``^`` and ``$`` are implicit)
:type pattern: str
:rtype: function
Named capture groups will be fed to function as ``**kwargs``
"""
def decorator(f):
# Request method involved, like get or post
f.method = method
f.url_pattern = re.compile(f'^{pattern}$')
return f
return decorator
return request_decorator
# Decorators like @get and @post are defined here
http_methods = ['get', 'post', 'delete', 'head', 'put', 'patch']
webdav_methods = ['propfind', 'mkcol', 'options', 'proppatch', 'copy', 'move', 'lock', 'unlock']
for method in http_methods + webdav_methods:
globals()[method] = requests_decorator_generator(method)
class BaseHttpHandler():
"""
Base class for everything that can process HTTP requests
"""
def handle(self, http_context):
"""
Should create a HTTP response in the given ``http_context`` and return
the plain output
:param http_context: HTTP context
:type http_context: :class:`aj.http.HttpContext`
"""
@interface
class HttpMiddleware(BaseHttpHandler):
def __init__(self, context):
self.context = context
def handle(self, http_context):
pass
@interface
class HttpMasterMiddleware(BaseHttpHandler):
def __init__(self, context):
self.context = context
def handle(self, http_context):
pass
@interface
class HttpPlugin():
"""
A base interface for HTTP request handling::
@component
class HelloHttp(HttpPlugin):
@get('/hello/(?P<name>.+)')
def get_page(self, http_context, name=None):
context.add_header('Content-Type', 'text/plain')
context.respond_ok()
return 'Hello, f"{name}"!'
"""
def __init__(self, context):
self.context = context
def handle(self, http_context):
"""
Finds and executes the handler for given request context
(handlers were methods decorated with :func:`url` and will be
decorated with e.g. @get and @post in the future)
:param http_context: HTTP context
:type http_context: :class:`aj.http.HttpContext`
:returns: reponse data
"""
def check_method(handle_function, http_context):
"""
Check if the requested method is supported by the function,
e.g. avoid accept a get request in a post method
:param handle_function:
:type handle_function:
:param http_context:
:type http_context:
:return:
:rtype:
"""
# Right http method called
if handle_function.method == http_context.method.lower():
return True
# Allow head request on get targets
if http_context.method.lower() == 'head' and handle_function.method == 'get':
return True
return False
for name, handle_function in self.__class__.__dict__.items():
if hasattr(handle_function, 'url_pattern'):
handle_function = getattr(self, name)
match = handle_function.url_pattern.match(http_context.path)
if match:
# New decorators @get, @post, @delete ... used
if hasattr(handle_function, 'method'):
if check_method(handle_function, http_context):
http_context.route_data = match.groupdict()
data = handle_function(http_context, **http_context.route_data)
if isinstance(data, str):
data = data.encode('utf-8')
if isinstance(data, types.GeneratorType):
return data
return [data]
else:
# Ensure compatibility with old @url decorator
logging.warning(f'Backward @url compatibility for {handle_function.__name__}')
http_context.route_data = match.groupdict()
data = handle_function(http_context, **http_context.route_data)
if isinstance(data, str):
data = data.encode('utf-8')
if isinstance(data, types.GeneratorType):
return data
return [data]
@interface
class SocketEndpoint():
"""
Base interface for Socket.IO endpoints.
"""
plugin = None
"""arbitrary plugin ID for socket message routing"""
def __init__(self, context):
self.context = context
self.greenlets = []
def on_connect(self, message):
"""
Called on a successful client connection
"""
def on_disconnect(self, message):
"""
Called on a client disconnect
"""
def destroy(self):
"""
Destroys endpoint, killing the running greenlets
"""
for gl in self.greenlets:
gl.kill(block=False)
def on_message(self, message, *args):
"""
Called when a socket message arrives to this endpoint
"""
def spawn(self, target, *args, **kwargs):
"""
Spawns a greenlet in this endpoint, which will be auto-killed when the client disconnects
:param target: target function
"""
logging.debug(
f'Spawning sub-Socket Greenlet (in a namespace): {target.__name__}'
)
greenlet = gevent.spawn(target, *args, **kwargs)
self.greenlets.append(greenlet)
return greenlet
def send(self, data, plugin=None):
"""
Sends a message to the client.the
:param data: message object
:param plugin: routing ID (this endpoint's ID if not specified)
:type plugin: str
"""
self.context.worker.send_to_upstream({
'type': 'socket',
'message': {
'plugin': plugin or self.plugin,
'data': data,
},
})