[Python] Asynchronously running a function in the background while sending results in Python

Discussão em 'Python' iniciado por Stack, Março 14, 2025.

  1. Stack

    Stack Membro Participativo

    I have a Python script which I would like to a) Continuously listen for requests from an API, and b) Run an expensive algorithm continuously in the background. The results from the algorithm are saved locally to a file (results.json), and if the API requests the result, I would like to load current results from disk and send it to the endpoint.

    I've provided a simplified sketch of the code logic below. However I'm not sure how to structure it so that algo.run runs in the background constantly, while Main.send periodically does the API calls. Since both are blocking operations, should I be using async def in the methods in Algorithm as well? In addition, how would I handle the edge case where Main.send tries to read the file from disk, while algo.run is trying to save the file at the same time?

    Any suggestions would be greatly appreciated!

    import json
    import random
    import time

    ENDPOINT = 'http://some_api.com/endpoint' # Some external API

    class Main:
    def __init__(self):
    algo = Algorithm()

    # self.send() ## These would block
    # algo.run()

    async def send(self):

    # Continuously listen on an endpoint
    while True:

    response = requests.get(ENDPOINT).json()
    if response['should_send']:

    # Load the result from disk
    with open('results.json', 'r') as file:
    outputs = json.load(file)

    # Send results to API
    requests.post(ENDPOINT, outputs)

    time.sleep(60)

    class Algorithm:
    def __init__(self):
    pass
    def run(self):
    # Some expensive computations, running repeatedly in background
    while True:
    outputs = {'result' : random.random()}
    time.sleep(60)

    # Save result to disk
    with open('results.json', 'w') as file:
    json.dump(outputs, file)

    Continue reading...

Compartilhe esta Página