def process_message(redis_conn, exit_event): User = get_user_model() while not exit_event.is_set(): record = redis_conn.lpop(IMBOT_QUEUE) if record: jid, message = json.loads(record) try: user = User.objects.get(jid=jid) except User.DoesNotExist: IMBot.send_message(jid, _('user with this jid not found')) continue timezone.activate(user.timezone) found = False for regex, func in IMBot._commands: params = regex.search(message) if params: found = True result = func(user, message, **params.groupdict()) if result: IMBot.send_message(jid, result) break if not found: IMBot.send_message(jid, _(u'command not found'))
def event_edit(request, id): """Edit form for a particular event.""" event = get_object_or_404(Event, id=id) if (not request.user.has_perm('main.change_event_others') and request.user != event.creator): return redirect('manage:events') if request.user.has_perm('main.change_event_others'): form_class = forms.EventEditForm elif request.user.has_perm('main.add_event_scheduled'): form_class = forms.EventExperiencedRequestForm else: form_class = forms.EventRequestForm if request.method == 'POST': form = form_class(request.POST, request.FILES, instance=event) if form.is_valid(): event = form.save(commit=False) _event_process(request, form, event) event.save() form.save_m2m() messages.info(request, 'Event "%s" saved.' % event.title) return redirect('manage:events') else: timezone.activate(pytz.timezone('UTC')) form = form_class(instance=event, initial={ 'timezone': timezone.get_current_timezone() # UTC }) return render(request, 'manage/event_edit.html', {'form': form, 'event': event})
def process_request(self, request): # Todo: remove when IE9 support will expire. request.ie_ajax_iframe = request.method == 'POST' and \ 'HTTP_X_REQUESTED_WITH' not in request.META and \ 'HTTP_X_REQUESTED_WITH' in request.POST if request.ie_ajax_iframe: # Fix IE9 not being able to post $.ajaxForm() with proper HTTP headers due to iframe emulation. request.META['HTTP_X_REQUESTED_WITH'] = request.POST['HTTP_X_REQUESTED_WITH'] # Get local timezone from browser and activate it. if getattr(settings, 'USE_JS_TIMEZONE', False): tz_name = self.__class__.get_request_timezone(request) if tz_name is not None: timezone.activate(pytz.timezone(tz_name)) self.__class__._threadmap[threading.get_ident()] = request # Optional server-side injected JSON. request.client_data = {} """ request.client_routes = [ 'logout', 'users_list', ] """ request.client_routes = [] vm_list = to_vm_list(request.client_data) if has_vm_list(request.session): vm_session = to_vm_list(request.session) vm_list.extend(vm_session)
def getDataLastHrs(req, hours): response = {} tz = req.GET.get('timezone', None) if tz is not None: timezone.activate(tz) else: timezone.activate(thermoctrl.settings.TIME_ZONE) # Calculate the range for today end = timezone.now() start = end - timedelta(hours=int(hours)) entries = Temp.objects.filter(time__range=[start, end]) response['status'] = 'success' response['numEntries'] = len(entries) response['entries'] = [] for e in entries: # Localize the time into the end user's timezone. zone = timezone.get_current_timezone() localTime = e.time.astimezone(zone) response['entries'].append({ "time_h": localTime.hour, "time_m": localTime.minute, "temp": e.temp }) timezone.deactivate() return render_json(response)
def test_override_decorator(self): default = timezone.get_default_timezone() @timezone.override(EAT) def func_tz_eat(): self.assertIs(EAT, timezone.get_current_timezone()) @timezone.override(None) def func_tz_none(): self.assertIs(default, timezone.get_current_timezone()) try: timezone.activate(ICT) func_tz_eat() self.assertIs(ICT, timezone.get_current_timezone()) func_tz_none() self.assertIs(ICT, timezone.get_current_timezone()) timezone.deactivate() func_tz_eat() self.assertIs(default, timezone.get_current_timezone()) func_tz_none() self.assertIs(default, timezone.get_current_timezone()) finally: timezone.deactivate()
def event_edit(request, slug): event = get_object_or_404( Event.objects, slug__exact=slug, user=request.user) if not event.is_visible_by(request.user): raise Http404 if request.method == 'POST': form = EventForm(request.POST, instance=event) formset = EventURLFormSet(request.POST, instance=event) if form.is_valid() and formset.is_valid(): instance = form.save() formset.save() messages.success( request, 'The event "%s" has been updated.' % instance.name) return redirect(instance.get_absolute_url()) else: # Activate the current event timezone: timezone.activate(pytz.timezone(event.timezone)) form = EventForm(instance=event) formset = EventURLFormSet(instance=event) context = { 'object': event, 'form': form, 'formset': formset, } return TemplateResponse(request, 'events/object_edit.html', context)
def set_timezone(new_tz): if settings.USE_TZ: try: import pytz timezone.activate(pytz.timezone(new_tz)) except ImportError: pass
def generate_event_pdf_multi(request, ids=None): # this shoud fix UTC showing up in PDFs timezone.activate(timezone.get_current_timezone()) if not ids: return HttpResponse("Should probably give some ids to return pdfs for..") # Prepare IDs idlist = ids.split(",") # Prepare context data = {} events = Event.objects.filter(pk__in=idlist) data["events"] = events # Render html content through html template with context template = get_template("pdf_templates/events.html") html = template.render(data) if "raw" in request.GET and bool(request.GET["raw"]): return HttpResponse(html) # Write PDF to file pdf_file = BytesIO() pisa.CreatePDF(html, dest=pdf_file, link_callback=link_callback) # Return PDF document through a Django HTTP response resp = HttpResponse(pdf_file.getvalue(), content_type="application/pdf") resp["Content-Disposition"] = 'inline; filename="events.pdf"' return resp
def process_request(self, request): user = request.user org = None if not user.is_anonymous(): org_id = request.session.get('org_id', None) if org_id: org = Org.objects.filter(is_active=True, pk=org_id).first() # only set the org if they are still a user or an admin if org and (user.is_superuser or user.is_staff or user in org.get_org_users()): user.set_org(org) # otherwise, show them what orgs are available else: user_orgs = user.org_admins.all() | user.org_editors.all() | user.org_viewers.all() | user.org_surveyors.all() user_orgs = user_orgs.distinct('pk') if user_orgs.count() == 1: user.set_org(user_orgs[0]) org = request.user.get_org() if org: timezone.activate(org.timezone) else: timezone.activate(settings.USER_TIME_ZONE) return None
def site(request, country, state, name): sites = Site.objects.filter(name=name).\ filter(state=state).\ filter(country=country) if len(sites) == 0: raise Http404 assert(len(sites) == 1) site = sites[0] env = {'site' : site} djtz.activate(site.timezone) main.addLevels(request, env) try: mgr = main.ForecastMgr(site, env['level']) days = mgr.getDays() env['highlightedDay'] = mgr.computeHighlightDay(days) env['days'] = days env['fetchTime'] = mgr.fetchTime env['maxWind'] = predictor.windMaxMap[env['level']] env['maxGust'] = predictor.gustMaxMap[env['level']] except weather.NoWeatherDataException: pass return render_to_response('siteviewer/siteview.html', env, context_instance=RequestContext(request))
def process_request(self, request): tzname = None if request.user.is_authenticated(): user_profile = request.user.profile tzname = user_profile.time_zone if tzname: timezone.activate(pytz.timezone(tzname))
def process_request(self, request): language = get_language_from_request(request) if hasattr(request, 'event') and not request.path.startswith(get_script_prefix() + 'control'): if language not in request.event.settings.locales: firstpart = language.split('-')[0] if firstpart in request.event.settings.locales: language = firstpart else: language = request.event.settings.locale for lang in request.event.settings.locales: if lang == firstpart or lang.startswith(firstpart + '-'): language = lang break translation.activate(language) request.LANGUAGE_CODE = translation.get_language() tzname = None if request.user.is_authenticated(): tzname = request.user.timezone if hasattr(request, 'event'): tzname = request.event.settings.timezone if tzname: try: timezone.activate(pytz.timezone(tzname)) request.timezone = tzname except pytz.UnknownTimeZoneError: pass else: timezone.deactivate()
def _check_has_timed_timeout(self, request): """Check for session timeout and return timestamp.""" has_timed_out = False # Activate timezone handling tz = request.session.get('django_timezone') if tz: timezone.activate(tz) try: timeout = settings.SESSION_TIMEOUT except AttributeError: timeout = 1800 last_activity = request.session.get('last_activity', None) timestamp = int(time.time()) if ( hasattr(request, "user") and hasattr(request.user, "token") and not auth_utils.is_token_valid(request.user.token) ): # The user was logged in, but his keystone token expired. has_timed_out = True if isinstance(last_activity, int): if (timestamp - last_activity) > timeout: has_timed_out = True if has_timed_out: request.session.pop('last_activity') return (has_timed_out, timestamp)
def _wrapper(): # need to activate the store's timezone for template rendering! timezone.activate(pytz.timezone(store.store_timezone)) with open(FS_SITE_DIR +\ "/templates/manage/notification-receipt-monthly-failed.html", 'r') as f: template = Template(f.read()) # variable names are misleading here >< date_now = subscription.date_last_billed +\ relativedelta(days=30) ######### # the 14 day sequence just like passed user limit date_disable = date_now + relativedelta(days=14) subject = "Repunch Inc. important service notice." ctx = get_notification_ctx() ctx.update({'store': store, "date_disable":date_disable, "date_now":date_now, "account_disabled": account_disabled, "sub_type":sub_type, "subscription":subscription}) body = template.render(Context(ctx)).__str__() email = mail.EmailMultiAlternatives(subject, strip_tags(body), EMAIL_FROM, [account.get('email')]) email.attach_alternative(body, 'text/html') _send_emails([email], connection)
def process_request(self, request): """Adds data necessary for Horizon to function to the request.""" # Activate timezone handling tz = request.session.get('django_timezone') if tz: timezone.activate(tz) # Check for session timeout try: timeout = settings.SESSION_TIMEOUT except AttributeError: timeout = 1800 last_activity = request.session.get('last_activity', None) timestamp = datetime.datetime.now() request.horizon = {'dashboard': None, 'panel': None, 'async_messages': []} if last_activity and (timestamp - last_activity).seconds > timeout: request.session.pop('last_activity') response = HttpResponseRedirect( '%s?next=%s' % (settings.LOGOUT_URL, request.path)) self.logout_reason = _("Session timed out.") utils.add_logout_reason(request, response, self.logout_reason) return response request.session['last_activity'] = timestamp
def process_request(self, request): if request.user.is_authenticated(): try: user = request.user.get_profile() timezone.activate(pytz.timezone(user.timezone)) except Profile.DoesNotExist: pass
def process_request(self, request: HttpRequest): language = get_language_from_request(request) # Normally, this middleware runs *before* the event is set. However, on event frontend pages it # might be run a second time by pretix.presale.EventMiddleware and in this case the event is already # set and can be taken into account for the decision. if hasattr(request, 'event') and not request.path.startswith(get_script_prefix() + 'control'): if language not in request.event.settings.locales: firstpart = language.split('-')[0] if firstpart in request.event.settings.locales: language = firstpart else: language = request.event.settings.locale for lang in request.event.settings.locales: if lang.startswith(firstpart + '-'): language = lang break translation.activate(language) request.LANGUAGE_CODE = translation.get_language() tzname = None if hasattr(request, 'event'): tzname = request.event.settings.timezone elif request.user.is_authenticated: tzname = request.user.timezone if tzname: try: timezone.activate(pytz.timezone(tzname)) request.timezone = tzname except pytz.UnknownTimeZoneError: pass else: timezone.deactivate()
def process_request(self, request): if request.path.startswith("/static") or request.path.startswith("/media"): return user = request.user user_timezone = None if TIMEZONE_FIELD: user_timezone = getattr(user, TIMEZONE_FIELD, None) if not user_timezone: timezone_name = request.session.get('django_timezone',None) if timezone_name: user_timezone = pytz.timezone(timezone_name) if not user_timezone and gi4: timezone_name = gi4.time_zone_by_addr(request.META['REMOTE_ADDR']) if timezone_name: user_timezone = pytz.timezone(timezone_name) request.session['django_timezone'] = timezone_name # Save us a little time next request if user_timezone and user.is_authenticated(): setattr(user,TIMEZONE_FIELD,user_timezone) user.save() if not user_timezone: user_timezone = pytz.timezone(getattr(settings,'TIME_ZONE','America/Chicago')) try: timezone.activate(user_timezone) except Exception, e: extra = {'_user': request.user, '_timezone': user_timezone} logger.error('Invalid timezone selected: %s' % (str(e)), extra=extra)
def process_request(self, request): user = request.user user_tz = 'Asia/Kolkata' if hasattr(user, 'profile'): if user.profile.timezone: user_tz = user.profile.timezone timezone.activate(pytz.timezone(user_tz))
def process_request(self, request): timezone.deactivate() if request.user and request.user.is_authenticated(): tzname = request.user.time_zone if tzname: timezone.activate(pytz.timezone(tzname)) return None
def process_request(self, request): """ Adds data necessary for Horizon to function to the request. Adds the current "active" :class:`~horizon.Dashboard` and :class:`~horizon.Panel` to ``request.horizon``. Adds a :class:`~horizon.users.User` object to ``request.user``. """ # Activate timezone handling tz = request.session.get('django_timezone') if tz: timezone.activate(tz) # A quick and dirty way to log users out def user_logout(request): if hasattr(request, '_cached_user'): del request._cached_user # Use flush instead of clear, so we rotate session keys in # addition to clearing all the session data request.session.flush() request.__class__.user_logout = user_logout request.__class__.user = users.LazyUser() request.horizon = {'dashboard': None, 'panel': None, 'async_messages': []}
def get_context_data(self, **kwargs): context = super(PhotoshootContractMixin, self).get_context_data(**kwargs) parent = Contract.objects.get(slug=self.kwargs['contract_slug']) context['contract'] = parent #Set current time zone to that of the client timezone.activate(parent.client.country.timezone) return context
def process_request(self, request): epoch = None request.need_setup = False request.need_upgrade = False request.kbsite = None # Select only the `epoch` column, as pending database migrations could # make a full select crash. rows = models.KegbotSite.objects.filter(name='default').values('epoch') if not rows: request.need_setup = True elif rows[0].get('epoch', 0) < EPOCH: request.need_upgrade = True else: request.kbsite = models.KegbotSite.objects.get(name='default') if request.kbsite.is_setup: timezone.activate(request.kbsite.timezone) request.plugins = dict((p.get_short_name(), p) for p in plugin_util.get_plugins()) else: request.need_setup = True request.kbcache = KegbotCache() request.backend = get_kegbot_backend() return None
def home_view(request, survey_type='TEAMTEMP'): timezone.activate(timezone.utc) if request.method == 'POST': form = CreateSurveyForm(request.POST, error_class=ErrorBox) if form.is_valid(): csf = form.cleaned_data form_id = utils.random_string(8) user, created = get_or_create_user(request) dept_names = csf['dept_names'] region_names = csf['region_names'] site_names = csf['site_names'] survey = TeamTemperature(password=make_password(csf['password']), creator=user, survey_type=survey_type, archive_date=timezone.now(), id=form_id, dept_names=dept_names, region_names=region_names, site_names=site_names, archive_schedule=7, default_tz='UTC' ) survey.save() responses.add_admin_for_survey(request, survey.id) return HttpResponseRedirect('/team/%s' % form_id) else: form = CreateSurveyForm() return render(request, 'index.html', {'form': form, 'survey_type': survey_type})
def process_request(self, request): if request.user.is_authenticated(): tz = request.user.profile.timezone if tz: timezone.activate(tz) else: timezone.deactivate()
def loginAction(request): if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): n = form.cleaned_data["username"] p = form.cleaned_data["password"] user = authenticate(username=n, password=p, request=request) if user is not None: login(request, user) try: user = User.objects.get(login=n) tz = user.timezone if user.timezone else "UTC" timezone.activate(tz) request.session["django_timezone"] = tz messages.info(request, _("Authentication successfull")) return HttpResponseRedirect("/frontend/controllers") except Exception as e: messages.error( request, _("Something wrent wrong - internal error, please contact the Technical Support") ) messages.error(request, e) else: messages.error(request, _("Authentication failed - either your Login or your Password is incorrect")) else: messages.error(request, _("Invalid Form Values")) else: form = LoginForm() return render(request, "auth/login.html", {"form": form})
def calc_multi_iteration_average(team_name, survey, num_iterations=2, tz='UTC'): timezone.activate(pytz.timezone(tz)) iteration_index = 0 if num_iterations > 0: iteration_index = num_iterations - 1 else: return None archive_dates = survey.temperature_responses.filter(archive_date__isnull=False).values( 'archive_date').distinct().order_by('-archive_date') if num_iterations > archive_dates.count() > 0: iteration_index = archive_dates.count() - 1 # oldest archive date if less than target iteration count if archive_dates.count() > iteration_index: response_dates = survey.temperature_responses.filter( archive_date=archive_dates[iteration_index]['archive_date']).values('response_date').order_by( 'response_date') if team_name != '': accumulated_stats, _ = survey.accumulated_team_stats(team_name, timezone.now(), response_dates[0]['response_date']) else: accumulated_stats, _ = survey.accumulated_stats(timezone.now(), response_dates[0]['response_date']) return accumulated_stats return None
def process_request(self, request): user = request.user user_language = user.language # or settings.SITE.get_default_language() if settings.USE_TZ: if user.time_zone: activate(user.time_zone.tzinfo) else: activate(settings.SITE.models.about.TimeZones.default.tzinfo) rqdata = request2data(request, user_language) if rqdata is None: return su = rqdata.get(constants.URL_PARAM_SUBST_USER, None) if su is not None: if su: try: su = settings.SITE.user_model.objects.get(id=int(su)) # ~ logger.info("20120714 su is %s",su.username) except settings.SITE.user_model.DoesNotExist: su = None else: su = None # e.g. when it was an empty string "su=" request.subst_user = su
def datetime_server(value=None): """ Переводит значение в зону серверного времени. На вход можно подавать как naive, так и aware, результатом будет аналогичное. Если генерируется новое время, то результатом будет naive при settings.USE_TZ = False, иначе - aware. """ if not value: value = timezone.now() if timezone.is_naive(value): return value tz_curr = timezone.get_current_timezone() tz_serv = timezone.get_default_timezone() if tz_curr != tz_serv: timezone.activate(tz_serv) value = timezone.localtime(value, tz_serv) timezone.activate(tz_curr) else: value = timezone.localtime(value, tz_curr) return value
def process_request(self, request): assert hasattr(request, 'user'), _('Add "django.contrib.auth.middleware.AuthenticationMiddleware" to MIDDLEWARE_CLASSES before UserLanguageMiddleware') timezone.activate(settings.TIME_ZONE) if request.user.is_authenticated(): timezone.activate(get_user_time_zone(request.user))
def process_request(self, request): if request.user.is_authenticated: try: timezone.activate(pytz.timezone(request.user.profile.timezone or 'US/Eastern')) except pytz.UnknownTimeZoneError: timezone.deactivate()
def run(scheduled_process): retention_settings = RetentionSettings.get_solo() if retention_settings.data_retention_in_hours == RetentionSettings.RETENTION_NONE: return scheduled_process.disable( ) # Changing the retention settings in the admin will re-activate it again. # These models should be rotated with retention. Dict value is the datetime field used. ITEM_COUNT_PER_HOUR = 2 MODELS_TO_CLEANUP = { DsmrReading.objects.processed(): 'timestamp', ElectricityConsumption.objects.all(): 'read_at', GasConsumption.objects.all(): 'read_at', } retention_date = timezone.now() - timezone.timedelta( hours=retention_settings.data_retention_in_hours) data_to_clean_up = False # We need to force UTC here, to avoid AmbiguousTimeError's on DST changes. timezone.activate(pytz.UTC) for base_queryset, datetime_field in MODELS_TO_CLEANUP.items(): hours_to_cleanup = base_queryset.filter(**{ '{}__lt'.format(datetime_field): retention_date }).annotate( item_hour=TruncHour(datetime_field)).values('item_hour').annotate( item_count=Count('id')).order_by().filter( item_count__gt=ITEM_COUNT_PER_HOUR ).order_by('item_hour').values_list( 'item_hour', flat=True )[:settings.DSMRREADER_RETENTION_MAX_CLEANUP_HOURS_PER_RUN] hours_to_cleanup = list(hours_to_cleanup) # Force evaluation. if not hours_to_cleanup: continue data_to_clean_up = True for current_hour in hours_to_cleanup: # Fetch all data per hour. data_set = base_queryset.filter( **{ '{}__gte'.format(datetime_field): current_hour, '{}__lt'.format(datetime_field): current_hour + timezone.timedelta(hours=1), }) # Extract the first/last item, so we can exclude it. # NOTE: Want to alter this? Please update ITEM_COUNT_PER_HOUR above as well! keeper_pks = [ data_set.order_by(datetime_field)[0].pk, data_set.order_by('-{}'.format(datetime_field))[0].pk ] # Now drop all others. logger.debug('Retention: Cleaning up: %s (%s)', current_hour, data_set[0].__class__.__name__) data_set.exclude(pk__in=keeper_pks).delete() timezone.deactivate() # Delay for a bit, as there is nothing to do. if not data_to_clean_up: scheduled_process.delay(timezone.timedelta(hours=12))
# Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True TZ = pytz.timezone(TIME_ZONE) timezone.activate(TZ) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/assets/' STATICFILES_DIRS = (os.path.join(BASE_DIR, STATIC_URL), ) # # Exit status # EXIT_SUCCESS = 0 EXIT_FAILURE = 1 #
def activate_timezone(self): timezone.activate(self.timezone)
def guardarInformacion(request): #trabajo #informacion respon = json.loads(request.body.decode("utf8")) archivo_id = respon['archivo_id'] timezone.activate(pytz.timezone("America/Bogota")) hoy = str(timezone.localtime(timezone.now())) hoy = hoy[:19] hoy = datetime.strptime(hoy, "%Y-%m-%d %H:%M:%S") archivo = Archivo.objects.filter(id=archivo_id) if archivo.exists(): archivo = Archivo.objects.get(id=archivo_id) documento = openpyxl.load_workbook(BASE7 + archivo.nombre_archivo) hojas = documento.sheetnames hoja = documento[hojas[0]] registros = hoja.rows contador = 0 trabajos_id = [] for fila in registros: contador = contador + 1 if contador > 1: variables = {} for columna in fila: indice = re.sub("\d", "", columna.coordinate) variables[indice] = columna.value informacion = informacion() informacion.archivo_id = informacion_id informacion.fecha_inicio = hoy informacion.codigoEstacion = json.dumps(variables) informacion.nombreEstacion = json.dumps(variables) informacion.latitud = json.dumps(variables) informacion.longitud = json.dumps(variables) informacion.altitud = json.dumps(variables) informacion.categoria = json.dumps(variables) informacion.entidad = json.dumps(variables) informacion.areaOperativa = json.dumps(variables) informacion.departamento = json.dumps(variables) informacion.municipio = json.dumps(variables) informacion.fechaInstalacion = json.dumps(variables) informacion.fechaSuspension = json.dumps(variables) informacion.idParametro = json.dumps(variables) informacion.etiqueta = json.dumps(variables) informacion.descripcionSerie = json.dumps(variables) informacion.frecuencia = json.dumps(variables) informacion.fecha = json.dumps(variables) informacion.valor = json.dumps(variables) informacion.grado = json.dumps(variables) informacion.calificador = json.dumps(variables) informacion.nivelAprovacion = json.dumps(variables) informacion.save() informacion_id.append(informacion.id) archivo.save() respuesta = {} respuesta['informacion_id'] = informacion_id return HttpResponse(json.dumps(respuesta), content_type="application/json")
def process_request(self, request): tzname = request.session.get('django_timezone') if tzname: timezone.activate(pytz.timezone(tzname)) else: timezone.deactivate()
def process_request(self, request): timezone.activate(timezone.utc)
def process_request(self, request): if request.path_info.startswith("/admin"): activate("America/Vancouver")
def setUp(self): """ Make sure all our tests are timezone-agnostic. Some of them parse ISO datetimes and those would be broken if we did not enforce timezone normalization. """ timezone.activate(pytz.utc)
def test_hour_conditions(rf, get_condition, params_for_matches): timezone.activate(pytz.UTC) w_today = timezone.now().date().weekday() w_tomorrow = (timezone.now() + datetime.timedelta(days=1)).date().weekday() w_future = (timezone.now() + datetime.timedelta(days=2)).date().weekday() matching_days = ",".join(map(str, [w_today])) non_matching_days = ",".join(map(str, [w_tomorrow, w_future])) # Matching time range hour_start = (timezone.now() - datetime.timedelta(hours=2)).time() # 8:00 AM hour_end = (timezone.now() + datetime.timedelta(hours=2)).time() # 12:00 PM hour_condition = get_condition(hour_start, hour_end, matching_days) assert hour_condition.matches(*params_for_matches) hour_condition.days = non_matching_days hour_condition.save() assert not hour_condition.matches(*params_for_matches) # Hour end shouldn't cause a match. Should be obvious that if the # merchant set start time 8:00 AM and end time 10:00 AM th campaign is no more # at 10:10 AM hour_condition.hour_start = (timezone.now() - datetime.timedelta(hours=2)).time() # 8:00 AM hour_condition.hour_end = timezone.now().time() # 10:00 PM hour_condition.save() assert not hour_condition.matches(*params_for_matches) # time in future shouldn't match hour_condition.hour_start = ( timezone.now() + datetime.timedelta(hours=2)).time() # 12:00 PM hour_condition.hour_end = (timezone.now() + datetime.timedelta(hours=4)).time() # 14:00 PM hour_condition.days = matching_days hour_condition.save() assert not hour_condition.matches(*params_for_matches) hour_condition.days = non_matching_days hour_condition.save() assert not hour_condition.matches(*params_for_matches) # time in past shouldn't match hour_condition.hour_start = (timezone.now() - datetime.timedelta(hours=3)).time() # 7:00 AM hour_condition.hour_end = (timezone.now() - datetime.timedelta(hours=2)).time() # 8:00 AM hour_condition.days = matching_days hour_condition.save() assert not hour_condition.matches(*params_for_matches) hour_condition.days = non_matching_days hour_condition.save() assert not hour_condition.matches(*params_for_matches) # Special times (should match) hour_condition.hour_start = timezone.now().time() # 10:00 AM hour_condition.hour_end = (timezone.now() + datetime.timedelta(hours=14)).time() # 0:00 AM hour_condition.days = matching_days hour_condition.save() assert hour_condition.matches(*params_for_matches) hour_condition.days = non_matching_days hour_condition.save() assert not hour_condition.matches(*params_for_matches) # Special times (should not match) hour_condition.hour_start = ( timezone.now() + datetime.timedelta(hours=2)).time() # 12:00 AM hour_condition.hour_end = (timezone.now() + datetime.timedelta(hours=14)).time() # 0:00 AM hour_condition.days = matching_days hour_condition.save() assert not hour_condition.matches(*params_for_matches) hour_condition.days = non_matching_days hour_condition.save() assert not hour_condition.matches(*params_for_matches) # Lastly few timezone tests (LA it is monday and time is 2:00 AM.) with override_settings(TIME_ZONE="America/Los_Angeles"): timezone.activate(pytz.timezone("America/Los_Angeles")) # So the 10:00 AM shouldn't match at all hour_condition.hour_start = ( timezone.now() - datetime.timedelta(hours=1)).time() # 9:00 AM hour_condition.hour_end = ( timezone.now() + datetime.timedelta(hours=1)).time() # 11:00 AM hour_condition.days = matching_days hour_condition.save() assert not hour_condition.matches(*params_for_matches) # Instead around 2:00 AM we will find a match hour_condition.hour_start = ( timezone.now() - datetime.timedelta(hours=9)).time() # 1:00 AM hour_condition.hour_end = ( timezone.now() - datetime.timedelta(hours=7)).time() # 3:00 AM hour_condition.days = matching_days hour_condition.save() assert hour_condition.matches(*params_for_matches) # Make sure that the hour end doesn't cause match hour_condition.hour_start = ( timezone.now() - datetime.timedelta(hours=9)).time() # 1:00 AM hour_condition.hour_end = ( timezone.now() - datetime.timedelta(hours=8)).time() # 2:00 AM hour_condition.days = matching_days hour_condition.save() assert not hour_condition.matches(*params_for_matches)
('ru', _('Russian')), ('en', _('English')), ) DEFAULT_LANGUAGE = 0 LANGUAGE_CODE = 'ru' TIME_ZONE = 'Europe/Moscow' USE_I18N = True USE_L10N = True USE_TZ = True timezone.activate(pytz.timezone('Europe/Moscow')) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"), ) MEDIA_ROOT = '/app-data/media' MEDIA_URL = '/media/' REST_FRAMEWORK = { # 'DATETIME_FORMAT': "%Y-%m-%dT%H:%M:%S.%fZ", 'DATETIME_FORMAT': "%Y-%m-%d %H:%M:%S", } CELERY_BROKER_URL = 'redis://redis:6379/0'
# https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # NOTE - This displays everything as PST. Everything in the backend is # still stored as UTC ZONE = "US/Pacific" timezone.activate(pytz.timezone(ZONE)) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = '/code/server/static' REACT_APP_DIR = os.path.join('client') if not DEBUG: STATICFILES_DIRS = [ os.path.join(REACT_APP_DIR, 'build', 'static'), os.path.join(REACT_APP_DIR, 'build'), os.path.join('static') ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
def __call__(self, request): # Maybe sometime later we'll let users set a timezone in their profile, for now it's always UK time tzname = "Europe/London" timezone.activate(tzname) return self.get_response(request)
def process_request(self, request): translation.get_language() if translation.get_language() == 'de': timezone.activate(pytz.timezone('Europe/Vienna'))
def process_request(self, request): zone = self.get_timezone_from_request(request) if zone: timezone.activate(zone)
def process_request(self, request): tzname = request.META.get('TZ') if tzname: timezone.activate(pytz.timezone(tzname)) else: timezone.deactivate()
def setUp(self): usd = Currency.objects.create() timezone.activate(pytz.timezone("America/New_York")) # Users user1 = User.objects.create(username="******", email="*****@*****.**", first_name="Brian", last_name="Katchmar", is_staff=True, is_active=True, is_superuser=True) user1.set_password("password1") user1.save() user2 = User.objects.create(username="******", email="*****@*****.**", first_name="Josh", last_name="Blank", is_staff=False, is_active=True, is_superuser=False) user2.set_password("password2") user2.save() user3 = User.objects.create(username="******", email="*****@*****.**", first_name="Matthew", last_name="Stewart", is_staff=False, is_active=True, is_superuser=False) user3.set_password("password3") user3.save() user4 = User.objects.create(username="******", email="*****@*****.**", first_name="Erin", last_name="Pienta", is_staff=False, is_active=True, is_superuser=False) user4.set_password("password4") user4.save() user5 = User.objects.create(username="******", email="*****@*****.**", first_name="Kenny", last_name="Kim", is_staff=False, is_active=True, is_superuser=False) user5.set_password("password5") user5.save() user6 = User.objects.create(username="******", email="*****@*****.**", first_name="Clara", last_name="Chang", is_staff=False, is_active=True, is_superuser=False) user6.set_password("password6") user6.save() # Contracts contract1 = Contract.objects.create(Creator=user2, Name="Josh Contract", StartDate=date(2017, 10, 5), EndDate=date(2017, 10, 15)) contract1.create_slug() contract1.save() contract2 = Contract.objects.create(Creator=user4, Name="Erin Contract", StartDate=date(2017, 10, 16), EndDate=date(2017, 10, 25)) contract2.create_slug() contract2.save() # Contract Recipients Recipient.objects.create(ContractForRecipient=contract1, Name="Brian Katchmar", BillingName="John Smith") Recipient.objects.create(ContractForRecipient=contract2, Name="Brian Katchmar", BillingName="John Smith") # Contract Payment Plan PaymentPlan.objects.create(ContractForPaymentPlan=contract1, ContractCurrency=usd) PaymentPlan.objects.create(ContractForPaymentPlan=contract2, ContractCurrency=usd) # Contract Relationship Relationship.objects.create(ContractUser=user2, ContractForRelationship=contract1, RelationshipType='f') Relationship.objects.create(ContractUser=user3, ContractForRelationship=contract1, RelationshipType='c') Relationship.objects.create(ContractUser=user4, ContractForRelationship=contract2, RelationshipType='f') Relationship.objects.create(ContractUser=user6, ContractForRelationship=contract2, RelationshipType='f') Relationship.objects.create(ContractUser=user5, ContractForRelationship=contract2, RelationshipType='c')
def _set_timezone(self, request): if request.person.timezone: timezone.activate(request.person.timezone)
def node_vis_id_info(request, node_vis_id, hwidth=HWIDTH_DEFAULT, hheight=HHEIGHT_DEFAULT, offx=0, offy=0): hwidth = int(hwidth) hheight = int(hheight) offx = int(offx) offy = int(offy) timezone.activate(get_tzone(request.user)) timezone_now = timezone.now() node = NichoNode.objects.get(node_vis_id=node_vis_id) node_oldinfo = node.generate_obsolete(timezone_now) node_pos_x = node.pos_x_on_map node_pos_y = node.pos_y_on_map if request.method == "POST": if request.POST.get("del_node", "") == "on": return HttpResponseRedirect( reverse("appNichoAnu:del_node", kwargs={"node_vis_id": node_vis_id})) iform_h = dict([(ikey, request.POST[ikey]) for ikey in request.POST]) iform_h["node_vis_id"] = node.node_vis_id iform_h["reliability"] = node.reliability node_form = NichoNode_Form(iform_h, instance=node) # node object is already affected at above line. # The object is returned with nodeform.save(commit = False) from pprint import pprint pprint(iform_h) print(".....") if node_form.is_valid() and len(node_form.changed_data): node_newinfo = node_form.save(commit=False) node_newinfo.user = request.user node_newinfo.timestamp = timezone.now() # New time stamp! node_newinfo.save() node_oldinfo.save() to_networkx_from_rec(update=True) return HttpResponse("Modified!") else: from pprint import pprint pprint(node_form.errors) else: node_form = NichoNode_Form(instance=node) grf = to_networkx_from_rec() image_file = os.path.join(settings.UCSD_IAB_WORKDIR, "Media", "appNichoAnu", "Images", "nodes", "%s.png" % node_vis_id) mkdir_on_absent(rs_filepath_info(image_file)["foldername"]) # http://127.0.0.1:8000/UCSD_IMM_media/appNichoAnu/Images/tmp1.png image_url = '/'.join([ settings.MEDIA_URL.rstrip('/'), "appNichoAnu", "Images", "nodes", "%s.png" % node_vis_id ]) if True: # not os.path.isfile(image_file): drawgrf = DrawNetworkX_simple(grf) if hwidth == HWIDTH_DEFAULT and hheight == HHEIGHT_DEFAULT: fig_face_color = (0.8, 0.8, 0.7) else: fig_face_color = (0.8, 0.8, 0.8) nodes_drawn, edges_drawn = \ drawgrf.output_fig_around_region_simple( [node_pos_x - hwidth + offx, node_pos_x + hwidth + offx], [node_pos_y - hheight + offy, node_pos_y + hheight + offy], nodes_central = [ node_vis_id ], node_label_off_num_nodes = 1000, figsize = (6, 6), fig_face_color = fig_face_color, title = "Network around %s" % node_vis_id, outfile = image_file) # for nodenam in nodes_drawn: # print("Getting", nodenam) # print(NichoNode.objects.get(node_vis_id = nodenam)) nodes_drawn = [ NichoNode.objects.get(node_vis_id=nodenam) for nodenam in nodes_drawn ] print("Nodes drawn:", nodes_drawn) else: nodes_drawn = [] hwidth_zi = int(hwidth / 1.5) if hwidth_zi < 2: hwidth_zi = 2 hheight_zi = int(hheight / 1.5) if hheight_zi < 2: hheight_zi = 2 zoom_in_param = { "hwidth": hwidth_zi, "hheight": hheight_zi, "offx": offx, "offy": offy } zoom_out_param = { "hwidth": int(hwidth * 1.5), "hheight": int(hheight * 1.5), "offx": offx, "offy": offy } shift_left_param = { "hwidth": hwidth, "hheight": hheight, "offx": int(offx - hwidth * 0.5), "offy": offy } shift_right_param = { "hwidth": hwidth, "hheight": hheight, "offx": int(offx + hwidth * 0.5), "offy": offy } shift_down_param = { "hwidth": hwidth, "hheight": hheight, "offx": offx, "offy": int(offy - hheight * 0.5) } shift_up_param = { "hwidth": hwidth, "hheight": hheight, "offx": offx, "offy": int(offy + hheight * 0.5) } contxt = { "node": node, "node_form": node_form, "image_url": image_url, "nodes_drawn": nodes_drawn, "zoom_in_param": zoom_in_param, "zoom_out_param": zoom_out_param, "shift_left_param": shift_left_param, "shift_right_param": shift_right_param, "shift_up_param": shift_up_param, "shift_down_param": shift_down_param, } return render(request, "appNichoAnu/map_Anurag_node_info4.html", contxt)
def set_current_zone(zone): timezone.activate(zone)
def setUp(self): self.original_tz = timezone.get_current_timezone() self.tz = dt.timezone(dt.timedelta(days=-1, hours=1)) timezone.activate(self.tz)
from collections import OrderedDict, defaultdict from django.db.models import signals from django.core.cache import cache from django.utils import timezone from mainframe import settings from django.db import models import pytz #No models for this app, since its just for Accounts #to set a date for an event timezone.activate(pytz.timezone(settings.TIME_ZONE)) current_tz = timezone.get_current_timezone() def normalise(date): return current_tz.normalize(date)
class QuestAdmin(admin.ModelAdmin): timezone.activate(pytz.timezone("America/Chicago")) list_display = ("created_at", "topic", "status_label", "last_update")
def tearDown(self): timezone.activate(self.original_tz)
def _sendmail(user, subject_template_name, body_template_name, recipient_list=None, bcc_list=None, from_email=None, connection=None, attachments=None, fail_silently=False, headers=None, cc_list=None, extra_context=None, user_i18n=False, billing_email=False, dc=None): """ Like https://docs.djangoproject.com/en/dev/topics/email/#send-mail But we are using templates instead of subject/message text. """ user_i18n_active = False if not dc: if user: dc = user.current_dc else: dc = DefaultDc() dc_settings = dc.settings if not dc_settings.EMAIL_ENABLED: return None # Default from header if not from_email: from_email = dc_settings.DEFAULT_FROM_EMAIL # Default headers default_headers = {'X-Mailer': 'Danube Cloud', 'X-es-version': __version__, 'X-es-dc': dc.name} if headers: default_headers.update(headers) # We have to have a recipient_list if recipient_list is None and user is not None: if billing_email: recipient_list = [user.userprofile.billing_email] else: recipient_list = [user.email] # Set i18n stuff from user settings if user_i18n and hasattr(user, 'userprofile'): logger.debug('Switching email language to %s and timezone to %s', user.userprofile.language, user.userprofile.timezone) translation.activate(user.userprofile.language) timezone.activate(user.userprofile.timezone) user_i18n_active = True # Context for templates context = { 'LANGUAGES': django_settings.LANGUAGES, 'LANGUAGE_CODE': translation.get_language(), 'LANGUAGE_BIDI': translation.get_language_bidi(), 'user': user, 'recipient_list': recipient_list, 'site_link': dc_settings.SITE_LINK, 'site_name': dc_settings.SITE_NAME, 'site_signature': dc_settings.SITE_SIGNATURE, 'company_name': dc_settings.COMPANY_NAME, } # Add extra context if specified if extra_context is not None: context.update(extra_context) # Render email subject and body body = render_to_string(body_template_name, context) subject = render_to_string(subject_template_name, context) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) # Unset user i18n stuff if user_i18n_active: translation.deactivate() timezone.deactivate() return send_mail(subject, body, recipient_list, bcc_list=bcc_list, from_email=from_email, connection=connection, attachments=attachments, fail_silently=fail_silently, headers=default_headers, cc_list=cc_list)
def process_request(self, request): tz = request.session.get('django_timezone') if tz: timezone.activate(tz) elif request.user.is_authenticated(): timezone.activate(request.user.timezone)
def process_request(self, request): timezone.activate(pytz.timezone(TIME_ZONE))
class EventAdmin(admin.ModelAdmin): timezone.activate(pytz.timezone("America/Chicago")) list_display = ("quest", "event_type", "created_at") list_filter = ('event_type', )
def process_request(self, request): if request.user.is_authenticated(): timezone.activate(request.user.timezone) else: timezone.deactivate()
def process_request(self, request): tzname = gpm['Timezone__timezone'] if tzname: timezone.activate(pytz.timezone(tzname)) else: timezone.deactivate()