pep-example/pepexample/server.py

62 lines
2.0 KiB
Python

# webapp.py
from functools import cached_property
from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qsl, urlparse
import subprocess
import os
import json
class WebRequestHandler(BaseHTTPRequestHandler):
@cached_property
def url(self):
return urlparse(self.path)
@cached_property
def query_data(self):
return dict(parse_qsl(self.url.query))
@cached_property
def post_data(self):
content_length = int(self.headers.get("Content-Length", 0))
return self.rfile.read(content_length)
@cached_property
def json_data(self):
return json.loads(self.post_data.decode("utf-8"))
@cached_property
def authorized(self):
return self.headers.get("Authorization") == os.environ["Authorization"]
def do_GET(self):
message = "GET from {} with params: {} and headers {}".format(self.url.path, str(self.query_data),str(self.headers))
print(message)
self.protocol_version = 'HTTP/1.0'
if self.url.path in ["/researcher/notexists", "/operator/notexists"] :
print("returning 404 Not found")
self.send_error(404, "Not found")
else:
print("returning 200")
self.send_response(200, "OK")
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write(message.encode("UTF-8"))
self.wfile.flush()
def do_POST(self):
message = "POST to {} with data: {} and headers {}".format(self.url.path, str(self.post_data),str(self.headers))
print(message)
self.protocol_version = 'HTTP/1.0'
self.send_response(200, "OK")
self.send_header("Content-Type", "text/plain")
self.send_header("X-Custom", "Hello world")
self.end_headers()
self.wfile.write(message.encode("UTF-8"))
self.wfile.flush()
if __name__ == "__main__":
server = HTTPServer(("0.0.0.0", 8000), WebRequestHandler)
server.serve_forever()