Reputation: 1689
I have written a middleware and I would like some suggestions on how I could improve my code. I have a model that saves the date and the url when a new instance of it is created (in a middleware, so everytime a url is visited).
Like so:
Middelware:
class GetUrlMiddleware():
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# before view
urltime = UrlTime.objects.create(associated_url=request.path)
urltime.save()
response = self.get_response(request)
# after view
return response
Model:
class UrlTime(models.Model):
url_track_model = models.ForeignKey(UrlTrack, blank=True, null=True, on_delete=models.CASCADE)
associated_url = models.CharField(blank=True, null= True, max_length=250)
timestamp = models.DateTimeField('Url viewed on: ',default=datetime.now, blank=True)
Now, everytime I click a link, a new object is created with the url and the date. That all works fine.
I have the feeling this could be done better. Is there for instance a way in which I could add a column every time I click the link with the url? Or maybe some other better way?
Help is of course very much appreciated Thanks in advance!
Upvotes: 0
Views: 70
Reputation: 5833
You could use redis instead of an actual model for this and in conjunction with the HSET
and HGET
commands you could do the following:
from datetime import datetime
current_hits = redis_client.hget("links_hits", request.path) or []
current_hits.append(datetime.now())
redis_client.hset("links_hits", request.path, current_hits)
Upvotes: 1