Instructions for Creating an HTTP Server in Python

Introduce

What is a web server?

overview

  • A web server is a computer that stores web content.
  • A web server used to serve websites on the internet or intranet.
  • It stores pages, scripts, progarmsor files multimediaand use the protocol HTTPto send the file to the web browser.
  • Some famous web servers such as Nginx web server , Apache web server , IIS web server , Light Speed web server .

Method of web server or dynamic.

  • For example, the user wants to see a website such as www.google.com, the user enters the url into the web browser provided the user needs an Internet connection. The protocol set TCP/IPis then used to establish the connection.
  • When the connection is established, the client sends a request through HTTPand waits for a response from the server. On the other side, the server receives the request, processes the request, and sends the response back to the client.

HTTP protocol

  • The protocol HTTPstands for Hyper Text Transfer Protocol.
  • It is an application-layer protocol that allows web applications to communicate and exchange data.
  • It is a protocol based TCP/IP.
  • It is used to provide content: hình ảnh, âm thanh, video, tài liệu
  • Using HTTPis the most convenient way to move data quickly and reliably on the web.

Example of HTTP message

How to create HTTP Server in python

Python has a number of built-in libraries to make web serverit easier. For example, you can create one SimpleHTTPServerwith a simple command:

  • With python2
python -m SimpleHTTPServer + port (if not write anything default is 8000)
  • With python3
python3 -m http.server + port (if not write anything default is 8000)

But you cannot customize your server.

Create an HTTPServer Project

Create HTML and CSS files

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/main.css">
</head>
<body>
    <h1>Sun* Cyber Security Research</h1>
</body>
</html>

main.css

@import url('https://fonts.googleapis.com/css?family=IBM+Plex+Sans+Condensed:100,200,300,400');

body{
    background-color: #222;
}

h1{
    color: white;
    padding: 20px 40px;
    margin: 0 auto;
    background-color: rgba(255, 255, 255, .7);
    display: inline-block;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateY(-50%) translateX(-50%);
    border-radius: 4px;
    border-bottom: 5px solid rgba(150, 150, 150, 1);
    font-weight: 200;
    font-family: 'IBM Plex Sans Condensed', sans-serif;
}

Project setup

server.py

from http.server import BaseHTTPRequestHandler
import os
class Server(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.path = '/index.html'
        try:
            split_path = os.path.splitext(self.path)
            request_extension = split_path[1]
            if request_extension != ".py":
                f = open(self.path[1:]).read()
                self.send_response(200)
                self.end_headers()
                self.wfile.write(bytes(f, 'utf-8'))
            else:
                f = "File not found"
                self.send_error(404,f)
        except:
            f = "File not found"
            self.send_error(404,f)

from http.server import BaseHTTPRequestHandler
import os
  • BaseHTTPRequestHandler is used to handle HTTP requests to the server.
  • Also BaseHTTPRequestHandlersupports some of the following properties and methods:
  • do_GET(): This method deals with GET requests.
  • do_POST(): This method deals with POST requests.
  • path: This property returns the path of the request.
  • send_error(): This method returns an HTTP error to the client.

First define a means do_GET(). This method runs when there is a GET request sent.

  • self.path == ‘/’ check if the post request is an index page and if it’s a page indexthen assign the path to the index self.path == '/ index.html` .
  • Next try to read the files that the user is trying to access except to file pythonavoid leaks source code.
  • If the requested file is found, the server sends a response 200200is the response that whenever you visit a website successfully.
  • If the requested file cannot be found, serveran invalid request file error code is sent.
  • Use the bytes()encode method utf-8to convert text to bytes.

main.py

import time
from http.server import HTTPServer
from server import Server

HOST_NAME = 'localhost'
PORT = 8000

if __name__ == "__main__":
    httpd = HTTPServer((HOST_NAME,PORT),Server)
    print(time.asctime(), "Start Server - %s:%s"%(HOST_NAME,PORT))
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    print(time.asctime(),'Stop Server - %s:%s' %(HOST_NAME,PORT))
import time
from http.server import HTTPServer
from server import Server
  • Time used to control time startand stopserver.
  • HTTPServer is a subclass of socketserver.TCPServer that creates and listens for HTTP sockets, sends requests to the processor.

Configure the server with two constants HOST_NAME = 'localhost',PORT = 8000with which HOST_NAME = 'localhost'to run the server on localhost and which PORT = 8000is the port where the application will be run.

httpd = HTTPServer((HOST_NAME,PORT),Server)

  • Call the HTTPServer that python provides with the first argument as a pair (HOST_NAME,PORT)and the second argument as a class Serverto handle that was set earlier.
try:
    httpd.serve_forever()
except KeyboardInterrupt:
    pass
httpd.server_close()
print(time.asctime(),'Stop Server - %s:%s' %(HOST_NAME,PORT))
  • The next block to startand the stopserver, when receiving an interrupt signal from the server keyboard will close the connection httpd.server_close().

Now we start the server by running the command:

python3 main.py

So we have successfully created a simple HTTP Server with python, in addition we can write more methods such as the HEAD, POST ...Server can handle more methods.

#python #programming

Instructions for Creating an HTTP Server in Python
34.40 GEEK