Created
November 3, 2021 02:22
-
-
Save gxara/dc13c18bb705dcb7b73cb7ec9d4b5a47 to your computer and use it in GitHub Desktop.
Exemplo de processamento assíncrono com Flask e multiprocessing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, current_app | |
from multiprocessing import Queue, Process | |
import time | |
def slow_job_to_be_processed_async(fifo): | |
while True: | |
seconds_to_sleep = int(fifo.get()) | |
print( | |
f"Gabriel salvando indicação de modelo no BD... Vai levar {seconds_to_sleep} segundos") | |
time.sleep(seconds_to_sleep) | |
print( | |
"Gabriel salvou resultado no BD... E o Marco Polo não precisou ficar esperando") | |
fifo.qsize() | |
app = Flask(__name__) | |
fifo = Queue() | |
app.config["queue"] = fifo | |
P = Process(target=slow_job_to_be_processed_async, args=(fifo, )) | |
P.daemon = True | |
P.start() | |
@app.route('/api/<workload_time>') | |
def endpoint_with_heavy_workload(workload_time): | |
current_app.config["queue"].put(workload_time) | |
return f'Trabalho inserido na fila', 201 | |
if __name__ == "__main__": | |
app.run(host="0.0.0.0", threaded=True, port=int(5000)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment