Python's http-based network communication and website port exposure; Python network programming's python application of HTTP protocol

1. Overview of HTTP protocol

HTTP (Hypertext Transfer Protocol) is a protocol used by web applications to transfer HTML pages and data between web browsers and web servers. HTTP is based on the TCP/IP protocol to transmit data and is a stateless protocol.

Key Features:

Supports client/server mode: the web browser acts as an HTTP client and sends an HTTP request to the HTTP server through the URL, and then the HTTP server will return the HTTP response to the client;
Simple and fast : When the client requests the server, it only needs to pass a simple HTTP request, and the server only needs to return a simple HTTP response when responding. The HTTP protocol has fast communication speed and is suitable for Hypermedia-based systems in distributed environments;
Flexible: HTTP protocol can allow the server to perform different processing by sending different request methods, request headers, etc.;
No connection: After the client sends a request, the server will disconnect after responding to the request. The HTTP server takes a short time to maintain each connection, and it does not limit the number of requests sent by the client. This allows for faster responses to user requests.

2. Python implements HTTP requests

  1. requests library
    The requests library is a third-party library for Python to implement HTTP requests. It provides a simpler HTTP request interface, which is easy to learn and is very suitable for web testing and crawling. development.

installation method:

pip install requests

Instructions:

import requests

url = "http://www.baidu.com"
response = requests.get(url)
print(response.content.decode())

Detailed explanation:

Use the requests.get() function to initiate a GET request and store the response object in the response variable;
Call the content attribute of the response object to obtain the byte stream data of the response content. And use the decode() function to decode it into a string type;
Output the obtained response content

  1. urllib library
    The urllib library is Python's own HTTP request library. It is also a basic way for Python to implement HTTP requests. It is more suitable for beginners to learn and use.

Instructions:

import urllib.request

url = "http://www.baidu.com"
response = urllib.request.urlopen(url)
print(response.read().decode())

Detailed explanation:

Use the urllib.request.urlopen() function to initiate a GET request and store the response object in the response variable;
Call the read() function of the response object to obtain the word of the response content Throttle the data and use the decode() function to decode it into a string type;
Output the obtained response content.

3. Python implements HTTP server

To implement an HTTP server in Python, you can use the built-in http.server module, which provides processing and parsing of the HTTP protocol.

  1. Simple example
    The following is a simple example to implement a simple HTTP server that can return different response content according to different requests:
from http.server import SimpleHTTPRequestHandler, HTTPServer

class MyHTTPRequestHandler(SimpleHTTPRequestHandler):

    def do_GET(self):
        if self.path == '/':
            self.path = '/index.html'
        return SimpleHTTPRequestHandler.do_GET(self)

if __name__ == '__main__':
    server = HTTPServer(('', 8000), MyHTTPRequestHandler)
    print('Serving HTTP on localhost port 8000...')
    server.serve_forever()

Detailed explanation:

Create a subclass inherited from the SimpleHTTPRequestHandler class, and override the do_GET method to return different response content by judging the request path;
Create an HTTPServer in the __main__ function Object, specify the server address, port and processor;
Call the serve_forever method of the HTTPServer object to start the HTTP server and specify that the service status remains running.

  1. Flask framework example
    The following is an example of using the Flask framework to implement an HTTP server:
from flask import Flask, request

app = Flask(__name__)

@app.route('/')
def home():
    return '<h1>Hello Flask!</h1>'

@app.route('/user/<name>')
def user(name):
    return f'<h1>Hello,{
      
      name}!</h1>'

Detailed explanation:

Import the Flask framework, create a Flask object instance, and specify the name of the current module through the __name__ parameter;
Use the @app.route() decorator to define routes and views Function, returns the response content through the return statement;
Calls the run method of the Flask object instance to start the HTTP server.

Guess you like

Origin blog.csdn.net/weixin_39589455/article/details/134898798