-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.py
More file actions
64 lines (57 loc) · 2.46 KB
/
server.py
File metadata and controls
64 lines (57 loc) · 2.46 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
import os
if not os.path.isfile("config.json"):
print("config.json not found, please create one")
exit()
import json
with open("config.json", "r") as f:
IMAGE_ROOT_PATH = json.load(f)["image-path"]
with open("searchsite.html", "r") as f:
website = "".join(f.readlines())
from search import create_image_string, count
# simple http server
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
import re
image_regex = re.compile('[/\\\\]\d+[/\\\\]')
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
if self.path == "/":
self.send_response(200)
self.headers["Cache-Control"] = "max-age=31536000"
self.end_headers()
self.wfile.write(bytes(website, "utf-8"))
elif self.path.startswith("/search"):
self.send_response(200)
self.end_headers()
args = parse_qs(urlparse(self.path).query)
query = args["query"][0]
page = int(args["page"][0]) if "page" in args else 0
page_size = int(args["page_size"][0]) if "page_size" in args else 30
self.wfile.write(bytes(f'<div id="imagecontainer" onkeydown="inputEventHandler()">{create_image_string(query, True, page, page_size)}</div>', "utf-8"))
elif self.path.startswith("/count"):
self.send_response(200)
self.end_headers()
args = parse_qs(urlparse(self.path).query)
query = args["query"][0]
self.wfile.write(bytes(str(count(query)), "utf-8"))
elif self.path.startswith("/refresh"):
self.send_response(200)
self.end_headers()
from ingest import main
from asyncio import run
run(main())
elif image_regex.match(self.path):
self.send_response(200)
self.headers["Cache-Control"] = "max-age=31536000"
self.end_headers()
self.wfile.write(open(IMAGE_ROOT_PATH + self.path, "rb").read())
else:
self.send_response(404)
self.end_headers()
self.wfile.write(bytes("404 Not Found", "utf-8"))
except KeyError:
pass
httpd = HTTPServer(("0.0.0.0", 8000), SimpleHTTPRequestHandler)
print("Serving on http://localhost:8000")
httpd.serve_forever()