-
Notifications
You must be signed in to change notification settings - Fork 5
/
local_compiler_api_server.py
117 lines (96 loc) · 3.8 KB
/
local_compiler_api_server.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
# Copyright (C) 2020-2021 - George Watkins and Alex Nguyen
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
# USA
import enum
import http.client
import json
import traceback
from http.server import BaseHTTPRequestHandler, HTTPServer
from typing import Dict, Optional
import jsonpickle
from lsqecc.pipeline import json_pipeline
class Routes(enum.Enum):
COMPILE = "/compile"
class _LocalCompilerApiServer(BaseHTTPRequestHandler):
def do_POST(self):
content_length = int(self.headers["Content-Length"]) # <--- Gets the size of data
post_data = self.rfile.read(content_length) # <--- Gets the data itself
print(
"POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n"
% (str(self.path), str(self.headers), post_data.decode("utf-8"))
)
if str(self.path) == Routes.COMPILE.value:
try:
response = json_pipeline.handle(post_data.decode("utf-8"))
self.send_response(response.status)
self.send_header("Content-type", "text/html")
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
self.wfile.write(jsonpickle.encode(response.body).encode("utf-8"))
except Exception:
self.send_response(500)
self.send_header("Content-type", "text/html")
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
self.wfile.write(
"{}\n\nRequest was {}".format(
traceback.format_exc(), post_data.decode("utf-8")
).encode("utf-8")
)
else:
self.send_response(404)
self.send_header("Content-type", "text/html")
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
self.wfile.write("POST Route not found: {}".format(self.path).encode("utf-8"))
# Handle Cors
def do_OPTIONS(self):
self.send_response(200, "ok")
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
self.send_header("Access-Control-Allow-Headers", "X-Requested-With, Content-type")
self.end_headers()
self.wfile.write("")
SAMPLE_CIRCUIT = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
h q[0];
cx q[0],q[1];
h q[0];
t q[1];
s q[0];
x q[0];
"""
JSON_POST_PARAMETERS = {
"circuit_source": "str", # alternative would be 'file'
"circuit": SAMPLE_CIRCUIT,
"apply_litinski_transform": True,
}
def probe(request_post_params: Optional[Dict] = None):
if request_post_params is None:
request_post_params = JSON_POST_PARAMETERS
conn = http.client.HTTPConnection("localhost:9876")
headers = {
"Content-type": "application/json",
}
conn.request("POST", "/compile", json.dumps(request_post_params), headers)
response = conn.getresponse()
print(response.read().decode())
if __name__ == "__main__":
server_address = ("", 9876)
httpd = HTTPServer(server_address, _LocalCompilerApiServer)
httpd.serve_forever()