本文整理汇总了Python中nnmware.core.utils.setting函数的典型用法代码示例。如果您正苦于以下问题:Python setting函数的具体用法?Python setting怎么用?Python setting使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了setting函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: backend_setting
def backend_setting(backend, name, default=None):
"""
Looks for setting value following these rules:
1. Search for <backend_name> prefixed setting
2. Search for setting given by name
3. Return default
"""
backend_name = backend.AUTH_BACKEND.name.upper().replace('-', '_')
return setting('%s_%s' % (backend_name, name)) or setting(name) or default
开发者ID:Carlos-Mosquera,项目名称:nnmware,代码行数:9,代码来源:utils.py
示例2: oauth_request
def oauth_request(self, token, url, extra_params=None):
extra_params = extra_params or {}
scope = GOOGLE_OAUTH_SCOPE + setting('GOOGLE_OAUTH_EXTRA_SCOPE', [])
extra_params.update({
'scope': ' '.join(scope),
})
if not self.registered():
xoauth_displayname = setting('GOOGLE_DISPLAY_NAME', 'Social Auth')
extra_params['xoauth_displayname'] = xoauth_displayname
return super(GoogleOAuth, self).oauth_request(token, url, extra_params)
开发者ID:MrTomato8,项目名称:nnmware,代码行数:10,代码来源:google.py
示例3: save_status_to_session
def save_status_to_session(request, auth, pipeline_index, *args, **kwargs):
"""Saves current social-auth status to session."""
next_entry = setting('SOCIAL_AUTH_PIPELINE_RESUME_ENTRY')
if next_entry and next_entry in PIPELINE:
idx = PIPELINE.index(next_entry)
else:
idx = pipeline_index + 1
data = auth.to_session_dict(idx, *args, **kwargs)
name = setting('SOCIAL_AUTH_PARTIAL_PIPELINE_KEY', 'partial_pipeline')
request.session[name] = data
开发者ID:Carlos-Mosquera,项目名称:nnmware,代码行数:12,代码来源:misc.py
示例4: convert_from_client_currency
def convert_from_client_currency(request, amount):
try:
if request.COOKIES['currency'] == setting('CURRENCY', 'RUB'):
return amount
currency = Currency.objects.get(code=request.COOKIES['currency'])
rate = ExchangeRate.objects.filter(currency=currency).filter(date__lte=now()).order_by('-date')[0]
if setting('OFFICIAL_RATE', True):
exchange = rate.official_rate
else:
exchange = rate.rate
return int((int(amount) * exchange) / rate.nominal)
except:
return int(amount)
开发者ID:cdrone-hotels,项目名称:nnmware,代码行数:13,代码来源:financial.py
示例5: avatar_set
def avatar_set(request):
uploader = AjaxUploader(filetype='image', upload_dir=setting('AVATAR_UPLOAD_DIR', 'avatars'),
size_limit=setting('AVATAR_UPLOAD_SIZE', 1024000))
result = uploader.handle_upload(request)
if result['success']:
request.user.img = result['path']
request.user.save()
try:
addons = dict(html=render_to_string('user/avatar.html', {'object': request.user}))
except:
addons = {}
result.update(addons)
return ajax_answer_lazy(result)
开发者ID:biomassives,项目名称:nnmware,代码行数:13,代码来源:ajax.py
示例6: validate_whitelists
def validate_whitelists(backend, email):
"""
Validates allowed domains and emails against the following settings:
GOOGLE_WHITE_LISTED_DOMAINS
GOOGLE_WHITE_LISTED_EMAILS
All domains and emails are allowed if setting is an empty list.
"""
emails = setting('GOOGLE_WHITE_LISTED_EMAILS', [])
domains = setting('GOOGLE_WHITE_LISTED_DOMAINS', [])
if emails and email in emails:
return # you're good
if domains and email.split('@', 1)[1] not in domains:
raise AuthFailed(backend, 'Domain not allowed')
开发者ID:MrTomato8,项目名称:nnmware,代码行数:14,代码来源:google.py
示例7: extra_data
def extra_data(self, user, uid, response, details):
"""Return defined extra data names to store in extra_data field.
Settings will be inspected to get more values names that should be
stored on extra_data field. Setting name is created from current
backend name (all uppercase) plus _SREG_EXTRA_DATA and
_AX_EXTRA_DATA because values can be returned by SimpleRegistration
or AttributeExchange schemas.
Both list must be a value name and an alias mapping similar to
SREG_ATTR, OLD_AX_ATTRS or AX_SCHEMA_ATTRS
"""
name = self.name.replace('-', '_').upper()
sreg_names = setting(name + '_SREG_EXTRA_DATA')
ax_names = setting(name + '_AX_EXTRA_DATA')
data = self.values_from_response(response, sreg_names, ax_names)
return data
开发者ID:MrTomato8,项目名称:nnmware,代码行数:16,代码来源:__init__.py
示例8: get_backends
def get_backends(force_load=False):
"""
Entry point to the BACKENDS cache. If BACKENDSCACHE hasn't been
populated, each of the modules referenced in
AUTHENTICATION_BACKENDS is imported and checked for a BACKENDS
definition and if enabled, added to the cache.
Previously all backends were attempted to be loaded at
import time of this module, which meant that backends that subclass
bases found in this module would not have the chance to be loaded
by the time they were added to this module's BACKENDS dict. See:
https://github.com/omab/django-social-auth/issues/204
This new approach ensures that backends are allowed to subclass from
bases in this module and still be picked up.
A force_load boolean arg is also provided so that get_backend
below can retry a requested backend that may not yet be discovered.
"""
if not BACKENDSCACHE or force_load:
for auth_backend in setting('AUTHENTICATION_BACKENDS'):
mod, cls_name = auth_backend.rsplit('.', 1)
module = import_module(mod)
backend = getattr(module, cls_name)
if issubclass(backend, SocialAuthBackend):
name = backend.name
backends = getattr(module, 'BACKENDS', {})
if name in backends and backends[name].enabled():
BACKENDSCACHE[name] = backends[name]
return BACKENDSCACHE
开发者ID:MrTomato8,项目名称:nnmware,代码行数:31,代码来源:__init__.py
示例9: expiration_datetime
def expiration_datetime(self):
"""Return provider session live seconds. Returns a timedelta ready to
use with session.set_expiry().
If provider returns a timestamp instead of session seconds to live, the
timedelta is inferred from current time (using UTC timezone). None is
returned if there's no value stored or it's invalid.
"""
name = setting('SOCIAL_AUTH_EXPIRATION', 'expires')
if self.extra_data and name in self.extra_data:
try:
expires = int(self.extra_data.get(name))
except (ValueError, TypeError):
return None
now = datetime.now()
now_timestamp = time.mktime(now.timetuple())
# Detect if expires is a timestamp
if expires > now_timestamp: # expires is a datetime
return datetime.utcfromtimestamp(expires) \
.replace(tzinfo=utc) - \
now.replace(tzinfo=utc)
else: # expires is a timedelta
return timedelta(seconds=expires)
开发者ID:MrTomato8,项目名称:nnmware,代码行数:25,代码来源:base.py
示例10: parse_currency
def parse_currency(on_date=None):
f = lambda x: Decimal(x.replace(',', '.'))
sdate = on_date or strftime("%d.%m.%Y", localtime())
d, m, y = map(lambda x: int(x), sdate.split('.'))
rate_date = datetime.date(y, m, d)
lst_currency = parse_xml_currency(currency_xml_input(sdate))
from nnmware.apps.money.models import ExchangeRate, Currency
currencies = Currency.objects.all().values_list('code', flat=True)
for currency in lst_currency:
charcode = currency['CharCode']
if charcode in currencies and charcode != setting('DEFAULT_CURRENCY', 'RUB'):
curr = Currency.objects.get(code=charcode)
# noinspection PyBroadException
try:
rate = ExchangeRate.objects.get(date=rate_date, currency=curr)
except:
rate = ExchangeRate()
rate.date = rate_date
rate.currency = curr
rate.nominal = currency['Nominal']
rate.official_rate = f(currency['Value'])
if not rate.rate:
rate.rate = f(currency['Value'])
rate.save()
return None
开发者ID:nnmware,项目名称:nnmware,代码行数:25,代码来源:parsers.py
示例11: auth_complete
def auth_complete(self, *args, **kwargs):
"""Performs check of authentication in VKontakte, returns User if
succeeded"""
app_cookie = 'vk_app_' + self.APP_ID
if not 'id' in self.request.GET or \
not app_cookie in self.request.COOKIES:
raise ValueError('VKontakte authentication is not completed')
cookie_dict = dict(item.split('=') for item in
self.request.COOKIES[app_cookie].split('&'))
check_str = ''.join(item + '=' + cookie_dict[item]
for item in ['expire', 'mid', 'secret', 'sid'])
hash = md5(check_str + setting('VKONTAKTE_APP_SECRET')).hexdigest()
if hash != cookie_dict['sig'] or int(cookie_dict['expire']) < time():
raise ValueError('VKontakte authentication failed: invalid hash')
else:
kwargs.update({
'auth': self,
'response': self.user_data(cookie_dict['mid']),
self.AUTH_BACKEND.name: True
})
return authenticate(*args, **kwargs)
开发者ID:MrTomato8,项目名称:nnmware,代码行数:25,代码来源:vkontakte.py
示例12: auth_extra_arguments
def auth_extra_arguments(self):
"""Return extra arguments needed on auth process, setting is per
backend and defined by:
<backend name in uppercase>_AUTH_EXTRA_ARGUMENTS.
"""
backend_name = self.AUTH_BACKEND.name.upper().replace('-', '_')
return setting(backend_name + '_AUTH_EXTRA_ARGUMENTS', {})
开发者ID:MrTomato8,项目名称:nnmware,代码行数:7,代码来源:__init__.py
示例13: get_user_id
def get_user_id(self, details, response):
"""Use google email or id as unique id"""
user_id = super(GoogleOAuth2Backend, self).get_user_id(details,
response)
if setting('GOOGLE_OAUTH2_USE_UNIQUE_USER_ID', False):
return response['id']
return user_id
开发者ID:MrTomato8,项目名称:nnmware,代码行数:7,代码来源:google.py
示例14: request_token_extra_arguments
def request_token_extra_arguments(self):
"""Return extra arguments needed on request-token process,
setting is per backend and defined by:
<backend name in uppercase>_REQUEST_TOKEN_EXTRA_ARGUMENTS.
"""
backend_name = self.AUTH_BACKEND.name.upper().replace('-', '_')
return setting(backend_name + '_REQUEST_TOKEN_EXTRA_ARGUMENTS', {})
开发者ID:MrTomato8,项目名称:nnmware,代码行数:7,代码来源:__init__.py
示例15: room_rates
def room_rates(request):
try:
json_data = json.loads(request.body)
currency = Currency.objects.get(code=setting('DEFAULT_CURRENCY', 'RUB'))
room = Room.objects.get(id=int(json_data['room_id']))
if request.user not in room.hotel.admins.all() and not request.user.is_superuser:
raise UserNotAllowed
# find settlements keys in data
all_settlements, all_discounts = [], []
for k in json_data.keys():
if k[0] == 's':
all_settlements.append(k)
elif k[0] == 'd':
all_discounts.append(k)
for i, v in enumerate(json_data['dates']):
on_date = datetime.fromtimestamp(time.mktime(time.strptime(v, "%d%m%Y")))
if 'placecount' in json_data.keys():
try:
placecount = int(json_data['placecount'][i])
try:
min_days = int(json_data['min_days'][i])
except:
min_days = None
# store availability
availability, created = Availability.objects.get_or_create(date=on_date, room=room)
availability.placecount = placecount
if min_days is not None:
availability.min_days = min_days
availability.save()
except ValueError:
pass
for k in all_discounts:
try:
discount_id = int(k[1:])
discount = Discount.objects.get(id=discount_id)
value = int(json_data[k][i])
room_discount, created = RoomDiscount.objects.get_or_create(date=on_date, discount=discount,
room=room)
room_discount.value = value
room_discount.save()
except ValueError:
pass
for k in all_settlements:
try:
settlement_id = int(k[1:])
settlement = SettlementVariant.objects.get(id=settlement_id)
price = int(json_data[k][i])
placeprice, created = PlacePrice.objects.get_or_create(date=on_date, settlement=settlement)
placeprice.amount = price
placeprice.currency = currency
placeprice.save()
except ValueError:
pass
payload = {'success': True}
except UserNotAllowed:
payload = {'success': False}
except:
payload = {'success': False}
return ajax_answer_lazy(payload)
开发者ID:biomassives,项目名称:nnmware,代码行数:59,代码来源:ajax.py
示例16: dsa_urlopen
def dsa_urlopen(*args, **kwargs):
"""Like urllib2.urlopen but sets a timeout defined by
SOCIAL_AUTH_URLOPEN_TIMEOUT setting if defined (and not already in
kwargs)."""
timeout = setting('SOCIAL_AUTH_URLOPEN_TIMEOUT')
if timeout and 'timeout' not in kwargs:
kwargs['timeout'] = timeout
return urlopen(*args, **kwargs)
开发者ID:Carlos-Mosquera,项目名称:nnmware,代码行数:8,代码来源:utils.py
示例17: build_absolute_uri
def build_absolute_uri(self, path=None):
"""Build absolute URI for given path. Replace http:// schema with
https:// if SOCIAL_AUTH_REDIRECT_IS_HTTPS is defined.
"""
uri = self.request.build_absolute_uri(path)
if setting('SOCIAL_AUTH_REDIRECT_IS_HTTPS'):
uri = uri.replace('http://', 'https://')
return uri
开发者ID:MrTomato8,项目名称:nnmware,代码行数:8,代码来源:__init__.py
示例18: extra_data
def extra_data(self, user, uid, response, details):
"""Return users extra data"""
# BrowserID sends timestamp for expiration date, here we
# convert it to the remaining seconds
expires = (response['expires'] / 1000) - time.mktime(now().timetuple())
return {
'audience': response['audience'],
'issuer': response['issuer'],
setting('SOCIAL_AUTH_EXPIRATION', 'expires'): expires
}
开发者ID:Carlos-Mosquera,项目名称:nnmware,代码行数:10,代码来源:browserid.py
示例19: room_rates
def room_rates(request):
try:
json_data = json.loads(request.body)
currency = Currency.objects.get(code=setting('DEFAULT_CURRENCY', 'RUB'))
hotel = Hotel.objects.get(id=int(json_data['hotel']))
if request.user not in hotel.admins.all() and not request.user.is_superuser:
raise UserNotAllowed
# find settlements keys in data
all_rooms, all_avail, all_limits = [], [], []
for k in json_data.keys():
if k[0] == 'r':
all_rooms.append(k)
elif k[0] == 'a':
all_avail.append(k)
elif k[0] == 'l':
all_limits.append(k)
for i, v in enumerate(json_data['dates']):
on_date = datetime.fromtimestamp(time.mktime(time.strptime(v, "%d%m%Y")))
for k in all_rooms:
try:
settlement_id = int(k[1:])
settlement = SettlementVariant.objects.get(id=settlement_id)
price = int(json_data[k][i])
placeprice, created = PlacePrice.objects.get_or_create(date=on_date, settlement=settlement)
placeprice.amount = price
placeprice.currency = currency
placeprice.save()
except ValueError:
pass
for k in all_avail:
try:
room_id = int(k[1:])
room = Room.objects.get(pk=room_id)
p = json_data[k][i]
if len(p.strip()) == 0:
placecount = 0
else:
placecount = int(p)
availability, created = Availability.objects.get_or_create(date=on_date, room=room)
availability.placecount = placecount
try:
min_days = int(json_data['l' + k[1:]][i])
except:
min_days = None
if min_days is not None:
availability.min_days = min_days
availability.save()
except ValueError:
pass
payload = {'success': True}
except UserNotAllowed:
payload = {'success': False}
except:
payload = {'success': False}
return ajax_answer_lazy(payload)
开发者ID:cdrone-hotels,项目名称:nnmware,代码行数:55,代码来源:ajax.py
示例20: user_data
def user_data(self, access_token, *args, **kwargs):
"""Return user data provided"""
fields_selectors = LINKEDIN_FIELD_SELECTORS + \
setting('LINKEDIN_EXTRA_FIELD_SELECTORS', [])
url = LINKEDIN_CHECK_AUTH + ':(%s)' % ','.join(fields_selectors)
request = self.oauth_request(access_token, url)
raw_xml = self.fetch_response(request)
try:
return to_dict(ElementTree.fromstring(raw_xml))
except (ExpatError, KeyError, IndexError):
return None
开发者ID:Carlos-Mosquera,项目名称:nnmware,代码行数:11,代码来源:linkedin.py
注:本文中的nnmware.core.utils.setting函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论