SoFunction
Updated on 2024-11-19

Python implementation of http server (module pass parameter receive parameter) example

summaries

To implement an HTTP server that can take parameters, you can use a module from the Python standard library. This module provides a simple HTTP server that can be used to develop and test web applications.

The following is sample code that implements an HTTP server that can take parameters:

coding

from  import BaseHTTPRequestHandler, HTTPServer
from  import urlparse, parse_qs
class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        # Parsing query strings in URLs
        query = parse_qs(urlparse().query)
        # Get parameter values
        name = ('name', [''])[0]
        time = ('time', [''])[0]
        # Construct the response
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        (bytes("<html><head><title>Python HTTP Server</title></head>", "utf-8"))
        (bytes("<body><p>Hello, %s!</p>" % name, "utf-8"))
        (bytes("<p>this is a python server page, this time is %s</p><img src='/bjh/' style='width:500px;' /></body></html>" % time, "utf-8"))
if __name__ == '__main__':
    # Start the HTTP server
    server_address = ('', 8000)
    httpd = HTTPServer(server_address, MyHandler)
    print('The service is on...')
    httpd.serve_forever()

Instructions for use

In this example, theMyHandlerClasses inherited fromBaseHTTPRequestHandler, which is used to process HTTP requests. In thedo_GET()method first parses the query string in the URL and then gets the parameter values. Next, the code constructs the response and inserts the parameter values into the HTML page. Finally, the response is sent to the client.

If you want to add more parameters, just add the appropriate query parameters to the URL and add them to thedo_GET()method can be parsed. For example, if you want to add agenderparameter, the URL can be accessed this way:http://localhost:8000/?name=Tanking&time=2023-10-21&gender=male

You can start the HTTP server by running the above code, and then accessing it in your browser athttp://localhost:8000/?name=Tanking&time=2023-10-21to test it. The server will return an HTML page containing the values of the parameters.

(of a computer) run

In Pagoda's terminal, you can run it like this:

However, closing the terminal stops it from running. So you need to use this command:

nohup python  &

demonstrations

The above is Python implementation of http server (module pass parameter receive parameter) example of the details, more information about Python pass parameter receive please pay attention to my other related articles!