I'm new to django, i'm currently working with API using Django Ninja Rest Framework .
in this example, users will have a unique APIKey each time i create new APIKey from this model and attach it to selected user.
this is my APIKey model:
### NOTE - This is just for testing, Not a real model, see the link below
class APIKey(models.Model):
key = models.CharField(max_length=64) # i know this should be unique, just for demo :)
user = models.ForeignKey(get_user_model(), related_name='free_key', on_delete=models.CASCADE)
label = models.CharField(max_length=40)
revoked = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
expires_at = models.DateTimeField(null=True, blank=True)
This model is just for testing purposes , I actually use this for my project and modify it.
So, My API endpoints need an API key for authentication (the API key that i have created that correspond to a specific user),
then i implement and follow the steps here and it works normally
My questions are:
Each user has a unique API key. How to count and store the total request from a user each time user makes a request to an endpoint? Should i add request_total
field to my APIKey
model or create a new Model? Should i use custom middleware? or should i use Redis or something? if so, how to implement it?
What's the best way for this scenario to implement a daily limit by the total request from a user? for example , the user daily limit request is 100 requests, and reset every 00:01AM
According to question number 1, what's the recommended way to filter the total request and show it to the corresponding user? for example , in Django Views, showing the total request each day from the last 7 days
As a piece of additional information , my API endpoints are mostly GET method and perform a function call, do some calculation or something, and return some data, not querying the database (Model.objects.get(id=id), etc...)
,
I apologize if my question doesn't make any sense, Thankyou...
I would do the following
class ApiRequest(models.Model): key = models.ForeignKey(APIKey) timestamp = models.DateTimeField(auto_now_add=True, db_index=True)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.