G
G
guit242021-12-02 02:50:34
Django
guit24, 2021-12-02 02:50:34

How can I implement a check for the number of requests in a certain amount of time in jango using middleware?

please tell me how to use middleware to return an error if there have been more than k requests from the same ip address in the last n seconds. ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Kuts, 2021-12-02
@guit24

Yes, how - create middleware . In it, take the ip-address from the request header (for this, you first configure your web server so that it adds the desired header).
Next, execute code like this:

count = cache.get_or_set(f'ip:{ip_address}', 0, <нужное количество секунд>) 
count += 1
if count > <допустимое количество попыток>:
     raise Exception('Давай, - до свидания')
else:
     cache.set(f'ip:{ip_address}', count, <нужное количество секунд>)

Well, the most correct thing is to implement this logic on the side of the web server. He usually knows how to do it himself. And don't overload your middleware...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question