def get_stations(cls, query):
if query.isdigit():
query = 'name:{query} OR number:{query}'.format(query=query)
else:
# Querying number with a string value raises an error, we remove this field
query = 'name:{}'.format(query)
req = requests.get(settings.VELIB_API_BASE_URL,
params={'apikey': settings.VELIB_API_KEY,
'dataset': 'stations-velib-disponibilites-en-temps-reel',
'fields': 'number,name',
'q': query,
#'sort': 'name', Seems to create an error 2016-10-21
'timezone': timezone.get_current_timezone_name()})
if not req.ok:
return ()
data = req.json()
if not data.get('nhits', 0):
# No matching data found
return ()
return [(item['fields']['number'], item['fields']['name']) for item in data.get('records', [])]
python类get_current_timezone_name()的实例源码
def get_station_infos(cls, station_id):
req = requests.get(settings.VELIB_API_BASE_URL,
params={'apikey': settings.VELIB_API_KEY,
'dataset': 'stations-velib-disponibilites-en-temps-reel',
'fields': 'name,bike_stands,available_bikes,status',
'q': 'number:"{}"'.format(station_id),
'timezone': timezone.get_current_timezone_name()})
if not req.ok:
return None
data = req.json()
if not data.get('nhits', 0):
# No matching data found
return None
data = data['records'][0]['fields']
return {
'station': data['name'],
'slots': data['bike_stands'],
'bikes': data['available_bikes'],
'status': data['status'] == 'OPEN'
}
def get_stations(cls, query):
if query.isdigit():
query = 'nom:{query} OR idstation:{query}'.format(query=query)
else:
# Querying idstation with a string value raises an error, we remove this field
query = 'nom:{}'.format(query)
req = requests.get(settings.STAR_API_BASE_URL, params={'apikey': settings.STAR_API_KEY,
'dataset': 'vls-stations-etat-tr',
'fields': 'idstation,nom',
'q': query,
'sort': 'nom',
'timezone': timezone.get_current_timezone_name()})
if not req.ok:
return ()
data = req.json()
if not data.get('nhits', 0):
# No matching data found
return ()
return [(item['fields']['idstation'], item['fields']['nom']) for item in data.get('records', [])]
def get_station_infos(cls, station_id):
req = requests.get(settings.STAR_API_BASE_URL,
params={'apikey': settings.STAR_API_KEY,
'dataset': 'vls-stations-etat-tr',
'fields': 'nom,nombreemplacementsactuels,nombrevelosdisponibles,etat',
'q': 'idstation:"{}"'.format(station_id),
'timezone': timezone.get_current_timezone_name()})
if not req.ok:
return None
data = req.json()
if not data.get('nhits', 0):
# No matching data found
return None
data = data['records'][0]['fields']
return {
'station': data['nom'],
'slots': data['nombreemplacementsactuels'],
'bikes': data['nombrevelosdisponibles'],
'status': data['etat'] == 'En fonctionnement'
}
def setUp(self):
self._timezone_backup = timezone.get_current_timezone_name()
return super(MiddlewareTests, self).setUp()
def test_timezone_awareness(self):
url = settings.LOGIN_REDIRECT_URL
mw = middleware.HorizonMiddleware()
request = self.factory.get(url)
request.session['django_timezone'] = 'America/Chicago'
mw.process_request(request)
self.assertEqual(
timezone.get_current_timezone_name(), 'America/Chicago')
request.session['django_timezone'] = 'Europe/Paris'
mw.process_request(request)
self.assertEqual(timezone.get_current_timezone_name(), 'Europe/Paris')
request.session['django_timezone'] = 'UTC'
mw.process_request(request)
self.assertEqual(timezone.get_current_timezone_name(), 'UTC')
def as_sql(self, compiler, connection):
lhs, lhs_params = compiler.compile(self.lhs)
tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
sql, tz_params = connection.ops.datetime_cast_date_sql(lhs, tzname)
lhs_params.extend(tz_params)
return sql, lhs_params
def as_sql(self, compiler, connection):
sql, params = compiler.compile(self.lhs)
lhs_output_field = self.lhs.output_field
if isinstance(lhs_output_field, DateTimeField):
tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
sql, tz_params = connection.ops.datetime_extract_sql(self.lookup_name, sql, tzname)
params.extend(tz_params)
elif isinstance(lhs_output_field, DateField):
sql = connection.ops.date_extract_sql(self.lookup_name, sql)
elif isinstance(lhs_output_field, TimeField):
sql = connection.ops.time_extract_sql(self.lookup_name, sql)
else:
raise ValueError('DateTransform only valid on Date/Time/DateTimeFields')
return sql, params
def tz(request):
from django.utils import timezone
return {'TIME_ZONE': timezone.get_current_timezone_name()}
def _i18n_cache_key_suffix(request, cache_key):
"""If necessary, adds the current locale or time zone to the cache key."""
if settings.USE_I18N or settings.USE_L10N:
# first check if LocaleMiddleware or another middleware added
# LANGUAGE_CODE to request, then fall back to the active language
# which in turn can also fall back to settings.LANGUAGE_CODE
cache_key += '.%s' % getattr(request, 'LANGUAGE_CODE', get_language())
if settings.USE_TZ:
# The datetime module doesn't restrict the output of tzname().
# Windows is known to use non-standard, locale-dependent names.
# User-defined tzinfo classes may return absolutely anything.
# Hence this paranoid conversion to create a valid cache key.
tz_name = force_text(get_current_timezone_name(), errors='ignore')
cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')
return cache_key
def render(self, context):
context[self.variable] = timezone.get_current_timezone_name()
return ''
def save(self):
data = self.cleaned_data
if data.get('register_username') and data.get('register_email') and data.get('register_password'):
user = User.objects.create_user(nick=data.get('register_username'),
email=data.get('register_email'),
password=data.get('register_password'),
locale=translation.get_language(),
timezone=timezone.get_current_timezone_name())
data['user_id'] = user.pk
return data['user_id']
def test_submission_count_for_today_in_form_list(self):
self._publish_xls_form_to_project()
request = self.factory.get('/', **self.extra)
response = self.view(request)
self.assertEqual(response.status_code, 200)
self.assertIn('submission_count_for_today', response.data[0].keys())
self.assertEqual(response.data[0]['submission_count_for_today'], 0)
self.assertEqual(response.data[0]['num_of_submissions'], 0)
paths = [os.path.join(
self.main_directory, 'fixtures', 'transportation',
'instances_w_uuid', s, s + '.xml')
for s in ['transport_2011-07-25_19-05-36']]
# instantiate date that is NOT naive; timezone is enabled
current_timzone_name = timezone.get_current_timezone_name()
current_timezone = pytz.timezone(current_timzone_name)
today = datetime.today()
current_date = current_timezone.localize(
datetime(today.year,
today.month,
today.day))
self._make_submission(paths[0], forced_submission_time=current_date)
self.assertEqual(self.response.status_code, 201)
request = self.factory.get('/', **self.extra)
response = self.view(request)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data[0]['submission_count_for_today'], 1)
self.assertEqual(response.data[0]['num_of_submissions'], 1)
def submission_count_for_today(self):
current_timzone_name = timezone.get_current_timezone_name()
current_timezone = pytz.timezone(current_timzone_name)
today = datetime.today()
current_date = current_timezone.localize(
datetime(today.year,
today.month,
today.day))
count = self.instances.filter(
deleted_at__isnull=True,
date_created=current_date).count()
return count
def get_tzname(self):
# Timezone conversions must happen to the input datetime *before*
# applying a function. 2015-12-31 23:00:00 -02:00 is stored in the
# database as 2016-01-01 01:00:00 +00:00. Any results should be
# based on the input datetime not the stored datetime.
tzname = None
if settings.USE_TZ:
if self.tzinfo is None:
tzname = timezone.get_current_timezone_name()
else:
tzname = timezone._get_timezone_name(self.tzinfo)
return tzname
def as_sql(self, compiler, connection):
# Cast to date rather than truncate to date.
lhs, lhs_params = compiler.compile(self.lhs)
tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
sql, tz_params = connection.ops.datetime_cast_date_sql(lhs, tzname)
lhs_params.extend(tz_params)
return sql, lhs_params
def as_sql(self, compiler, connection):
# Cast to date rather than truncate to date.
lhs, lhs_params = compiler.compile(self.lhs)
tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
sql, tz_params = connection.ops.datetime_cast_time_sql(lhs, tzname)
lhs_params.extend(tz_params)
return sql, lhs_params
def tz(request):
from django.utils import timezone
return {'TIME_ZONE': timezone.get_current_timezone_name()}
def _i18n_cache_key_suffix(request, cache_key):
"""If necessary, adds the current locale or time zone to the cache key."""
if settings.USE_I18N or settings.USE_L10N:
# first check if LocaleMiddleware or another middleware added
# LANGUAGE_CODE to request, then fall back to the active language
# which in turn can also fall back to settings.LANGUAGE_CODE
cache_key += '.%s' % getattr(request, 'LANGUAGE_CODE', get_language())
if settings.USE_TZ:
# The datetime module doesn't restrict the output of tzname().
# Windows is known to use non-standard, locale-dependent names.
# User-defined tzinfo classes may return absolutely anything.
# Hence this paranoid conversion to create a valid cache key.
tz_name = force_text(get_current_timezone_name(), errors='ignore')
cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')
return cache_key
def _placeholder_cache_key(placeholder, lang):
cache_key = '%srender_placeholder:%s.%s' % (get_cms_setting("CACHE_PREFIX"), placeholder.pk, str(lang))
if settings.USE_TZ:
tz_name = force_text(get_current_timezone_name(), errors='ignore')
cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')
return cache_key
def _page_cache_key(request):
#md5 key of current path
cache_key = "%s:%d:%s" % (
get_cms_setting("CACHE_PREFIX"),
settings.SITE_ID,
hashlib.md5(iri_to_uri(request.get_full_path()).encode('utf-8')).hexdigest()
)
if settings.USE_TZ:
# The datetime module doesn't restrict the output of tzname().
# Windows is known to use non-standard, locale-dependant names.
# User-defined tzinfo classes may return absolutely anything.
# Hence this paranoid conversion to create a valid cache key.
tz_name = force_text(get_current_timezone_name(), errors='ignore')
cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')
return cache_key
def get_tzname(self):
# Timezone conversions must happen to the input datetime *before*
# applying a function. 2015-12-31 23:00:00 -02:00 is stored in the
# database as 2016-01-01 01:00:00 +00:00. Any results should be
# based on the input datetime not the stored datetime.
tzname = None
if settings.USE_TZ:
if self.tzinfo is None:
tzname = timezone.get_current_timezone_name()
else:
tzname = timezone._get_timezone_name(self.tzinfo)
return tzname
def as_sql(self, compiler, connection):
# Cast to date rather than truncate to date.
lhs, lhs_params = compiler.compile(self.lhs)
tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
sql, tz_params = connection.ops.datetime_cast_date_sql(lhs, tzname)
lhs_params.extend(tz_params)
return sql, lhs_params
def as_sql(self, compiler, connection):
# Cast to date rather than truncate to date.
lhs, lhs_params = compiler.compile(self.lhs)
tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
sql, tz_params = connection.ops.datetime_cast_time_sql(lhs, tzname)
lhs_params.extend(tz_params)
return sql, lhs_params
def tz(request):
from django.utils import timezone
return {'TIME_ZONE': timezone.get_current_timezone_name()}
def _i18n_cache_key_suffix(request, cache_key):
"""If necessary, adds the current locale or time zone to the cache key."""
if settings.USE_I18N or settings.USE_L10N:
# first check if LocaleMiddleware or another middleware added
# LANGUAGE_CODE to request, then fall back to the active language
# which in turn can also fall back to settings.LANGUAGE_CODE
cache_key += '.%s' % getattr(request, 'LANGUAGE_CODE', get_language())
if settings.USE_TZ:
# The datetime module doesn't restrict the output of tzname().
# Windows is known to use non-standard, locale-dependent names.
# User-defined tzinfo classes may return absolutely anything.
# Hence this paranoid conversion to create a valid cache key.
tz_name = force_text(get_current_timezone_name(), errors='ignore')
cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')
return cache_key
def as_sql(self, compiler, connection):
lhs, lhs_params = compiler.compile(self.lhs)
tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
sql, tz_params = connection.ops.datetime_cast_date_sql(lhs, tzname)
lhs_params.extend(tz_params)
return sql, lhs_params
def as_sql(self, compiler, connection):
sql, params = compiler.compile(self.lhs)
lhs_output_field = self.lhs.output_field
if isinstance(lhs_output_field, DateTimeField):
tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
sql, tz_params = connection.ops.datetime_extract_sql(self.lookup_name, sql, tzname)
params.extend(tz_params)
elif isinstance(lhs_output_field, DateField):
sql = connection.ops.date_extract_sql(self.lookup_name, sql)
elif isinstance(lhs_output_field, TimeField):
sql = connection.ops.time_extract_sql(self.lookup_name, sql)
else:
raise ValueError('DateTransform only valid on Date/Time/DateTimeFields')
return sql, params
def tz(request):
from django.utils import timezone
return {'TIME_ZONE': timezone.get_current_timezone_name()}
def _i18n_cache_key_suffix(request, cache_key):
"""If necessary, adds the current locale or time zone to the cache key."""
if settings.USE_I18N or settings.USE_L10N:
# first check if LocaleMiddleware or another middleware added
# LANGUAGE_CODE to request, then fall back to the active language
# which in turn can also fall back to settings.LANGUAGE_CODE
cache_key += '.%s' % getattr(request, 'LANGUAGE_CODE', get_language())
if settings.USE_TZ:
# The datetime module doesn't restrict the output of tzname().
# Windows is known to use non-standard, locale-dependent names.
# User-defined tzinfo classes may return absolutely anything.
# Hence this paranoid conversion to create a valid cache key.
tz_name = force_text(get_current_timezone_name(), errors='ignore')
cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')
return cache_key