Search code examples
pythonflaskriot-games-api

Python Flask timed queuing script


I just started using Flask, and I'm creating a web application that does two main things server side: Accessing another online API (which I can only send so many requests to per second) and sending page requests to a user connecting to the server.

When a user connects to my Flask server, it will send the user's browser a page, then an AJAX script on that page will populate the page with data (this is done for UI performance). This data comes from another API (the League of Legends API), but there is a rate limit set on the number of calls I can make per second, so I must make a queuing script.

Currently, I plan on using a time.sleep() function after every call, but I'm worried that this will prevent the server from doing anything else. I still want the server to be responding to page requests while the API calls are being delayed.

For this, should I use multiprocessing, or does Flask have something built in to handle this? Or should I install a specific plugin for this?

Thanks!


Solution

  • I think the recommended way of doing this is by using an asynchronous task queue/job like celery

    Using it is very simple, you just need to put @app.task for functions you need to run in the background:

    from celery import Celery
    
    app = Celery('tasks', broker='amqp://guest@localhost//')
    
    @app.task
    def add(x, y):
        return x + y
    
    result = add.delay(2, 2)
    

    It has many features and functionalities and it'll do the job for you. You can refer to the doc for more information.