Question

I've had some problems with a Django application after I deployed it. I use a Apache + mod-wsgi on a ubuntu server. A while after I reboot the server the time goes foobar, it's wrong by around -10 hours. I made a Django view that looks like:

def servertime():
  return HttpResponse( datetime.now() )

and after I reboot the server and check the url that shows that view it first looks alright. Then at one point it sometimes gives the correct time and sometimes not and later it gives the wrong time always. The server time is corect though.

Any clues? I've googled it without luck.

Was it helpful?

Solution 2

I found that putting wsgi in daemon mode works. Not sure why, but it did. Seems like some of the newly created processes gets the time screwed up.

OTHER TIPS

Can I see your urls.py as well?

Similar behaviors stumped me once before...

What it turned out to be was the way that my urls.py called the view. Python ran the datetime.now() once and stored that for future calls, never really calling it again. This is why django devs had to implement the ability to pass a function, not a function call, to a model's default value, because it would take the first call of the function and use that until python is restarted.

Your behavior sounds like the first time is correct because its the first time the view was called. It was incorrect at times because it got that same date again. Then it was randomly correct again because your apache probably started another worker process for it, and the craziness probably happens when you get bounced in between which process was handling the request.

datetime.now() is probably being evaluated once, when your class is instantiated. Try removing the parenthesis so that the function datetime.now is returned and THEN evaluated. I had a similar issue with setting default values for my DateTimeFields and wrote up my solution here.

Maybe the server is evaluating the datetime.now() at server start, try making it lazy through a template or use a variable in your view.

Take a look at this blog post.

Django sets the system time zone based on your settings variable TIME_ZONE. This may lead to all kinds of confusion when running multiple Django instances with different TIME_ZONE settings.

This is what Django does:

os.environ['TZ'] = self.TIME_ZONE

The above answer:

"I found that putting wsgi in daemon mode works"

does not work for me...

I think I'm going with not using django's built in TIME_ZONE anymore.

you may need to specify the content type like so

def servertime():
  return HttpResponse( datetime.now(), content_type="text/plain" )

another idea:

it may not be working because datetime.now() returns a datetime object. Try this:

def servertime():
  return HttpResponse( str(datetime.now()), content_type="text/plain" )

Try to set your time zone (TIME_ZONE variable) in settings.py

That worked for me.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top