-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.py
50 lines (38 loc) · 1.2 KB
/
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
import json
import sys
from twisted.web import server
from twisted.web.resource import Resource
from twisted.internet import reactor
from twisted.python import log
from twisted.internet import endpoints
def load_stock():
# load data from JSON
with open("books.json") as stock_file:
return json.load(stock_file)
BOOKS = load_stock()
class Index(Resource):
"""Serve all book ids.
"""
def render_GET(self, request):
return json.dumps(list(BOOKS.keys())).encode("utf8")
class Book(Resource):
"""Return detailed data about each book.
"""
isLeaf = True
def render_GET(self, request):
book_id = request.args.get(b"id")
book = BOOKS.get(book_id[0].decode("utf8"))
if not book:
request.setResponseCode(404)
return b""
return json.dumps(book).encode("utf8")
if __name__ == "__main__":
log.startLogging(sys.stdout)
root = Resource()
root.putChild(b"", Index())
root.putChild(b"book", Book())
site = server.Site(root)
endpoint_spec = "ssl:port=8080:privateKey=privkey.pem:certKey=cert.pem"
server = endpoints.serverFromString(reactor, endpoint_spec)
server.listen(site)
reactor.run()