taskiq icon indicating copy to clipboard operation
taskiq copied to clipboard

Add middleware, which will allow to use various functions to determine the delay time before sending

Open chandr-andr opened this issue 3 years ago • 8 comments
trafficstars

chandr-andr avatar Sep 02 '22 15:09 chandr-andr

Hi I think I can solve this ... I think you should try this ... if it is of any use then please merge it.... if possible please assign me this.... this my first time contributing to this big repository

Transyltooniaa avatar Sep 30 '23 13:09 Transyltooniaa

Hi, @Transyltooniaa. Thank you for your interest in this project. You're now assigned.

s3rius avatar Sep 30 '23 13:09 s3rius

Here is the implementation (DO let me know if you want anything different :

import time
import random

app = Flask(__name__)

# Define custom delay functions
def random_delay():
    return random.uniform(0, 1)  # Random delay between 0 and 1 second

def fixed_delay():
    return 0.5  # Fixed delay of 0.5 seconds

def custom_delay():
    # Implement your custom delay logic here
    return 1.0  # Custom delay of 1 second

# Middleware to determine delay time
@app.before_request
def determine_delay():
    delay_function = request.args.get('delayFunction')

    if delay_function:
        delay_function = delay_function.lower()
        if delay_function == 'random':
            delay_time = random_delay()
        elif delay_function == 'fixed':
            delay_time = fixed_delay()
        elif delay_function == 'custom':
            delay_time = custom_delay()
        else:
            delay_time = 0  # No delay if the function is not recognized
    else:
        delay_time = 0  # No delay if no function is specified

    if delay_time > 0:
        print(f"Delaying response by {delay_time} seconds")
        time.sleep(delay_time)

# Example route
@app.route('/api/resource')
def get_resource():
    return jsonify({'message': 'Resource retrieved successfully'})

if __name__ == '__main__':
    app.run(debug=True)

Transyltooniaa avatar Sep 30 '23 13:09 Transyltooniaa

Please fork repo, push changes and make a Pull Request. We will discuss everything within it.

s3rius avatar Sep 30 '23 13:09 s3rius

ok. got it

Transyltooniaa avatar Sep 30 '23 13:09 Transyltooniaa

Just to confirm .... can you please tell in which file do I push my code in ?

Transyltooniaa avatar Sep 30 '23 13:09 Transyltooniaa

Try creating a new middleware module here:

https://github.com/taskiq-python/taskiq/tree/develop/taskiq/middlewares

s3rius avatar Sep 30 '23 13:09 s3rius

please add the hacktoberfest label and review my pr . thanks

Transyltooniaa avatar Sep 30 '23 19:09 Transyltooniaa