def from_request(self, request): if not hasattr(request, 'secretballot_token'): raise ImproperlyConfigured( 'To use secretballot a SecretBallotMiddleware must ' 'be installed. (see secretballot/middleware.py)') return self.from_token(request.secretballot_token)
def __init__(self, *args, **kwargs): if not hasattr(settings, 'ENCRYPTED_FIELD_KEYS_DIR'): raise ImproperlyConfigured('You must set settings.ENCRYPTED_FIELD_KEYS_DIR to your Keyczar keys directory.') self.crypt = keyczar.Crypter.Read(settings.ENCRYPTED_FIELD_KEYS_DIR) super(BaseEncryptedField, self).__init__(*args, **kwargs)
def get_env(key): try: return os.environ[key] except KeyError: raise ImproperlyConfigured(f'The environment var "{key}" is absolutely required to run this software')
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.contrib.auth.models import User from theme.models import UserProfile from utils import get_std_log_fields from hs_core.models import BaseResource from hs_core.hydroshare import get_resource_by_shortkey SESSION_TIMEOUT = settings.TRACKING_SESSION_TIMEOUT PROFILE_FIELDS = settings.TRACKING_PROFILE_FIELDS USER_FIELDS = settings.TRACKING_USER_FIELDS VISITOR_FIELDS = ["id"] + USER_FIELDS + PROFILE_FIELDS if set(PROFILE_FIELDS) & set(USER_FIELDS): raise ImproperlyConfigured( "hs_tracking PROFILE_FIELDS and USER_FIELDS must not contain" " overlapping field names") class SessionManager(models.Manager): def for_request(self, request, user=None): if hasattr(request, 'user'): user = request.user signed_id = request.session.get('hs_tracking_id') if signed_id: tracking_id = signing.loads(signed_id) cut_off = datetime.now() - timedelta(seconds=SESSION_TIMEOUT) session = None try:
if os.path.exists(DEV_ENVS): # Develop Env env_file = open(DEV_ENVS) elif os.path.exists(DEPLOY_ENVS): # Deploy Env env_file = open(DEPLOY_ENVS) else: env_file = None if env_file is None: # System environ try: #FACEBOOK_KEY = os.environ['FACEBOOK_KEY'] #FACEBOOK_SECRET = os.environ['FACEBOOK_SECRET'] GOOGLE_KEY = os.environ['GOOGLE_KEY'] GOOGLE_SECRET = os.environ['GOOGLE_SECRET'] except KeyError as error_msg: raise ImproperlyConfigured(error_msg) else: # JSON env envs = json.loads(env_file.read()) #FACEBOOK_KEY = get_env('FACEBOOK_KEY', envs) #FACEBOOK_SECRET = get_env('FACEBOOK_SECRET', envs) GOOGLE_KEY = get_env('GOOGLE_KEY', envs) GOOGLE_SECRET = get_env('GOOGLE_SECRET', envs) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '8sisfla$nu#t!!8(^ti6vowf7og3sd-e5bxadjgds&zyeq#pg3' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True
def get_success_url(self): if self.success_url: return self.success_url else: raise ImproperlyConfigured( "No URL to redirect to. Provide a success_url.")
def get_environment_variable(var_name, default_value=None): value = os.getenv(var_name, default_value) if value is None: error_msg = "Set the {0} environment variable".format(var_name) raise ImproperlyConfigured(error_msg) return value
def get_queryset(self): qs = super(SortableListMixin, self).get_queryset() if self.sort_fields and self.sort_fields_aliases: raise ImproperlyConfigured('You should provide sort_fields or sort_fields_aliaces but not both') return self._sort_queryset(qs)
MySQL database backend for Django. Requires MySQLdb: http://sourceforge.net/projects/mysql-python """ from __future__ import unicode_literals import datetime import re import sys import warnings try: import MySQLdb as Database except ImportError as e: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) from django.utils.functional import cached_property # We want version (1, 2, 1, 'final', 2) or later. We can't just use # lexicographic ordering in this check because then (1, 2, 1, 'gamma') # inadvertently passes the version test. version = Database.version_info if (version < (1, 2, 1) or (version[:3] == (1, 2, 1) and (len(version) < 5 or version[3] != 'final' or version[4] < 2))): from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured("MySQLdb-1.2.1p2 or newer is required; you have %s" % Database.__version__) from MySQLdb.converters import conversions, Thing2Literal from MySQLdb.constants import FIELD_TYPE, CLIENT
def get_secret(setting, keys=keys): try: return keys[setting] except KeyError: msg = 'Set the {} environment variable'.format(setting) raise ImproperlyConfigured(msg)
def get_secret(setting, secrets=secrets): try: return secrets[setting] except KeyError: error_msg = f'Set the {setting} environment variable.' raise ImproperlyConfigured(error_msg)
from django.core.exceptions import ImproperlyConfigured from django.http import HttpResponse try: from tablib import Dataset except ImportError: # pragma: no cover raise ImproperlyConfigured( "You must have tablib installed in order to use the django-tables2 export functionality" ) class TableExport: """ Export data from a table to the file type specified. Arguments: export_format (str): one of `csv, json, latex, ods, tsv, xls, xlsx, yml` table (`~.Table`): instance of the table to export the data from exclude_columns (iterable): list of column names to exclude from the export dataset_kwargs (dictionary): passed as `**kwargs` to `tablib.Dataset` constructor """ CSV = "csv" JSON = "json" LATEX = "latex" ODS = "ods" TSV = "tsv"
def env(setting): try: return os.environ[setting] except KeyError: error_msg = "Please set the '%s' env variable" % setting raise ImproperlyConfigured(error_msg)
def _safe_import_class(path): try: dot = path.rindex('.') except ValueError: raise ImproperlyConfigured('%s isn\'t a middleware module' % path) module_, classname_ = path[:dot], path[dot + 1:] try: mod = import_module(module_) except ImportError, e: raise ImproperlyConfigured('Error importing module %s: "%s"' % (module_, e)) try: auth_class = getattr(mod, classname_) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a "%s" class' % (module_, classname_)) return auth_class class ProxyingMetadataRegistry(MetadataRegistry): """ A registry that only writes, and does so by proxying to Providers. """ def __init__(self, providers): self._providers = providers def registerReader(self, metadata_prefix, reader): raise NotImplementedError def registerWriter(self, metadata_prefix, writer): raise NotImplementedError
def get(self, request): """Return a description of the registration form. This decouples clients from the API definition: if the API decides to modify the form, clients won't need to be updated. This is especially important for the registration form, since different edx-platform installations might collect different demographic information. See `user_api.helpers.FormDescription` for examples of the JSON-encoded form description. Arguments: request (HttpRequest) Returns: HttpResponse """ form_desc = FormDescription("post", reverse("user_api_registration")) self._apply_third_party_auth_overrides(request, form_desc) # Default fields are always required for field_name in self.DEFAULT_FIELDS: self.field_handlers[field_name](form_desc, required=True) # Custom form fields can be added via the form set in settings.REGISTRATION_EXTENSION_FORM custom_form = get_registration_extension_form() if custom_form: for field_name, field in custom_form.fields.items(): restrictions = {} if getattr(field, 'max_length', None): restrictions['max_length'] = field.max_length if getattr(field, 'min_length', None): restrictions['min_length'] = field.min_length field_options = getattr(getattr(custom_form, 'Meta', None), 'serialization_options', {}).get(field_name, {}) field_type = field_options.get( 'field_type', FormDescription.FIELD_TYPE_MAP.get(field.__class__)) if not field_type: raise ImproperlyConfigured( "Field type '{}' not recognized for registration extension field '{}'." .format(field_type, field_name)) form_desc.add_field( field_name, label=field.label, default=field_options.get('default'), field_type=field_options.get( 'field_type', FormDescription.FIELD_TYPE_MAP.get(field.__class__)), placeholder=field.initial, instructions=field.help_text, required=field.required, restrictions=restrictions, options=getattr(field, 'choices', None), error_messages=field.error_messages, include_default_option=field_options.get( 'include_default_option'), ) # Extra fields configured in Django settings # may be required, optional, or hidden for field_name in self.EXTRA_FIELDS: if self._is_field_visible(field_name): self.field_handlers[field_name]( form_desc, required=self._is_field_required(field_name)) # Add any Enterprise fields if the app is enabled insert_enterprise_fields(request, form_desc) return HttpResponse(form_desc.to_json(), content_type="application/json")
from django.core.files.storage import Storage from django.utils import timezone from django.utils.deconstruct import deconstructible from django.utils.encoding import force_bytes, smart_str from storages.utils import ( check_location, clean_name, get_available_overwrite_name, safe_join, setting, ) try: from google.cloud.storage import Blob, Client from google.cloud.storage.blob import _quote from google.cloud.exceptions import Conflict, NotFound except ImportError: raise ImproperlyConfigured("Could not load Google Cloud Storage bindings.\n" "See https://github.com/GoogleCloudPlatform/gcloud-python") class GoogleCloudFile(File): def __init__(self, name, mode, storage): self.name = name self.mime_type = mimetypes.guess_type(name)[0] self._mode = mode self._storage = storage self.blob = storage.bucket.get_blob(name) if not self.blob and 'w' in mode: self.blob = Blob( self.name, storage.bucket, chunk_size=setting('GS_BLOB_CHUNK_SIZE')) self._file = None self._is_dirty = False
def authenticate( self, username=None, #for 'password' and 'ldap' password=None, #for 'password' and 'ldap' user_id=None, #for 'force' provider_name=None, #required with all except email_key openid_url=None, email_key=None, email=None, # used with mozilla-persona method oauth_user_id=None, #used with oauth facebook_user_id=None, #user with facebook wordpress_url=None, # required for self hosted wordpress wp_user_id=None, # required for self hosted wordpress method=None, #requried parameter ): """this authentication function supports many login methods just which method it is going to use it determined from the signature of the function call """ login_providers = util.get_enabled_login_providers() assoc = None # UserAssociation not needed for ldap if method == 'password': if login_providers[provider_name]['type'] != 'password': raise ImproperlyConfigured('login provider must use password') if provider_name == 'local': try: user = User.objects.get(username=username) if not user.check_password(password): return None except User.DoesNotExist: try: email_address = username user = User.objects.get(email=email_address) if not user.check_password(password): return None except User.DoesNotExist: return None except User.MultipleObjectsReturned: LOG.critical( ('have more than one user with email %s ' + 'he/she will not be able to authenticate with ' + 'the email address in the place of user name') % email_address) return None else: if login_providers[provider_name]['check_password'](username, password): try: #if have user associated with this username and provider, #return the user assoc = UserAssociation.objects.get( openid_url=username + '@' + provider_name, #a hack - par name is bad provider_name=provider_name) return assoc.user except UserAssociation.DoesNotExist: #race condition here a user with this name may exist user, created = User.objects.get_or_create( username=username) if created: user.set_password(password) user.save() user_registered.send(None, user=user) else: #have username collision - so make up a more unique user name #bug: - if user already exists with the new username - we are in trouble new_username = '******' % (username, provider_name) user = User.objects.create_user( new_username, '', password) user_registered.send(None, user=user) message = _( 'Welcome! Please set email address (important!) in your ' 'profile and adjust screen name, if necessary.' ) user.message_set.create(message=message) else: return None #this is a catch - make login token a little more unique #for the cases when passwords are the same for two users #from the same provider try: assoc = UserAssociation.objects.get( user=user, provider_name=provider_name) except UserAssociation.DoesNotExist: assoc = UserAssociation(user=user, provider_name=provider_name) assoc.openid_url = username + '@' + provider_name #has to be this way for external pw logins elif method == 'openid': try: assoc = UserAssociation.objects.get(openid_url=openid_url) user = assoc.user except UserAssociation.DoesNotExist: return None except UserAssociation.MultipleObjectsReturned: logging.critical('duplicate openid url in the database!!! %s' % openid_url) return None elif method == 'mozilla-persona': try: assoc = UserAssociation.objects.get( openid_url=email, provider_name='mozilla-persona') return assoc.user except UserAssociation.DoesNotExist: return None except UserAssociation.MultipleObjectsReturned: logging.critical('duplicate user with mozilla persona %s!!!' % email) elif method == 'email': #with this method we do no use user association try: #todo: add email_key_timestamp field #and check key age user = User.objects.get(email_key=email_key) user.email_key = None #one time key so delete it user.email_isvalid = True user.save() return user except User.DoesNotExist: return None elif method in ('valid_email', 'any_email'): try: user = User.objects.get(email=email) except User.DoesNotExist: return None except User.MultipleObjectsReturned: LOG.critical(('have more than one user with email %s ' + 'he/she will not be able to authenticate with ' + 'the email address in the place of user name') % email_address) return None if method == 'valid_email' and user.email_isvalid == False: return None return user elif method == 'oauth': if login_providers[provider_name]['type'] in ('oauth', 'oauth2'): try: assoc = UserAssociation.objects.get( openid_url=oauth_user_id, provider_name=provider_name) user = assoc.user except UserAssociation.DoesNotExist: return None else: return None elif method == 'facebook': try: #assert(provider_name == 'facebook') assoc = UserAssociation.objects.get( openid_url=facebook_user_id, provider_name='facebook') user = assoc.user except UserAssociation.DoesNotExist: return None elif method == 'ldap': user_info = ldap_authenticate(username, password) if user_info['success'] == False: # Maybe a user created internally (django admin user) try: user = User.objects.get(username__exact=username) if user.check_password(password): return user else: return None except User.DoesNotExist: return None else: #load user by association or maybe auto-create one ldap_username = user_info['ldap_username'] try: #todo: provider_name is hardcoded - possible conflict assoc = UserAssociation.objects.get( openid_url=ldap_username + '@ldap', provider_name='ldap') user = assoc.user except UserAssociation.DoesNotExist: #email address is required if 'email' in user_info and askbot_settings.LDAP_AUTOCREATE_USERS: assoc = ldap_create_user(user_info) user = assoc.user else: return None elif method == 'wordpress_site': try: custom_wp_openid_url = '%s?user_id=%s' % (wordpress_url, wp_user_id) assoc = UserAssociation.objects.get( openid_url=custom_wp_openid_url, provider_name='wordpress_site') user = assoc.user except UserAssociation.DoesNotExist: return None elif method == 'force': return self.get_user(user_id) else: raise TypeError('only openid and password supported') if assoc: #update last used time assoc.last_used_timestamp = timezone.now() assoc.save() return user
def add_default_language_settings(languages_list, var_name='PARLER_LANGUAGES', **extra_defaults): """ Apply extra defaults to the language settings. This function can also be used by other packages to create their own variation of ``PARLER_LANGUAGES`` with extra fields. For example:: from django.conf import settings from parler import appsettings as parler_appsettings # Create local names, which are based on the global parler settings MYAPP_DEFAULT_LANGUAGE_CODE = getattr(settings, 'MYAPP_DEFAULT_LANGUAGE_CODE', parler_appsettings.PARLER_DEFAULT_LANGUAGE_CODE) MYAPP_LANGUAGES = getattr(settings, 'MYAPP_LANGUAGES', parler_appsettings.PARLER_LANGUAGES) # Apply the defaults to the languages MYAPP_LANGUAGES = parler_appsettings.add_default_language_settings(MYAPP_LANGUAGES, 'MYAPP_LANGUAGES', code=MYAPP_DEFAULT_LANGUAGE_CODE, fallback=MYAPP_DEFAULT_LANGUAGE_CODE, hide_untranslated=False ) The returned object will be an :class:`~parler.utils.conf.LanguagesSetting` object, which adds additional methods to the :class:`dict` object. :param languages_list: The settings, in :ref:`PARLER_LANGUAGES` format. :param var_name: The name of your variable, for debugging output. :param extra_defaults: Any defaults to override in the ``languages_list['default']`` section, e.g. ``code``, ``fallback``, ``hide_untranslated``. :return: The updated ``languages_list`` with all defaults applied to all sections. :rtype: LanguagesSetting """ languages_list = LanguagesSetting(languages_list) languages_list.setdefault('default', {}) defaults = languages_list['default'] defaults.setdefault( 'hide_untranslated', False ) # Whether queries with .active_translations() may or may not return the fallback language. if 'fallback' in defaults: #warnings.warn("Please use 'fallbacks' instead of 'fallback' in the 'defaults' section of {0}".format(var_name), DeprecationWarning) defaults['fallbacks'] = [defaults.pop('fallback')] if 'fallback' in extra_defaults: #warnings.warn("Please use 'fallbacks' instead of 'fallback' in parameters for {0} = add_default_language_settings(..)".format(var_name), DeprecationWarning) extra_defaults['fallbacks'] = [extra_defaults.pop('fallback')] defaults.update( extra_defaults) # Also allow to override code and fallback this way. # This function previously existed in appsettings, where it could reference the defaults directly. # However, this module is a more logical place for this function. To avoid circular import problems, # the 'code' and 'fallback' parameters are always passed by the appsettings module. # In case these are missing, default to the original behavior for backwards compatibility. if 'code' not in defaults: from parler import appsettings defaults['code'] = appsettings.PARLER_DEFAULT_LANGUAGE_CODE if 'fallbacks' not in defaults: from parler import appsettings defaults['fallbacks'] = [appsettings.PARLER_DEFAULT_LANGUAGE_CODE] if not is_supported_django_language(defaults['code']): raise ImproperlyConfigured( "The value for {0}['defaults']['code'] ('{1}') does not exist in LANGUAGES" .format(var_name, defaults['code'])) for site_id, lang_choices in six.iteritems(languages_list): if site_id == 'default': continue if not isinstance(lang_choices, (list, tuple)): raise ImproperlyConfigured( "{0}[{1}] should be a tuple of language choices!".format( var_name, site_id)) for i, choice in enumerate(lang_choices): if not is_supported_django_language(choice['code']): raise ImproperlyConfigured( "{0}[{1}][{2}]['code'] does not exist in LANGUAGES".format( var_name, site_id, i)) # Copy all items from the defaults, so you can provide new fields too. for key, value in six.iteritems(defaults): choice.setdefault(key, value) return languages_list
def set_txn(basket, shipping_methods, currency, return_url, cancel_url, update_url=None, action=SALE, user=None, user_address=None, shipping_method=None, shipping_address=None, no_shipping=False): """ Register the transaction with PayPal to get a token which we use in the redirect URL. This is the 'SetExpressCheckout' from their documentation. There are quite a few options that can be passed to PayPal to configure this request - most are controlled by PAYPAL_* settings. """ # PayPal have an upper limit on transactions. It's in dollars which is a # fiddly to work with. Lazy solution - only check when dollars are used as # the PayPal currency. amount = basket.total_incl_tax if currency == 'USD' and amount > 10000: raise exceptions.PayPalError( 'PayPal can only be used for orders up to 10000 USD') if amount <= 0: raise exceptions.PayPalError('Zero value basket is not allowed') # PAYMENTREQUEST_0_AMT should include tax, shipping and handling params = { 'PAYMENTREQUEST_0_AMT': amount, 'PAYMENTREQUEST_0_CURRENCYCODE': currency, 'RETURNURL': return_url, 'CANCELURL': cancel_url, 'PAYMENTREQUEST_0_PAYMENTACTION': action, } # Add item details index = 0 for index, line in enumerate(basket.all_lines()): product = line.product params['L_PAYMENTREQUEST_0_NAME%d' % index] = product.get_title() params['L_PAYMENTREQUEST_0_NUMBER%d' % index] = (product.upc if product.upc else '') desc = '' if product.description: desc = truncatewords(product.description, 12) params['L_PAYMENTREQUEST_0_DESC%d' % index] = desc # Note, we don't include discounts here - they are handled as separate # lines - see below params['L_PAYMENTREQUEST_0_AMT%d' % index] = _format_currency( line.unit_price_incl_tax) params['L_PAYMENTREQUEST_0_QTY%d' % index] = line.quantity # If the order has discounts associated with it, the way PayPal suggests # using the API is to add a separate item for the discount with the value # as a negative price. See "Integrating Order Details into the Express # Checkout Flow" # https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_ECCustomizing # Iterate over the 3 types of discount that can occur for discount in basket.offer_discounts: index += 1 name = _("Special Offer: %s") % discount['name'] params['L_PAYMENTREQUEST_0_NAME%d' % index] = name params['L_PAYMENTREQUEST_0_DESC%d' % index] = truncatewords(name, 12) params['L_PAYMENTREQUEST_0_AMT%d' % index] = _format_currency(-discount['discount']) params['L_PAYMENTREQUEST_0_QTY%d' % index] = 1 for discount in basket.voucher_discounts: index += 1 name = "%s (%s)" % (discount['voucher'].name, discount['voucher'].code) params['L_PAYMENTREQUEST_0_NAME%d' % index] = name params['L_PAYMENTREQUEST_0_DESC%d' % index] = truncatewords(name, 12) params['L_PAYMENTREQUEST_0_AMT%d' % index] = _format_currency(-discount['discount']) params['L_PAYMENTREQUEST_0_QTY%d' % index] = 1 for discount in basket.shipping_discounts: index += 1 name = _("Shipping Offer: %s") % discount['name'] params['L_PAYMENTREQUEST_0_NAME%d' % index] = name params['L_PAYMENTREQUEST_0_DESC%d' % index] = truncatewords(name, 12) params['L_PAYMENTREQUEST_0_AMT%d' % index] = _format_currency(-discount['discount']) params['L_PAYMENTREQUEST_0_QTY%d' % index] = 1 # We include tax in the prices rather than separately as that's how it's # done on most British/Australian sites. Will need to refactor in the # future no doubt. # Note that the following constraint must be met # # PAYMENTREQUEST_0_AMT = ( # PAYMENTREQUEST_0_ITEMAMT + # PAYMENTREQUEST_0_TAXAMT + # PAYMENTREQUEST_0_SHIPPINGAMT + # PAYMENTREQUEST_0_HANDLINGAMT) # # Hence, if tax is to be shown then it has to be aggregated up to the order # level. params['PAYMENTREQUEST_0_ITEMAMT'] = _format_currency( basket.total_incl_tax) params['PAYMENTREQUEST_0_TAXAMT'] = _format_currency(D('0.00')) # Customer services number customer_service_num = getattr(settings, 'PAYPAL_CUSTOMER_SERVICES_NUMBER', None) if customer_service_num: params['CUSTOMERSERVICENUMBER'] = customer_service_num # Display settings page_style = getattr(settings, 'PAYPAL_PAGESTYLE', None) header_image = getattr(settings, 'PAYPAL_HEADER_IMG', None) if page_style: params['PAGESTYLE'] = page_style elif header_image: params['LOGOIMG'] = header_image else: # Think these settings maybe deprecated in latest version of PayPal's # API display_params = { 'HDRBACKCOLOR': getattr(settings, 'PAYPAL_HEADER_BACK_COLOR', None), 'HDRBORDERCOLOR': getattr(settings, 'PAYPAL_HEADER_BORDER_COLOR', None), } params.update(x for x in display_params.items() if bool(x[1])) # Locale locale = getattr(settings, 'PAYPAL_LOCALE', None) if locale: valid_choices = ('AU', 'DE', 'FR', 'GB', 'IT', 'ES', 'JP', 'US') if locale not in valid_choices: raise ImproperlyConfigured("'%s' is not a valid locale code" % locale) params['LOCALECODE'] = locale # Confirmed shipping address confirm_shipping_addr = getattr(settings, 'PAYPAL_CONFIRM_SHIPPING', None) if confirm_shipping_addr: params['REQCONFIRMSHIPPING'] = 1 # Instant update callback information if update_url: params['CALLBACK'] = update_url params['CALLBACKTIMEOUT'] = getattr(settings, 'PAYPAL_CALLBACK_TIMEOUT', 3) # Contact details and address details - we provide these as it would make # the PayPal registration process smoother is the user doesn't already have # an account. if user: params['EMAIL'] = user.email if user_address: params['SHIPTONAME'] = user_address.name() params['SHIPTOSTREET'] = user_address.line1 params['SHIPTOSTREET2'] = user_address.line2 params['SHIPTOCITY'] = user_address.line4 params['SHIPTOSTATE'] = user_address.state params['SHIPTOZIP'] = user_address.postcode params['SHIPTOCOUNTRYCODE'] = user_address.country.iso_3166_1_a2 # Shipping details (if already set) - we override the SHIPTO* fields and # set a flag to indicate that these can't be altered on the PayPal side. if shipping_method and shipping_address: params['ADDROVERRIDE'] = 1 # It's recommend not to set 'confirmed shipping' if supplying the # shipping address directly. params['REQCONFIRMSHIPPING'] = 0 params['SHIPTONAME'] = shipping_address.name() params['SHIPTOSTREET'] = shipping_address.line1 params['SHIPTOSTREET2'] = shipping_address.line2 params['SHIPTOCITY'] = shipping_address.line4 params['SHIPTOSTATE'] = shipping_address.state params['SHIPTOZIP'] = shipping_address.postcode params['SHIPTOCOUNTRYCODE'] = shipping_address.country.iso_3166_1_a2 elif no_shipping: params['NOSHIPPING'] = 1 # Allow customer to specify a shipping note allow_note = getattr(settings, 'PAYPAL_ALLOW_NOTE', True) if allow_note: params['ALLOWNOTE'] = 1 # Shipping charges params['PAYMENTREQUEST_0_SHIPPINGAMT'] = _format_currency(D('0.00')) max_charge = D('0.00') for index, method in enumerate(shipping_methods): is_default = index == 0 params['L_SHIPPINGOPTIONISDEFAULT%d' % index] = 'true' if is_default else 'false' charge = method.basket_charge_incl_tax() if charge > max_charge: max_charge = charge if is_default: params['PAYMENTREQUEST_0_SHIPPINGAMT'] = _format_currency(charge) params['PAYMENTREQUEST_0_AMT'] += charge params['L_SHIPPINGOPTIONNAME%d' % index] = unicode(method.name) params['L_SHIPPINGOPTIONAMOUNT%d' % index] = _format_currency(charge) # Set shipping charge explicitly if it has been passed if shipping_method: max_charge = charge = shipping_method.basket_charge_incl_tax() params['PAYMENTREQUEST_0_SHIPPINGAMT'] = _format_currency(charge) params['PAYMENTREQUEST_0_AMT'] += charge # Both the old version (MAXAMT) and the new version (PAYMENT...) are needed # here - think it's a problem with the API. params['PAYMENTREQUEST_0_MAXAMT'] = _format_currency(amount + max_charge) params['MAXAMT'] = _format_currency(amount + max_charge) # Handling set to zero for now - I've never worked on a site that needed a # handling charge. params['PAYMENTREQUEST_0_HANDLINGAMT'] = _format_currency(D('0.00')) # Ensure that the total is formatted correctly. params['PAYMENTREQUEST_0_AMT'] = _format_currency( params['PAYMENTREQUEST_0_AMT']) txn = _fetch_response(SET_EXPRESS_CHECKOUT, params) # Construct return URL if getattr(settings, 'PAYPAL_SANDBOX_MODE', True): url = 'https://www.sandbox.paypal.com/webscr' else: url = 'https://www.paypal.com/webscr' params = ( ('cmd', '_express-checkout'), ('token', txn.token), ) return '%s?%s' % (url, urllib.urlencode(params))
def get_api_key(): if not conf.GCM_APIKEY: raise ImproperlyConfigured( "You haven't set the 'GCM_APIKEY' setting yet.") return conf.GCM_APIKEY
def get_env_value(env_variable): try: return os.environ[env_variable] except KeyError: error_msg = 'Set the {} environment variable'.format(env_variable) raise ImproperlyConfigured(error_msg)
LDAP_AUTHENTICATION = config.get("ldap_authentication") if LDAP_AUTHENTICATION: ALLOW_USER_EDITS = False AUTHENTICATION_BACKENDS.insert(0, "components.accounts.backends.CustomLDAPBackend") from .components.ldap_auth import * # noqa CAS_AUTHENTICATION = config.get("cas_authentication") if CAS_AUTHENTICATION: # CAS circumvents the Archivematica login screen and prevents usage # of other authentication methods, so we raise an exception if a # single sign-on option other than CAS is enabled. if SHIBBOLETH_AUTHENTICATION or LDAP_AUTHENTICATION: raise ImproperlyConfigured( "CAS authentication is not supported in tandem with other single " "sign-on methods. Please disable other Archivematica SSO settings " "(e.g. Shibboleth, LDAP) before proceeding." ) ALLOW_USER_EDITS = False INSTALLED_APPS += ["django_cas_ng"] AUTHENTICATION_BACKENDS += ["components.accounts.backends.CustomCASBackend"] # Insert CAS after the authentication middleware MIDDLEWARE.insert( MIDDLEWARE.index("django.contrib.auth.middleware.AuthenticationMiddleware") + 1, "django_cas_ng.middleware.CASMiddleware", ) from .components.cas_auth import * # noqa
default_context = { 'url' : url, 'static': static.static, '_': ugettext, } default_charset = getattr(settings, 'DEFAULT_CHARSET', 'utf8') app_template_dirs = [] fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding() for app in settings.INSTALLED_APPS: try: mod = import_module(app) except ImportError as e: raise ImproperlyConfigured('ImportError %s: %s' % (app, e.args[0])) template_dir = os.path.join(os.path.dirname(mod.__file__), 'templates') if os.path.isdir(template_dir): app_template_dirs.append(template_dir) template_lookup = TemplateLookup(directories=app_template_dirs, input_encoding=default_charset, output_encoding=default_charset, ) def render_to_response(filename, dictionary, context_instance=None): ''' :param filename: :param dictionary: :param context_instance:
from django.conf import settings from django.core.cache import cache from django.core.exceptions import ImproperlyConfigured from django.utils.translation import ugettext as _ ############################## ###### REQUIRED SETTIGS ###### ############################## try: API_KEY = settings.FLICKR_API_KEY SECRET = settings.FLICKR_SECRET USER_ID = settings.FLICKR_USER_ID except AttributeError: raise ImproperlyConfigured(_( "Need to define FLICKR_API_KEY and " "FLICKR_SECRET and FLICKR_USER_ID")) ############################## ###### OPTIONAL SETTIGS ###### ############################## LIST_ALBUMS_TEMPLATE = getattr(settings, 'FLICKR_LIST_ALBUMS_TEMPLATE', "gallery/flickr/album.html") LIST_PHOTOS_TEMPLATE = getattr(settings, 'FLICKR_LIST_PHOTOS_TEMPLATE', "gallery/flickr/photos.html") PER_PAGE = getattr(settings, 'FLICKR_PER_PAGE', 30) PER_PAGE_FIELD = getattr(settings, 'FLICKR_PER_PAGE_FIELD', "page") ########################### ###### OTHER SETTIGS ###### ########################### FLICKR_STORE_TOKEN = True
def get_env(setting, envs): try: return envs[setting] except KeyError: error_msg = "You SHOULD set {} environ".format(setting) raise ImproperlyConfigured(error_msg)
def get_app_label(): if not _app_label: raise ImproperlyConfigured("Application label is not detected. " "Check whether the configure() was called.") return _app_label
'default': dj_database_url.config(default=DATABASE_URL, conn_max_age=600) } elif os.environ.get('POSTHOG_DB_NAME'): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': get_env('POSTHOG_DB_NAME'), 'USER': os.environ.get('POSTHOG_DB_USER', 'postgres'), 'PASSWORD': os.environ.get('POSTHOG_DB_PASSWORD', ''), 'HOST': os.environ.get('POSTHOG_POSTGRES_HOST', 'localhost'), 'PORT': os.environ.get('POSTHOG_POSTGRES_PORT', '5432'), 'CONN_MAX_AGE': 0, } } else: raise ImproperlyConfigured(f'The environment vars "DATABASE_URL" or "POSTHOG_DB_NAME" are absolutely required to run this software') # Broker # The last case happens when someone upgrades Heroku but doesn't have Redis installed yet. Collectstatic gets called before we can provision Redis. if TEST or DEBUG or (sys.argv[1] and sys.argv[1] == 'collectstatic'): REDIS_URL = os.environ.get('REDIS_URL', 'redis://localhost/') else: REDIS_URL = os.environ.get('REDIS_URL', '') if not REDIS_URL and os.environ.get('POSTHOG_REDIS_HOST', ''): REDIS_URL = "redis://:{}@{}:{}/".format(os.environ.get('POSTHOG_REDIS_PASSWORD', ''), os.environ.get('POSTHOG_REDIS_HOST', ''), os.environ.get('POSTHOG_REDIS_PORT', '6379')) if not REDIS_URL: print("тЪая╕ПтЪая╕ПтЪая╕ПтЪая╕ПтЪая╕ПтЪая╕ПтЪая╕ПтЪая╕ПтЪая╕ПтЪая╕ПтЪая╕ПтЪая╕ПтЪая╕ПтЪая╕ПтЪая╕ПтЪая╕ПтЪая╕ПтЪая╕ПтЪая╕ПтЪая╕ПтЪая╕ПтЪая╕ПтЪая╕ПтЪая╕ПтЪая╕ПтЪая╕П") print("я╕ПтЪая╕П ЁЯЪиЁЯЪиЁЯЪи PostHog warning! ЁЯЪиЁЯЪиЁЯЪи")
def get_secret(setting, secrets=secrets): try: return secrets[setting] except KeyError: error_msg = "Set the {} environment variable".format(setting) raise ImproperlyConfigured(error_msg)
def _check_connection(self, connection): # Make sure raster fields are used only on backends with raster support. if not connection.features.gis_enabled or not connection.features.supports_raster: raise ImproperlyConfigured( 'Raster fields require backends with raster support.')
for old_suffix, new_key in DEPRECATED_AWS_SETTINGS: old_key = 'DBBACKUP_S3_%s' % old_suffix if hasattr(settings, old_key): STORAGE_OPTIONS[new_key] = getattr(settings, old_key) msg = "%s is deprecated, use DBBACKUP_STORAGE_OPTIONS['%s']" % ( old_key, new_key) warnings.warn(msg, DeprecationWarning) for old_suffix in UNSED_AWS_SETTINGS: if hasattr(settings, 'DBBACKUP_S3_%s' % old_suffix): msg = "DBBACKUP_S3_%s is now useless" % old_suffix warnings.warn(msg, DeprecationWarning) del old_suffix, new_key # TODO: Make a module ? # Checks for sett in [ sett for sett in locals().copy() if sett.endswith('FILENAME_TEMPLATE') ]: if callable(locals()[sett]): continue for param in ('datetime', ): if '{%s}' % param not in locals()[sett]: msg = "You must provide '{%s}' in DBBACKUP_%s" % ( param, 'FILENAME_TEMPLATE') raise ImproperlyConfigured(msg) del sett if re.search(r'[^A-Za-z0-9%_-]', DATE_FORMAT): # pragma: no cover msg = "Bad DBBACKUP_DATE_FORMAT: %s, it must match with [A-Za-z0-9%_-]" % DATE_FORMAT raise ImproperlyConfigured(msg)