forked from ucloud/ucloud-sdk-python2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.py
More file actions
53 lines (40 loc) · 1.59 KB
/
middleware.py
File metadata and controls
53 lines (40 loc) · 1.59 KB
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
# -*- coding: utf-8 -*-
class Middleware(object):
""" middleware is the object to store request/response handlers
>>> middleware = Middleware()
Add a request handler to prepare the request
>>> @middleware.request
... def prepare(req):
... req['Region'] = 'cn-bj2'
... return req
Add a response handler to log the response detail
>>> @middleware.response
... def logged(resp):
... print(resp)
... return resp
>>> len(middleware.request_handlers), len(middleware.response_handlers)
(1, 1)
"""
def __init__(self):
self.request_handlers = []
self.response_handlers = []
def request(self, handler, index=-1):
""" request is the request handler register to add request handler.
:param handler: request handler function, receive request object
and return a new request
:param int index: the position of request in the handler list,
default is append it to end
:return:
"""
self.request_handlers.insert(index, handler)
return handler
def response(self, handler, index=-1):
""" response is the response handler register to add response handler.
:param handler: response handler function, receive response object
and return a new response
:param int index: the position of response in the handler list,
default is append it to end
:return:
"""
self.response_handlers.insert(index, handler)
return handler