This is a simple HTTP server. It is used to understand the working mode of HTTP, from the underlying socket to the composition mode of HTTP packets.
The server supports CGI & WSGI standards.
The using is not difficult, there is a sample file run.py
in the project, here is some details:
Just use the server.HTTPServer
module to create an HTTP server.
Bind the Application
instance to the server and use the start
method to start the server.
HTTPServer(self, address: Tuple[str, int], maxsize: Optional[int] = settings.DEFAULT_WATTING_QSIZE)
- address: which address you want to bind and listen
- maxsize: max waiting queue size of HTTP client
Generally speaking, you do not need to use the Request
class directly, but you can process the return value of the specified mime type.
request = Request(rawdata: str)
# Return reverse
request.register_body_handler("text/plain", lambda obj: obj[::-1])
You can instantiate a Response
class as follows:
Response(200, "Hello World")
Response(200, "Hello World", environ={"HOSTNAME": "localhost"})
Response(200, "Hello World", headers={"UA": "Test-UA"})
Instantiate an Application
and use the route
method to bind your view function to it.
Then just bind the Application instance to the HTTP server.
ttpd = HTTPServer(("0.0.0.0", 15014))
application = Application(__name__)
httpd.serve(application)
@application.route("/hello", methods=["GET"])
def test_get_function(request):
"""Hello World!"""
# __import__("time").sleep(10)
return \
"""
<html>
<body style="background: #dfe6e9; text-align:center;">
<h1 style="margin-top:30vh;">Hello World</h1>
<h3>From: Simple-Python-HTTP-Server</h3>
<h4 style="font-style: italic;">Your UA info: {UA}</h4>
</body>
</html>
""".format(UA=request.headers.get("User-Agent", ''))
httpd.start()
Your view function's return can be:
return 200, "Hello world" # HTTP Code, Content
return "Hello world" # Content
return Response(200, "Hello world") # HTTP Response instance
You can define CGI extensions and catalogue such as Settings
below.
Then just write you CGI extension.
Using WSGI with tutorial here.
You can modify server/settings.py
to imply your own settings, for example:
# CGI Execution Timeout(s)
CGI_TIMEOUT = 5
# CGI Execution catalogue
CGI_CATALOGUE = "./cgi-bin"
Why named Flaks?
Because it mimics Flask's routing pattern, such as:
@application.route("/hello", methods=["GET", POST])
And there is also request
environ support (but provided in the form of parameters):
def simple_hello_world(request: server.Request)
Author: [email protected]
GitHub: https://github.com/guiqiqi
A back-end programmer, speak English, русский, Python, C++, C.
Wish you happy using.