[英]How to create a simple HTTP webserver in python 3 responding to GET request with a generated content?
How do I create a simple HTTP webserver in python 3, that would return a generated content for GET requests?我如何在 python 3 中创建一个简单的 HTTP 网络服务器,它会为 GET 请求返回生成的内容?
I checked this question, How to create a simple HTTP webserver in python?我检查了这个问题, 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.我知道像 Flask 和 Django 这样的框架,但它们对我来说太过分了。 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:您可以使用
http
模块执行此操作,如下所示:
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!
这段代码在
http://localhost:8080
上创建了一个 web 服务器,并显示一些文本说Web server is open!
. .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.