#!/usr/bin/env python3 # You can test it with: # curl --request POST --data name=foobar http://localhost:4000 import wsgiref.simple_server as server import urllib.parse import psycopg2 PORT = 4000 def pack(start_response, status, data): datae = data.encode() # Always encode to UTF-8 response_headers = [("Content-type", "text/plain; charset=UTF-8"), ("Content-Length", str(len(datae)))] start_response(status, response_headers) return [datae] def application(environ, start_response): if environ["REQUEST_METHOD"] != "POST": status = "405 Method unavailable" output = "Unsupported HTTP method \"%s\"\r\n" % environ["REQUEST_METHOD"] return pack(start_response, status, output) try: body_size = int(environ.get("CONTENT_LENGTH", 0)) except (ValueError): body_size = 0 body = environ["wsgi.input"].read(body_size) query = urllib.parse.parse_qsl(body.decode()) form = {} for q in query: form[q[0]] = q[1] for mandatory in ["string", "what"]: if mandatory not in form: status = "400 Invalid request" output = "Missing \"%s\" in request\r\n" % mandatory return pack(start_response, status, output) # TODO case-insensitive (scripts are capitalized) if form["what"] == "language": sql = "SELECT * FROM Languages WHERE code = %s" elif form["what"] == "script": sql = "SELECT * FROM Scripts WHERE code = %s" else: status = "400 Invalid request" output = "Unknown search category \"%s\"\r\n" % form["what"] return pack(start_response, status, output) # TODO junctions # TODO search in descriptions cursor.execute(sql, (form["string"], )) mytuple = cursor.fetchone() status = "200 OK" output = "TODO %s\r\n" % str(mytuple) # TODO display comments, preferredscript, addition date etc # TODO HTML with a templating engine? # TODO link to mulhtml ? return pack(start_response, status, output) if __name__ == "__main__": conn = psycopg2.connect("dbname=lsr") cursor = conn.cursor() httpd = server.make_server("", PORT, application) print("Listening on port %s" % PORT) httpd.serve_forever()