I have a strange problem with a website running on Django 1.8 and Apache.
I am trying to display a list of next week's upcoming events. After making modifications to the model, making and applying my migrations on the website, and restarting Apache, everything shows up fine. I have a python script queries and displays next week's days worth of events on the website. This week-to-week rollover of events is scheduled to happen shortly after midnight on the Saturday before the events take place.
Unfortunately, the events are not showing up on Saturday until I manually reload the Apache service. Also, by the time Monday rolls around, the site is again displaying old information until I again reload the Apache service. After the Monday reload, everything works as it should until the next Saturday.
I've checked all the crons, and there's nothing running that should make the site behave this way. I've also checked the ctime and mtime on all of the files and it does not appear that they've been changed or modified. I've also checked through the script and can find nothing that would be causing this behaviour.
Does anyone know what might be causing this or have another approach to solving this problem?
Thank you.
Here's the relevant code...
views.py
def index(request, starttime = datetime.now(), version = False):
# starttime: Datetime object for when to begin looking for events. Index pages are always a week.
starttime = datetime.now()
endtime = starttime + timedelta(7)
event_list = getEventsDB(EventList(), start = starttime, end = endtime)
event_calendar = getEventsDB(
EventSeries.objects.get(event_slug = 'competition'),
start = starttime, end = starttime + timedelta(7))
highlight_title = 'Competitions'
t = loader.get_template('event/index.html')
c = RequestContext(request, {
'page_title': 'Events',
'highlight_title': highlight_title,
'event_list': event_list,
'highlight': event_calendar,
'event_series_list': EventSeries.objects.filter(active=True),
})
return HttpResponse(t.render(c))
Your problem is here:
def index(request, starttime = datetime.now(), version = False):
There starttime is evaluated when the method is defined, which happens when the module is first imported - in other words, when the server is restarted. Don't put values there; instead, leave the default as None and check in the function itself:
def index(request, starttime=None, version = False):
if starttime is None:
starttime = datetime.now()
Related
ok so im automating a a couple of fields in the image added. i have everything done but the start time and end time revert back to zero after i put them in.
here is my current code for automating this
`
def add_meeting_track(self):
Waiter().wait_timer(3)
self.driver.find_element(*SummitPage.add_meeting).click()
Waiter().wait_timer(3)
self.driver.find_element(*SummitPage.display_name).send_keys("Test01")
self.driver.find_element(*SummitPage.zoom_webinar_id).send_keys("91516169900")
s_time = self.driver.find_element(*SummitPage.evt_start_time)
self.driver.execute_script("arguments[0].value = '09:40:00';", s_time)
e_time = self.driver.find_element(*SummitPage.evt_end_time)
self.driver.find_element(*SummitPage.stream_link).send_keys("https://www.youtube.com/watch?v=oqk65aqfJBo")
self.driver.execute_script("arguments[0].value = '13:00:00';", e_time)
self.driver.find_element(*SummitPage.track_day).send_keys(1)
self.driver.find_element(*SummitPage.track).send_keys(1)
`
The situation
I have a celery task I am running at different timezone for each customer.
Basically, for each customer in my database, I get the timezone, and then I set up the celery task this way.
'schedule': crontab(minute=30, hour=14, nowfun=self.now_function)
Basically, what I want is the task to run at 14:30, at the customer timezone. Hence the now_function.
My now_function is just getting the current time with the customer timezone.
def now_function(self):
"""
return the now function for the task
this is used to compute the time a task should be scheduled for a given customer
"""
return datetime.now(timezone(self.customer.c_timezone))
What is happening
I am getting inconsistencies in the time the task run, sometimes they run at the expected time, so let's say 14:30 in the customer time zone, if the timezone is America/Chicago it runs at 20:30 and that is my expected behavior.
Some other days, it runs at 14:30, which is just the time in UTC.
I am tracking to see if there is a pattern in the day the task run at the correct time and the day the cards run at the incorrect time.
Additional Information
I have tried this on celery 4.4.2 and 5.xx but it is still has the same behavior.
Here is my celery config.
CELERY_REDIS_SCHEDULER_URL = redis_instance_url
logger.debug("****** CELERY_REDIS_SCHEDULER_URL: ", CELERY_REDIS_SCHEDULER_URL)
logger.debug("****** environment: ", environment)
redbeat_redis_url = CELERY_REDIS_SCHEDULER_URL
broker_url = CELERY_REDIS_SCHEDULER_URL
result_backend = CELERY_REDIS_SCHEDULER_URL
task_serializer = 'pickle'
result_serializer = 'pickle'
accept_content = ['pickle']
enable_utc = False
task_track_started = True
task_send_sent_event = True
You can notice enable_utc is set to False.
I am using Redis instance from AWS to run my task.
I am using the RedBeatScheduler scheduler from this package to schedule my tasks.
If anyone has experienced this issue or can help me to reproduce it, I will be very thankful.
Other edits:
I have another cron for the same job at the same time but running weekly and monthly but they are working perfectly.
weekly_schedule : crontab(minute=30, hour=14, nowfun=self.now_function, day_of_week=1)
monthly_schedule : crontab(minute=30, hour=14, nowfun=self.now_function, day_of_month=1)
Sample Project
Here is a sample project on GitHub if you want to run and reproduce the issue.
RedBeat's encoder and decoder don't support nowfun.
Source code: https://github.com/sibson/redbeat/blob/e6d72e2/redbeat/decoder.py#L94-L102
The behaviour you see was described previously: sibson/redbeat#192 (comment 756397651)
You can subclass and replace RedBeatJSONDecoder and RedBeatJSONEncoder.
Since nowfun has to be JSON serializable, we can only support some special cases,
e.g. nowfun=partial(datetime.now, tz=pytz.timezone(self.customer.c_timezone))
from datetime import datetime
from functools import partial
from celery.schedules import crontab
import pytz
from pytz.tzinfo import DstTzInfo
from redbeat.decoder import RedBeatJSONDecoder, RedBeatJSONEncoder
class CustomJSONDecoder(RedBeatJSONDecoder):
def dict_to_object(self, d):
if '__type__' not in d:
return d
objtype = d.pop('__type__')
if objtype == 'crontab':
if d.get('nowfun', {}).get('keywords', {}).get('zone'):
d['nowfun'] = partial(datetime.now, tz=pytz.timezone(d.pop('nowfun')['keywords']['zone']))
return crontab(**d)
d['__type__'] = objtype
return super().dict_to_object(d)
class CustomJSONEncoder(RedBeatJSONEncoder):
def default(self, obj):
if isinstance(obj, crontab):
d = super().default(obj)
if 'nowfun' not in d and isinstance(obj.nowfun, partial) and obj.nowfun.func == datetime.now:
zone = None
if obj.nowfun.args and isinstance(obj.nowfun.args[0], DstTzInfo):
zone = obj.nowfun.args[0].zone
elif isinstance(obj.nowfun.keywords.get('tz'), DstTzInfo):
zone = obj.nowfun.keywords['tz'].zone
if zone:
d['nowfun'] = {'keywords': {'zone': zone}}
return d
return super().default(obj)
Replace the classes in redbeat.schedulers:
from redbeat import schedulers
schedulers.RedBeatJSONDecoder = CustomJSONDecoder
schedulers.RedBeatJSONEncoder = CustomJSONEncoder
If I run this in VS Code, it gives me the correct local time:
from time import strftime
time = strftime("%H:%M %p")
print(time)
But if I use the same code in a Django project, my website displays a time which is 8 hours behind local time.
from time import strftime,localtime
def time_display(request):
context = {
"date":strftime("%b %d, %Y",localtime()), #DOESN'T DISPLAY LOCAL TIME
"time1": strftime("%H:%M %p",localtime()), #DOESN'T DISPLAY LOCAL TIME
"time3": strftime("%H:%M %p"), #DOESN'T DISPLAY LOCAL TIME
}
return render(request,'time_display.html',context)
How do I fix it to display correct local time where the webpage is being viewed?
Not an expert but you can change setting.py file like:
TIME_ZONE = 'Europe/London'
note: change Europe/London to your time zone.
You can find a list of timezone names here: http://en.wikipedia.org/wiki/List_of_tz_database_time_zones
I would like to run a script every five minutes in windows task scheduler. The script reads a JSON web-service of service requests and writes specified fields to an esri geodatabase.
For this process, there is a time stamp, with the information to query the time per service request.
My question is how do I create the logic in this script to say "Hey, I ran successfully for 12:00PM-12:05:59PM, something happened for 12:06-12:11:59, but I will run for 12:11-12:16:59, and since I am so nice I will grab data for 12:06-12:11."
the logic that I have built into my code so far is;
import datetime
DateofDataCreation = 2015-02-17 16:53:25
i = 5
Start = datetime.datetime.now()
now_minus_5 = Start - datetime.timedelta(minutes =i)
if DateofDataCreation >= now_minus_5:
WriteToDatabase
else:
print "No Current Data"
am not sure if I understand your question exactly. Based on what I think you are asking, try this:
import datetime
#If you change the time to be after now() then it will print "WriteToDatabase" .
#If the time is before then it will print "No Current "Data"
DateofDataCreation = datetime.datetime(2015,2,17,16,53,25)
i = 5
Start = datetime.datetime.now()
now_minus_5 = Start - datetime.timedelta(minutes =i)
if DateofDataCreation >= now_minus_5:
print("WriteToDatabase")
else:
print ("No Current Data")
I am new to Python. I need to create a door.lock file that contains the current date and time. Also, I need to overwrite this file every x minutes with a new file containing the current date and time. I'm using this as a pseudo lock file to allow me to test on run of the software whether or not the software crashed and how long ago it crashed. My issue is I can't seem to overwrite the file. I've only failed at creating and/or appending the file. I created the following as a test:
from datetime import datetime, timedelta
ending = False
LOCK_FILENAME = "door.lock" # The lock file
LOCK_FILE_UPDATE = True
MINS_LOCK_FILE_UPDATE = 1 # the (x) time in minutes to write to lock file
NEXT_LOCK_FILE_UPDATE = datetime.now()
lock_file = open(LOCK_FILENAME, "w")
now = datetime.now()
NOW_STRING1 = str(now.strftime("%Y-%m-%d_%a_%H:%M"))
lock_file.write(NOW_STRING1)
print "First Now String"
print NOW_STRING1
# ==============================================================================
#Main Loop:
while ending is False:
# ==============================================================================
# Check if it is time to do a LOCK FILE time update
now = datetime.now()
NOW_STRING1 = str(now.strftime("%Y-%m-%d_%a_%H:%M"))
if LOCK_FILE_UPDATE: # if LOCK_FILE_UPDATE is set to True in DM settings
if NEXT_LOCK_FILE_UPDATE <= datetime.now():
lock_file.write(NOW_STRING1)
print NOW_STRING1
NEXT_LOCK_FILE_UPDATE = datetime.now() + timedelta(minutes=MINS_LOCK_FILE_UPDATE)
Will someone pinpoint my error(s) for me? TIA
When I cat the above file, door.lock, it is empty.
You need to push buffer to file. You can do it with a close() and re-open for next write.
lock_file.close()
...
lock_file = open(LOCK_FILENAME, "a")
If you are logging events you'd be better using a logger instead of a plain text file.
Solution from #MAC will work except it will append and seems that you don't want to do that so just open again with the 'w' option or yet better, use the 'w+' option so it can be truncated (which for what I get it is what you want to do) and read.
Also, consider your changes won't get written down until you close the file (having said that, consider open/close inside your loop instead).
lock_file = open(LOCK_FILENAME, "w+")
now = datetime.now()
NOW_STRING1 = str(now.strftime("%Y-%m-%d_%a_%H:%M"))
lock_file.write(NOW_STRING1)
# your loop and so on ...
lock_file.close()