How do I create a simple HTTP webserver in python 3, that would return a generated content for GET requests?
I checked this question, How to create a simple HTTP webserver in python? , but the solution proposed will return files, which is not the thing I need.
Instead, my server should respond with a generated response.
I know about frameworks like Flask and Django, but they would be an overkill for me. I need the shortest and the least resource greedy code that will just return generated content for any request.
After a little bit of research, I have come up with this as the simplest possible solution:
from http.server import HTTPServer, BaseHTTPRequestHandler
class MyRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(b'My content')
httpd = HTTPServer(('localhost', 5555), MyRequestHandler)
httpd.serve_forever()
You can do so with the http
module as shown below:
from http.server import BaseHTTPRequestHandler, HTTPServer
import time
hostname = "localhost"
serverPort = 8080
class Server(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("<html><head><title>Python Webserver</title>
</head>", "utf-8"))
self.wfile.write(bytes("<body>", "utf-8"))
self.wfile.write(bytes("<p>Web server is open!</p>", "utf-8"))
self.wfile.write(bytes("</body></html>", "utf-8"))
if __name__ == "__main__":
webServer = HTTPServer((hostname, serverPort), Server)
print("Server started http://%s:%s" % (hostname, serverPort))
try:
webServer.serve_forever()
except KeyboardInterrupt:
pass
webServer.server_close()
print("Server closed")
time.sleep(2)
This code creates a web server on http://localhost:8080
and displays some text saying Web server is open!
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.