This repository was archived by the owner on May 5, 2022. It is now read-only.
forked from launchdarkly/python-server-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_util.py
More file actions
159 lines (126 loc) · 5.2 KB
/
Copy pathserver_util.py
File metadata and controls
159 lines (126 loc) · 5.2 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
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
import json
import logging
from queue import Empty
import ssl
import threading
try:
import queue as queuemod
except:
import Queue as queuemod
try:
from SimpleHTTPServer import SimpleHTTPRequestHandler
# noinspection PyPep8Naming
import SocketServer as socketserver
import urlparse
except ImportError:
# noinspection PyUnresolvedReferences
from http.server import SimpleHTTPRequestHandler
# noinspection PyUnresolvedReferences
import socketserver
# noinspection PyUnresolvedReferences
from urllib import parse as urlparse
class TestServer(socketserver.TCPServer):
allow_reuse_address = True
class GenericServer:
def __init__(self, host='localhost', use_ssl=False, port=None, cert_file="self_signed.crt",
key_file="self_signed.key"):
self.get_paths = {}
self.post_paths = {}
self.raw_paths = {}
self.stopping = False
parent = self
class CustomHandler(SimpleHTTPRequestHandler):
def handle_request(self, paths):
# sort so that longest path wins
for path, handler in sorted(paths.items(), key=lambda item: len(item[0]), reverse=True):
if self.path.startswith(path):
handler(self)
return
self.send_response(404)
self.end_headers()
def do_GET(self):
self.handle_request(parent.get_paths)
# noinspection PyPep8Naming
def do_POST(self):
self.handle_request(parent.post_paths)
self.httpd = TestServer(
("0.0.0.0", port if port is not None else 0), CustomHandler)
port = port if port is not None else self.httpd.socket.getsockname()[1]
self.url = ("https://" if use_ssl else "http://") + host + ":%s" % port
self.port = port
logging.info("serving at port %s: %s" % (port, self.url))
if use_ssl:
self.httpd.socket = ssl.wrap_socket(self.httpd.socket,
certfile=cert_file,
keyfile=key_file,
server_side=True,
ssl_version=ssl.PROTOCOL_TLSv1)
self.start()
def start(self):
self.stopping = False
httpd_thread = threading.Thread(target=self.httpd.serve_forever)
httpd_thread.setDaemon(True)
httpd_thread.start()
def stop(self):
self.shutdown()
def post_events(self):
q = queuemod.Queue()
def do_nothing(handler):
handler.send_response(200)
handler.end_headers()
self.post_paths["/api/events/bulk"] = do_nothing
self.post_paths["/bulk"] = do_nothing
return q
def add_feature(self, key, data):
def handle(handler):
handler.send_response(200)
handler.send_header('Content-type', 'application/json')
handler.end_headers()
handler.wfile.write(json.dumps(data).encode('utf-8'))
self.get("/api/eval/features/{}".format(key), handle)
def get(self, path, func):
"""
Registers a handler function to be called when a GET request beginning with 'path' is made.
:param path: The path prefix to listen on
:param func: The function to call. Should be a function that takes the querystring as a parameter.
"""
self.get_paths[path] = func
def post(self, path, func):
"""
Registers a handler function to be called when a POST request beginning with 'path' is made.
:param path: The path prefix to listen on
:param func: The function to call. Should be a function that takes the post body as a parameter.
"""
self.post_paths[path] = func
def shutdown(self):
self.stopping = True
self.httpd.shutdown()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
try:
self.shutdown()
finally:
pass
class SSEServer(GenericServer):
def __init__(self, host='localhost', use_ssl=False, port=None, cert_file="self_signed.crt",
key_file="self_signed.key", queue=queuemod.Queue()):
GenericServer.__init__(self, host, use_ssl, port, cert_file, key_file)
def feed_forever(handler):
handler.send_response(200)
handler.send_header(
'Content-type', 'text/event-stream; charset=utf-8')
handler.end_headers()
while not self.stopping:
try:
event = queue.get(block=True, timeout=1)
""" :type: ldclient.twisted_sse.Event """
if event:
lines = "event: {event}\ndata: {data}\n\n".format(event=event.event,
data=json.dumps(event.data))
print("returning {}".format(lines))
handler.wfile.write(lines.encode('utf-8'))
except Empty:
pass
self.get_paths["/"] = feed_forever
self.queue = queue