[Python http.server] Build an http server for downloading/uploading files

Motivation: The author needs to test the file upload and download performance under the bs architecture, so I want to build an http server through Python and realize the file upload and download requirements between the client and the server.

Difficulty: This should be a very basic thing, but the author has never been exposed to http programming before. I would like to record the learning process here. It may not be the optimal solution.

Method: Deploy the html page on the server side, execute the monitoring Python code, and operate on the client side to upload and download files.

1 [Server] Create a local folder to enable http service

First open the power shell and create a folder locally on the server to enable the http service. For example, create an E:\WebServer folder, as shown in the figure:

 Enter power shell and enter the command:

cd E:\WebServer

Enter the enable http command:

python -m http.server

The following situation indicates success:

 At this time, we can enter the local IP address + port number in the server's browser address bar to access the http page, for example:

http://172.1.1.1:8000

 As for the local IP address, you can right-click "Network", click on the blue word of your network connection, and view the IPv4 address in the detailed information, as shown in the figure:

 At this point, the page in the browser should look like this:

When you see this page, the first step is completed!


2 [Server] Write a listening script for client to upload files

Create a Python script in the root folder of the server (it should work if created elsewhere, I haven’t tried it):

from http.server import BaseHTTPRequestHandler, HTTPServer
import time


# 创建自定义的请求处理类
class FileUploadHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        start_time = time.time()
        content_length = int(self.headers['Content-Length'])
        # 读取客户端发送的二进制文件数据
        file_data = self.rfile.read(content_length)

        # 在这里可以对接收到的文件数据进行处理,例如保存到磁盘
        with open('uploaded_file.bin', 'wb') as file:
            file.write(file_data)

        self.send_response(200)
        self.end_headers()
        self.wfile.write(b'File uploaded successfully.')

        end_time = time.time()
        time_elapsed_ms = int((end_time - start_time) * 1000)
        print(f"Update in {time_elapsed_ms} ms")


# 启动服务器
def run_server():
    server_address = ('your web server', 8000)  # 可以根据需要修改端口号
    httpd = HTTPServer(server_address, FileUploadHandler)
    print('Server running on port 8000...')
    httpd.serve_forever()


# 运行服务器
run_server()

Note ,enter your own IP address at 'your web server'


3 [Server] Write html script to display the upload file interface

<!DOCTYPE html>
<html>

<head>
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.6.0.js" type="text/javascript"></script>
    <!-- <script src="./jquery-3.6.0.js" type="text/javascript"></script> -->
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
</head>

<body>
    <form id="uploadForm" action="/upload" enctype="multipart/form-data" method="post" onsubmit="return submitFile()">
        <div><input type="file" name="file" multiple></div>
        <br>
        <div><input type="submit" value="upload"> </div>
    </form>
    <script>
        function submitFile() {
            // formData = new FormData($('#uploadForm')[0])
            files = $('#uploadForm')[0].file.files
            for (i = 0; i < files.length; i++) {
                $.ajax({
                    url: "/upload?fileName=" + encodeURIComponent(files[i].name),
                    type: "POST",
                    data: files[i],
                    success: function (data) {
                        console.info("success", data);
                    },
                    error: function (data) {
                        console.warn("fail", data);
                    },
                    processData: false,
                    contentType: "multipart/form-data",
                    // contentType: "application/octet-stream"
                });
            }
            return false;
        }
    </script>
</body>

</html>

The above code refers to: python HTTPServer implements file upload and download_xiekch's blog-CSDN blog  

Write the above code into a notepad file, save it as an html file, put it in the server root directory, and name it index.html

The http page will be changed to the predetermined style. That is, when the http page is opened again at this time, it should appear:


4 [Client] Write a script to upload files

Use another computer to act as a client and write a Python script to upload files:

import requests
import os

# 指定服务器URL和要上传的文件路径
server_url = 'http://your web server:8000/upload'
file_path = '/your file path/file.bin'

testResponse = requests.get(server_url)
if testResponse.status_code == 200:
    print("与服务器的连接正常!")
else:
    print("无法连接到服务器!")

with open(file_path, 'rb') as file:
    file_data = file.read()

response = requests.post(server_url, files={'file': 'file'})

if response.status_code == 200:
    print("文件上传成功!")
else:
    print("文件上传失败!")

Also note ,enter your IP address in 'your web server' and write the file path in your file path

Under Windows systems, the file path can use double slashes:

http://172.1.1.1:8000//data.bin

 Under the MacOS system, the following formats can currently be used for testing:

'/users/north/desktop/data.bin'

[Client] Write a script to download files

Similarly, use another Python file to write a download file script:

import time
import requests

response = requests.get("http://your web server:8000//file.bin")
with open("data.bin", "wb") as f:
f.write(response.content)

Again ,enter your IP address at 'your web server'


[Client] Implementation effect

After the above steps are fully prepared, run the [server] listening script . At this time, the Python IDE's Terminal window should prompt:

At the same time, the script should be running all the time (if the stop button is currently displayed, it means it is running continuously) to continue to monitor:

 At this time, run the download file script of [Client] to download the target file in the server. The author has also written a function to record the download time. The following results indicate that the download is successful. Of course, you can also use a similar method to upload The judgment mechanism of the price inquiry script determines whether the file is downloaded successfully.

Enter the http address of the server in [Client] and select a local file to upload:

Similarly, the following message appears on the [server] listening terminal, indicating that the upload is successful:

 A temporary file will appear in the root directory of [Server] . If you need to further process the temporary file, you can further modify the script.

Revision 230524 : You need to enter the upload file page on the client before running the server-side monitoring script, otherwise an Error will occur. Since it does not affect the function implementation for the time being, the cause has not yet been studied. 


The End

Guess you like

Origin blog.csdn.net/Norths_/article/details/130728255