Home > Enterprise >  datetime.date.today() always returns the same value
datetime.date.today() always returns the same value

Time:10-27

I have a Django project. I use nginx gunicorn. The views.py file has a combined_data() function that creates and returns an HTML page. As you can see, I am passing the objects in 'rows' and the current date in 'time'.

enter image description here

A function that returns objects looks like this

enter image description here

The problem is that in this function, reporting_date always gets the value it got the first time it was called. For example, I do "sudo systemctl restart gunicorn" and open this page in the browser. reporting_date will be equal to today. If I open the page tomorrow, reporting_date will not change its value.

Initially, I assumed that datetime.date.today () does not work correctly, so I added the 'time' parameter to views.py (first screen), but the date is always correct there. Then I thought that the default value of the parameters of the get_combined() function (second screen) is somehow cached, so I added the r_int parameter, which receives a random value, but everything works correctly here. r_int always gets a new value.

Now, I have to call "sudo systemctl restart gunicorn" every day to make the page work properly ((

Any ideas how to fix this problem? Thanks

CodePudding user response:

The default value for the parameter reported_date is the value of the first time the function gets imported. You should do something like

def get_combined(reported_date=None, ...):
    reported_date = reported_date or datetime.datetime.today()
    ...

CodePudding user response:

Instead of

def get_combined(reported_date=datetime.datetime.today()):

use

def get_combined():
    reported_date = datetime.datetime.today()

What I tried:-

>>> def c(day = datetime.today()):
        print(day)

    
>>> c()
>>> 2022-10-27 15:44:57.593444
>>> c()
>>> 2022-10-27 15:44:57.593444
>>> def c():
        day = datetime.today()
        print(day)

    
>>> c()
>>> 2022-10-27 15:56:02.459517
>>> c()
>>> 2022-10-27 15:56:04.630902

As @OldBill mentioned: When you declare a default value for a function parameter it is evaluated once and not every time the function is called

  • Related