SoFunction
Updated on 2024-11-19

Simple implementation of Http server-side with Python

Python Implementation of an Http Server

Android development often have a lot of Http for interaction, sometimes want to test some API functions may need the cooperation of the background, but often need both sides are free time to do, the efficiency is not high. When testing APIs, you may want to use Python to write your own Http Service to realize some simple functions.

Implementing a simple server

Python has a simple built-in server. You can start an Http Service with a command-line command. By default, it can be used as a file server, using the folder you're currently operating in as a directory, displaying the contents of the folder, and displaying a file by default if it's in the current folder. The port is optional, if you don't fill it in, the default port 8000 will be used, and you can access the address in the browser.http://localhost:8000, you will be able to see the file server.

Python2 commands

python -m SimpleHTTPServer 8080

Python3 commands

python -m  8080

Customizing the API Server

Simple file servers sometimes do not meet our needs, we need to test some API interfaces, this time we can use Python to write a server that handles APIs.

  • HTTPServer allows us to specify a local address and port for the server, as well as configure the use of our custom http handler class
  • BaseHTTPRequestHandler Inheriting this class, we can customize do_GET(), do_POST() and other methods to handle client url requests.
  • Separate the path and parameters of the url, and process the corresponding business logic.
  • send_response() sets the Http return code, which will automatically set Message
  • send_header() sets the Http headers and confirms their completion with end_headers().
  • () Write Http body data, file use 'rb' to read and write, String write normally.

Note: Calling end_headers() and then calling send_header() will write the data to the body.

Here is the sample program, python3 version:

import time
import getHandler
from  import BaseHTTPRequestHandler, HTTPServer
HOST = '192.168.137.1'
PORT_NUMBER = 8080
class TestHttpHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        // Business logic processing
        ret_code, ret_byte = ()
        // Set the corresponding code
        self.send_response(ret_code)
        if ret_byte is None:
            // No body
            // Confirmation of header information
            self.end_headers()
            return
        // Set the return length
        self.send_header('Content-Length', len(ret_byte))
        // Confirmation of header information
        self.end_headers()
        // Write body data
        (ret_byte)
    def do_POST(self):
        self.send_response(400)
        self.end_headers()
    def do_PUT(self):
        self.send_response(400)
        self.end_headers()
    def do_DELETE(self):
        self.send_response(400)
        self.end_headers()
def start_server():
    http_server = HTTPServer((HOST, PORT_NUMBER), TestHttpHandler)
    print((), "Server Starts - %s:%s" % (HOST, PORT_NUMBER))
    try:
        http_server.serve_forever()
    except KeyboardInterrupt:
        pass
    http_server.server_close()
    print((), "Server Stops - %s:%s" % (HOST, PORT_NUMBER))
if __name__ == "__main__":
    start_server()

Above is a simple implementation of Http server-side details with Python, more information about Python Http server-side please pay attention to my other related articles!