0

So if a user access a file, this creates a link which is accessible for 3 minutes. On my MongoDB the fields are.

page_link:'link_to_file1',
date_expires: ISODate("2017-06-14T04:30:39.380Z")

So when the user access the same file, again.

I'll check if the date_expires of the page_link is less than the current time

links = PageLink.objects(page_link = url).first()
date_expires = links.date_expires
current_date = datetime.now()

if str(date_expires) < str(current_date):
    #generate a new link.
    current_date = datetime.now()
    date_expires = current_date + timedelta(minutes = 3)
    new_link = PageLink(page_link = url, date_expires = date_expires)
    new_link.save()
    links = PageLink.objects(page_link = url).first()
    final_url = links.page_link
else:
    #use existing link

So when I access a file, if 3 minutes had already elapsed (or date_expires is less than current_date), then I will save a new page_link with SAME name but different date_expires.

The problem is,

links = PageLink.objects(page_link = url).first()

This code always get the first record. When I run the code, it always execute the "if" not the "else" so it generates a new link with SAME name but different expiration.

How to get the last record instead of the first one? Thanks!

Julio de Leon
  • 1,032
  • 3
  • 14
  • 30
  • I think I should make the date_expires a ListField? Then get the last one, if the date_expires is less than current_date then I'll update it by adding a new date_expires in the ListField. – Julio de Leon Jun 14 '17 at 05:40
  • 1
    Would you not simply sort? `PageLink.objects(page_link = url).order_by('-date_expires').first()`. I think you can even make that more efficient for looking for a `date_expires` that is "greater than" the current time as well `PageLink.objects(page_link = url, date_expires__gt = datetime.now()).order_by('-date_expires').first()` or something like that. – Neil Lunn Jun 14 '17 at 05:45
  • *@NeilLunn* `PageLink.objects(page_link = url).order_by('-date_expires').first()` solves my problem. Thanks!! – Julio de Leon Jun 14 '17 at 05:56

0 Answers0