views:

834

answers:

5

Hi, 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.

+6  A: 

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.

phillc
A: 

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" )
Jiaaro
+1  A: 

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.

Fernando Gutierrez
+1  A: 

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.

Nixarn
Most likely because you were running some other web application at the same time in Apache, such as PHP, and that application was changing the timezone to be another value and screwing with the Django application. This issue is documented in mod_wsgi documentation at http://code.google.com/p/modwsgi/wiki/ApplicationIssues#Timezone_and_Locale_Settings.
Graham Dumpleton
A: 

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.

Klaas van Schelven