Search code examples
pythonraspberry-piwebserver

Reacting to Webrequest while answering it - Python 3.7


I'm currently trying to figure out how I can host a simple webserver to handle POST requests with Python 3.7. My problem is that I want to answer requests after they were received, but the submitted POST data should be used to play back a specific audio file on my RaspberryPi. In two days of googling I couldn't figure out how to have the webserver run constantly while processing the incoming requests in the background.

I tried to use the subprocess module to run the playback script in the background but I never found a way to have it run in the background independently from the webserver. I always end up with my webserver getting a request which is than handled, but while this happens the webserver is unaccessible.

I would apreciate if someone pointed out a direction to look at for me.


Solution

  • I always end up with my webserver getting a request which is than handled, but while this happens the webserver is unaccessible.

    To solve this problem, you can create a separate thread or a process to handle the request while the main thread/process goes back to processing new requests.

    The workflow will be something like this:

    1. The main process receives a request
    2. The main process creates a new process to handle the request.
    3. The main process goes back to listening for new requests while the new process processes the received request.

    Assuming, you are unfamiliar with multithreading and multiprocessing, I'd suggest you go read a little about these topics. Most likely, multithreading will solve your problem. So, you can start from there. Here's a good article about it: An Intro to Threading in Python