I created a simple fastapi server to receive webhook, and whenever there is a webhook signal, it calls the function printmessage() with a new process and to print out the message "WEBHOOK RECEIVED". And the code appears to work, but whenever there is a new webhook, my server will restart again which is not what I intend to do and it seems that the problem comes from calling the function, it appears that whenever a function is called, it will run the main.py all over again ("PROGRAM LAUNCH..." is printed out when new webhooks received but it suppose only run once) instead running once only, but I just want the program to run the function print message()only instead running all the code all over again, how can I solve this issue? It appears to be the problem when using multiprocessing, how should I edit my code to prevent it restarting every time when there is new webhook signal?
I run the command: uvicorn main:app
#main.py
import time
from fastapi import Request, FastAPI
import multiprocessing as mp
def printmessage():
print("WEBHOOK RECEIVED")
app = FastAPI()
print("PROGRAM LAUNCH...")
print("WEBHOOK RECEIVE READY...")
@app.post("/webhook")
async def webhook(request : Request):
p = mp.Process(target=printmessage)
p.start()
return 'WEBHOOK RECEIVED'
OUTPUT:
INFO: Started server process [21840]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: 127.0.0.1:64595 - "POST /webhook HTTP/1.1" 200 OK
PROGRAM LAUNCH...
WEBHOOK RECEIVE READY...
WEBHOOK RECEIVED
INFO: 127.0.0.1:64614 - "POST /webhook HTTP/1.1" 200 OK
PROGRAM LAUNCH...
WEBHOOK RECEIVE READY...
WEBHOOK RECEIVED
INFO: 127.0.0.1:64932 - "POST /webhook HTTP/1.1" 200 OK
PROGRAM LAUNCH...
WEBHOOK RECEIVE READY...
WEBHOOK RECEIVED
INFO: 127.0.0.1:64932 - "POST /webhook HTTP/1.1" 200 OK
PROGRAM LAUNCH...
WEBHOOK RECEIVE READY...
WEBHOOK RECEIVED
INFO: 127.0.0.1:64932 - "POST /webhook HTTP/1.1" 200 OK
PROGRAM LAUNCH...
WEBHOOK RECEIVE READY...
WEBHOOK RECEIVED
INTENDED OUTPUT:
This is the output I wanted to be, I achieved this result by just calling the function without creating a new process (without multiprocessing), just by calling the function printmessage().
INFO: Started server process [22624]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
WEBHOOK RECEIVED
INFO: 127.0.0.1:65079 - "POST /webhook HTTP/1.1" 200 OK
WEBHOOK RECEIVED
INFO: 127.0.0.1:65079 - "POST /webhook HTTP/1.1" 200 OK
WEBHOOK RECEIVED
INFO: 127.0.0.1:65079 - "POST /webhook HTTP/1.1" 200 OK
WEBHOOK RECEIVED
INFO: 127.0.0.1:65079 - "POST /webhook HTTP/1.1" 200 OK
WEBHOOK RECEIVED
INFO: 127.0.0.1:65079 - "POST /webhook HTTP/1.1" 200 OK