Serve and request in the same python script

I am trying to briefly spin up an HTTP server, so that I can call a subprocess that needs to access local files over HTTP, but running the server using the following code blocks further code from …

问题描述:

I am trying to briefly spin up an HTTP server, so that I can call a subprocess that needs to access local files over HTTP, but running the server using the following code blocks further code from executing:

import http.server
import socketserver

PORT = 8000

Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()
    print('Hello, server!')  # Never executed

What is the simplest way to spin up the server, make requests, and then close the server, all from the same script?

解决方案 1:[1]

It looks like you are using code from the documentation, which is good!
https://docs.python.org/3/library/http.server.html?highlight=simplehttprequesthandler#http.server.SimpleHTTPRequestHandler

{SimpleHTTPRequestHandler} is just made to work this way. The issue is that server_forever is never meant to return. Most processes like this are meant to be shut down from the server (via a cronscript or similar or manually) and not an external request.

How many requests do you want the server to serve? You would have to inherit from {SimpleHTTPRequestHandler} and change the behavior you don’t like or else create your own handler with the specific logic you want.

For an example of what I mean, a user comes and transfers one file. Should your server shut down then? What if they want to transfer another file? If you’re not using it that much, you could start it from a script that keeps it open 5 minutes and then kills the process if there are no active transfers or something.

If you want something with more complex behavior, you are going to have to write a more complex handler.

If you can add more info, I will update my answer.

解决方案 2:[2]

You can use threading and requests to do this. Here’s a small working example of a Python script that spins up an HTTP server, then talks to it in the same program. It will display the contents of test.txt using a request to http://localhost:8000/test.txt. It waits one second then ends the server.

import http.server
import socketserver
import threading
import requests

# create a test file
with open("test.txt", "w") as file:
    file.write("hello!")

PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler

def run_server():
    with socketserver.TCPServer(("", PORT), Handler) as httpd:
        print("serving at port", PORT)
        httpd.serve_forever()

server_thread = threading.Thread(target=run_server)
# set daemon to true so that the thread exits when the main program is done
server_thread.daemon = True
server_thread.start()

print('Hello, server!')

response = requests.get('http://localhost:8000/test.txt')

if response.status_code == 200:
    print("Content of 'test.txt':")
    print(response.text)
else:
    print(f"Error: {response.status_code}")

print('Goodbye, server!')

# Give the server a moment to finish processing any pending requests before the script exits
server_thread.join(timeout=1)

# Clean up test.txt
import os
os.remove("test.txt")

参考链接:

Copyright Notice: This article follows StackOverflow’s copyright notice requirements and is licensed under CC BY-SA 3.0.

Article Source: StackOverflow

[1] bikemule

[2] Brock Brown

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(1)
青葱年少的头像青葱年少普通用户
上一篇 2022年10月8日 下午9:21
下一篇 2023年4月29日

相关推荐