INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Deserialize data based on the schema defined by fields_dict.
def _deserialize( self, data, fields_dict, error_store, many=False, partial=False, unknown=RAISE, dict_class=dict, index_errors=True, index=None, ): """Deserialize ``data`` based on the schema defined by ``fields_dict``. :param dict data: The data to deserialize. :param dict...
Deserialize a data structure to an object defined by this Schema s fields.
def load(self, data, many=None, partial=None, unknown=None): """Deserialize a data structure to an object defined by this Schema's fields. :param dict data: The data to deserialize. :param bool many: Whether to deserialize `data` as a collection. If `None`, the value for `self.many`...
Same as: meth: load except it takes a JSON string as input.
def loads( self, json_data, many=None, partial=None, unknown=None, **kwargs ): """Same as :meth:`load`, except it takes a JSON string as input. :param str json_data: A JSON string of the data to deserialize. :param bool many: Whether to deserialize `obj` as a collection. If ...
Validate data against the schema returning a dictionary of validation errors.
def validate(self, data, many=None, partial=None): """Validate `data` against the schema, returning a dictionary of validation errors. :param dict data: The data to validate. :param bool many: Whether to validate `data` as a collection. If `None`, the value for `self.many` i...
Deserialize data returning the deserialized result.
def _do_load( self, data, many=None, partial=None, unknown=None, postprocess=True, ): """Deserialize `data`, returning the deserialized result. :param data: The data to deserialize. :param bool many: Whether to deserialize `data` as a collection. If `None`, the v...
Apply then flatten nested schema options
def _normalize_nested_options(self): """Apply then flatten nested schema options""" if self.only is not None: # Apply the only option to nested fields. self.__apply_nested_option('only', self.only, 'intersection') # Remove the child field names from the only option. ...
Apply nested options to nested fields
def __apply_nested_option(self, option_name, field_names, set_operation): """Apply nested options to nested fields""" # Split nested field names on the first dot. nested_fields = [name.split('.', 1) for name in field_names if '.' in name] # Partition the nested field names by parent fiel...
Update fields based on schema options.
def _init_fields(self): """Update fields based on schema options.""" if self.opts.fields: available_field_names = self.set_class(self.opts.fields) else: available_field_names = self.set_class(self.declared_fields.keys()) if self.opts.additional: ...
Bind field to the schema setting any necessary attributes on the field ( e. g. parent and name ).
def _bind_field(self, field_name, field_obj): """Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name). Also set field load_only and dump_only values if field_name was specified in ``class Meta``. """ try: if field_nam...
Register a schema - level validator.
def validates_schema( fn=None, pass_many=False, pass_original=False, skip_on_field_errors=True, ): """Register a schema-level validator. By default, receives a single object at a time, regardless of whether ``many=True`` is passed to the `Schema`. If ``pass_many=True``, the raw data (which ...
Register a method to invoke after serializing an object. The method receives the serialized object and returns the processed object.
def post_dump(fn=None, pass_many=False, pass_original=False): """Register a method to invoke after serializing an object. The method receives the serialized object and returns the processed object. By default, receives a single object at a time, transparently handling the ``many`` argument passed to th...
Register a method to invoke after deserializing an object. The method receives the deserialized data and returns the processed data.
def post_load(fn=None, pass_many=False, pass_original=False): """Register a method to invoke after deserializing an object. The method receives the deserialized data and returns the processed data. By default, receives a single datum at a time, transparently handling the ``many`` argument passed to the...
Mark decorated function as a hook to be picked up later.
def set_hook(fn, key, **kwargs): """Mark decorated function as a hook to be picked up later. .. note:: Currently only works with functions and instance methods. Class and static methods are not supported. :return: Decorated function if supplied, else this decorator with its args bo...
Return a generator over the ( value label ) pairs where value is a string associated with each choice. This convenience method is useful to populate for instance a form select field.
def options(self, valuegetter=text_type): """Return a generator over the (value, label) pairs, where value is a string associated with each choice. This convenience method is useful to populate, for instance, a form select field. :param valuegetter: Can be a callable or a string. In the...
Deeply merge two error messages.
def merge_errors(errors1, errors2): """Deeply merge two error messages. The format of ``errors1`` and ``errors2`` matches the ``message`` parameter of :exc:`marshmallow.exceptions.ValidationError`. """ if not errors1: return errors2 if not errors2: return errors1 if isinstan...
Add a class to the registry of serializer classes. When a class is registered an entry for both its classname and its full module - qualified path are added to the registry.
def register(classname, cls): """Add a class to the registry of serializer classes. When a class is registered, an entry for both its classname and its full, module-qualified path are added to the registry. Example: :: class MyClass: pass register('MyClass', MyClass) ...
Retrieve a class from the registry.
def get_class(classname, all=False): """Retrieve a class from the registry. :raises: marshmallow.exceptions.RegistryError if the class cannot be found or if there are multiple entries for the given class name. """ try: classes = _registry[classname] except KeyError: raise Re...
Return the value for a given key from an object.
def get_value(self, obj, attr, accessor=None, default=missing_): """Return the value for a given key from an object. :param object obj: The object to get the value from :param str attr: The attribute/key in `obj` to get the value from. :param callable accessor: A callable used to retrie...
Perform validation on value. Raise a: exc: ValidationError if validation does not succeed.
def _validate(self, value): """Perform validation on ``value``. Raise a :exc:`ValidationError` if validation does not succeed. """ errors = [] kwargs = {} for validator in self.validators: try: r = validator(value) if not isinst...
Validate missing values. Raise a: exc: ValidationError if value should be considered missing.
def _validate_missing(self, value): """Validate missing values. Raise a :exc:`ValidationError` if `value` should be considered missing. """ if value is missing_: if hasattr(self, 'required') and self.required: self.fail('required') if value is None: ...
Pulls the value for the given key from the object applies the field s formatting and returns the result.
def serialize(self, attr, obj, accessor=None, **kwargs): """Pulls the value for the given key from the object, applies the field's formatting and returns the result. :param str attr: The attribute or key to get from the object. :param str obj: The object to pull the key from. :p...
Deserialize value.
def deserialize(self, value, attr=None, data=None, **kwargs): """Deserialize ``value``. :param value: The value to be deserialized. :param str attr: The attribute/key in `data` to be deserialized. :param dict data: The raw input data passed to the `Schema.load`. :param dict kwar...
Update field with values from its parent schema. Called by: meth: _bind_field<marshmallow. Schema. _bind_field >.
def _bind_to_schema(self, field_name, schema): """Update field with values from its parent schema. Called by :meth:`_bind_field<marshmallow.Schema._bind_field>`. :param str field_name: Field name set in schema. :param Schema schema: Parent schema. """ self.parent = s...
Reference to the Schema that this field belongs to even if it is buried in a List. Return None for unbound fields.
def root(self): """Reference to the `Schema` that this field belongs to even if it is buried in a `List`. Return `None` for unbound fields. """ ret = self while hasattr(ret, 'parent') and ret.parent: ret = ret.parent return ret if isinstance(ret, SchemaABC) el...
The nested Schema object.
def schema(self): """The nested Schema object. .. versionchanged:: 1.0.0 Renamed from `serializer` to `schema` """ if not self.__schema: # Inherit context from parent. context = getattr(self.parent, 'context', {}) if isinstance(self.nested...
Same as: meth: Field. _deserialize with additional partial argument.
def _deserialize(self, value, attr, data, partial=None, **kwargs): """Same as :meth:`Field._deserialize` with additional ``partial`` argument. :param bool|tuple partial: For nested schemas, the ``partial`` parameter passed to `Schema.load`. .. versionchanged:: 3.0.0 Add...
Format the value or raise a: exc: ValidationError if an error occurs.
def _validated(self, value): """Format the value or raise a :exc:`ValidationError` if an error occurs.""" if value is None: return None if isinstance(value, uuid.UUID): return value try: if isinstance(value, bytes) and len(value) == 16: ...
Return the number value for value given this field s num_type.
def _format_num(self, value): """Return the number value for value, given this field's `num_type`.""" # (value is True or value is False) is ~5x faster than isinstance(value, bool) if value is True or value is False: raise TypeError('value must be a Number, not a boolean.') r...
Format the value or raise a: exc: ValidationError if an error occurs.
def _validated(self, value): """Format the value or raise a :exc:`ValidationError` if an error occurs.""" if value is None: return None try: return self._format_num(value) except (TypeError, ValueError): self.fail('invalid', input=value) except...
Return a string if self. as_string = True otherwise return this field s num_type.
def _serialize(self, value, attr, obj, **kwargs): """Return a string if `self.as_string=True`, otherwise return this field's `num_type`.""" ret = self._validated(value) return ( self._to_string(ret) if (self.as_string and ret not in (None, missing_)) else ret ...
Deserialize an ISO8601 - formatted time to a: class: datetime. time object.
def _deserialize(self, value, attr, data, **kwargs): """Deserialize an ISO8601-formatted time to a :class:`datetime.time` object.""" if not value: # falsy values are invalid self.fail('invalid') try: return utils.from_iso_time(value) except (AttributeError, TypeE...
Return True if val is either a subclass or instance of class_.
def is_instance_or_subclass(val, class_): """Return True if ``val`` is either a subclass or instance of ``class_``.""" try: return issubclass(val, class_) except TypeError: return isinstance(val, class_)
Pretty - printing function that can pretty - print OrderedDicts like regular dictionaries. Useful for printing the output of: meth: marshmallow. Schema. dump.
def pprint(obj, *args, **kwargs): """Pretty-printing function that can pretty-print OrderedDicts like regular dictionaries. Useful for printing the output of :meth:`marshmallow.Schema.dump`. """ if isinstance(obj, collections.OrderedDict): print(json.dumps(obj, *args, **kwargs)) else: ...
Return the RFC822 - formatted representation of a timezone - aware datetime with the UTC offset.
def local_rfcformat(dt): """Return the RFC822-formatted representation of a timezone-aware datetime with the UTC offset. """ weekday = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][dt.weekday()] month = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov'...
Return the RFC822 - formatted representation of a datetime object.
def rfcformat(dt, localtime=False): """Return the RFC822-formatted representation of a datetime object. :param datetime dt: The datetime. :param bool localtime: If ``True``, return the date relative to the local timezone instead of UTC, displaying the proper offset, e.g. "Sun, 10 Nov 2013 0...
Return the ISO8601 - formatted UTC representation of a datetime object.
def isoformat(dt, localtime=False, *args, **kwargs): """Return the ISO8601-formatted UTC representation of a datetime object.""" if localtime and dt.tzinfo is not None: localized = dt else: if dt.tzinfo is None: localized = UTC.localize(dt) else: localized = d...
Parse a RFC822 - formatted datetime string and return a datetime object.
def from_rfc(datestring, use_dateutil=True): """Parse a RFC822-formatted datetime string and return a datetime object. Use dateutil's parser if possible. https://stackoverflow.com/questions/885015/how-to-parse-a-rfc-2822-date-time-into-a-python-datetime """ # Use dateutil's parser if possible ...
Parse an ISO8601 - formatted datetime string and return a datetime object.
def from_iso_datetime(datetimestring, use_dateutil=True): """Parse an ISO8601-formatted datetime string and return a datetime object. Use dateutil's parser if possible and return a timezone-aware datetime. """ if not _iso8601_datetime_re.match(datetimestring): raise ValueError('Not a valid ISO8...
Parse an ISO8601 - formatted datetime string and return a datetime. time object.
def from_iso_time(timestring, use_dateutil=True): """Parse an ISO8601-formatted datetime string and return a datetime.time object. """ if not _iso8601_time_re.match(timestring): raise ValueError('Not a valid ISO8601-formatted time string') if dateutil_available and use_dateutil: retu...
Set a value in a dict. If key contains a. it is assumed be a path ( i. e. dot - delimited string ) to the value s location.
def set_value(dct, key, value): """Set a value in a dict. If `key` contains a '.', it is assumed be a path (i.e. dot-delimited string) to the value's location. :: >>> d = {} >>> set_value(d, 'foo.bar', 42) >>> d {'foo': {'bar': 42}} """ if '.' in key: head, ...
Given a callable return a tuple of argument names. Handles functools. partial objects and class - based callables.
def get_func_args(func): """Given a callable, return a tuple of argument names. Handles `functools.partial` objects and class-based callables. .. versionchanged:: 3.0.0a1 Do not return bound arguments, eg. ``self``. """ if isinstance(func, functools.partial): return _signature(func....
Return a Schema instance from a Schema class or instance.
def resolve_field_instance(cls_or_instance): """Return a Schema instance from a Schema class or instance. :param type|Schema cls_or_instance: Marshmallow Schema class or instance. """ if isinstance(cls_or_instance, type): if not issubclass(cls_or_instance, FieldABC): raise FieldInst...
Convert naive time to local time
def localize(self, dt, is_dst=False): """Convert naive time to local time""" if dt.tzinfo is not None: raise ValueError('Not naive datetime (tzinfo is already set)') return dt.replace(tzinfo=self)
Correct the timezone information on the given datetime
def normalize(self, dt, is_dst=False): """Correct the timezone information on the given datetime""" if dt.tzinfo is self: return dt if dt.tzinfo is None: raise ValueError('Naive time - no tzinfo set') return dt.astimezone(self)
Check if a username/ password combination is valid.
def check_auth(email, password): """Check if a username/password combination is valid. """ try: user = User.get(User.email == email) except User.DoesNotExist: return False return password == user.password
Now be aware the following is quite ugly let me explain:
def _stash_user(cls, user): """Now, be aware, the following is quite ugly, let me explain: Even if the user credentials match, the authentication can fail because Django's default ModelBackend calls user_can_authenticate(), which checks `is_active`. Now, earlier versions of allauth did ...
Fetches email address from email API endpoint
def get_email(self, token): """Fetches email address from email API endpoint""" resp = requests.get(self.emails_url, params={'access_token': token.token}) emails = resp.json().get('values', []) email = '' try: email = emails[0].get('email')...
Checks whether or not the email address is already verified beyond allauth scope for example by having accepted an invitation before signing up.
def is_email_verified(self, request, email): """ Checks whether or not the email address is already verified beyond allauth scope, for example, by having accepted an invitation before signing up. """ ret = False verified_email = request.session.get('account_verifi...
Returns the default URL to redirect to after logging in. Note that URLs passed explicitly ( e. g. by passing along a next GET parameter ) take precedence over the value returned here.
def get_login_redirect_url(self, request): """ Returns the default URL to redirect to after logging in. Note that URLs passed explicitly (e.g. by passing along a `next` GET parameter) take precedence over the value returned here. """ assert request.user.is_authenticated ...
The URL to return to after successful e - mail confirmation.
def get_email_confirmation_redirect_url(self, request): """ The URL to return to after successful e-mail confirmation. """ if request.user.is_authenticated: if app_settings.EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL: return \ app_settin...
Fills in a valid username if required and missing. If the username is already present it is assumed to be valid ( unique ).
def populate_username(self, request, user): """ Fills in a valid username, if required and missing. If the username is already present it is assumed to be valid (unique). """ from .utils import user_username, user_email, user_field first_name = user_field(user, '...
Saves a new User instance using information provided in the signup form.
def save_user(self, request, user, form, commit=True): """ Saves a new `User` instance using information provided in the signup form. """ from .utils import user_username, user_email, user_field data = form.cleaned_data first_name = data.get('first_name') ...
Validates the username. You can hook into this if you want to ( dynamically ) restrict what usernames can be chosen.
def clean_username(self, username, shallow=False): """ Validates the username. You can hook into this if you want to (dynamically) restrict what usernames can be chosen. """ for validator in app_settings.USERNAME_VALIDATORS: validator(username) # TODO: Add re...
Validates a password. You can hook into this if you want to restric the allowed password choices.
def clean_password(self, password, user=None): """ Validates a password. You can hook into this if you want to restric the allowed password choices. """ min_length = app_settings.PASSWORD_MIN_LENGTH if min_length and len(password) < min_length: raise forms.Val...
Wrapper of django. contrib. messages. add_message that reads the message text from a template.
def add_message(self, request, level, message_template, message_context=None, extra_tags=''): """ Wrapper of `django.contrib.messages.add_message`, that reads the message text from a template. """ if 'django.contrib.messages' in settings.INSTALLED_APPS: ...
Marks the email address as confirmed on the db
def confirm_email(self, request, email_address): """ Marks the email address as confirmed on the db """ email_address.verified = True email_address.set_as_primary(conditional=True) email_address.save()
Constructs the email confirmation ( activation ) url.
def get_email_confirmation_url(self, request, emailconfirmation): """Constructs the email confirmation (activation) url. Note that if you have architected your system such that email confirmations are sent outside of the request context `request` can be `None` here. """ ...
Only authenticates does not actually login. See login
def authenticate(self, request, **credentials): """Only authenticates, does not actually login. See `login`""" from allauth.account.auth_backends import AuthenticationBackend self.pre_authenticate(request, **credentials) AuthenticationBackend.unstash_authenticated_user() user = ...
Extract fields from a metadata query.
def extract_common_fields(self, data): """Extract fields from a metadata query.""" return dict( dc=data.get('dc'), role=data.get('role'), account_name=data.get('accountname'), user_id=data.get('user_id'), login=data.get('login'), lo...
Convert XML structure to dict recursively repeated keys entries are returned as in list containers.
def to_dict(self, xml): """ Convert XML structure to dict recursively, repeated keys entries are returned as in list containers. """ children = list(xml) if not children: return xml.text else: out = {} for node in list(xml): ...
{ % provider_login_url facebook next = bla % } { % provider_login_url openid openid = http:// me. yahoo. com next = bla % }
def provider_login_url(parser, token): """ {% provider_login_url "facebook" next=bla %} {% provider_login_url "openid" openid="http://me.yahoo.com" next=bla %} """ bits = token.split_contents() provider_id = bits[1] params = token_kwargs(bits[2:], parser, support_legacy=False) return Pro...
{ % get_social_accounts user as accounts % }
def get_social_accounts(user): """ {% get_social_accounts user as accounts %} Then: {{accounts.twitter}} -- a list of connected Twitter accounts {{accounts.twitter.0}} -- the first Twitter account {% if accounts %} -- if there is at least one social account """ accounts = {}...
Saves a newly signed up social login. In case of auto - signup the signup form is not available.
def save_user(self, request, sociallogin, form=None): """ Saves a newly signed up social login. In case of auto-signup, the signup form is not available. """ u = sociallogin.user u.set_unusable_password() if form: get_account_adapter().save_user(reques...
Hook that can be used to further populate the user instance.
def populate_user(self, request, sociallogin, data): """ Hook that can be used to further populate the user instance. For convenience, we populate several common fields. Note that the user instance being populated repres...
Returns the default URL to redirect to after successfully connecting a social account.
def get_connect_redirect_url(self, request, socialaccount): """ Returns the default URL to redirect to after successfully connecting a social account. """ assert request.user.is_authenticated url = reverse('socialaccount_connections') return url
Validate whether or not the socialaccount account can be safely disconnected.
def validate_disconnect(self, account, accounts): """ Validate whether or not the socialaccount account can be safely disconnected. """ if len(accounts) == 1: # No usable password would render the local account unusable if not account.user.has_usable_passw...
Since Django 1. 6 items added to the session are no longer pickled but JSON encoded by default. We are storing partially complete models in the session ( user account token... ). We cannot use standard Django serialization as these are models are not complete yet. Serialization will start complaining about missing rela...
def serialize_instance(instance): """ Since Django 1.6 items added to the session are no longer pickled, but JSON encoded by default. We are storing partially complete models in the session (user, account, token, ...). We cannot use standard Django serialization, as these are models are not "complet...
This function is a verbatim copy of django. forms. Form. order_fields () to support field ordering below Django 1. 9.
def set_form_field_order(form, field_order): """ This function is a verbatim copy of django.forms.Form.order_fields() to support field ordering below Django 1.9. field_order is a list of field names specifying the order. Append fields not included in the list in the default order for backward compa...
request. build_absolute_uri () helper
def build_absolute_uri(request, location, protocol=None): """request.build_absolute_uri() helper Like request.build_absolute_uri, but gracefully handling the case where request is None. """ from .account import app_settings as account_settings if request is None: site = Site.objects.ge...
Currently we inherit from the custom form if any. This is all not very elegant though it serves a purpose:
def _base_signup_form_class(): """ Currently, we inherit from the custom form, if any. This is all not very elegant, though it serves a purpose: - There are two signup forms: one for local accounts, and one for social accounts - Both share a common base (BaseSignupForm) - Given the above...
Provides the credentials required to authenticate the user for login.
def user_credentials(self): """ Provides the credentials required to authenticate the user for login. """ credentials = {} login = self.cleaned_data["login"] if app_settings.AUTHENTICATION_METHOD == AuthenticationMethod.EMAIL: credentials["email"] = lo...
Parses the FacebookLocales. xml file and builds a dict relating every available language ( en es zh... ) with a list of available regions for that language ( en - > US EN ) and an ( arbitrary ) default region.
def _build_locale_table(filename_or_file): """ Parses the FacebookLocales.xml file and builds a dict relating every available language ('en, 'es, 'zh', ...) with a list of available regions for that language ('en' -> 'US', 'EN') and an (arbitrary) default region. """ # Require the XML parser mod...
Wrapper function so that the default mapping is only built when needed
def get_default_locale_callable(): """ Wrapper function so that the default mapping is only built when needed """ exec_dir = os.path.dirname(os.path.realpath(__file__)) xml_path = os.path.join(exec_dir, 'data', 'FacebookLocales.xml') fb_locales = _build_locale_table(xml_path) def default_l...
The user is required to hand over an e - mail address when signing up
def EMAIL_REQUIRED(self): """ The user is required to hand over an e-mail address when signing up """ from allauth.account import app_settings as account_settings return self._setting("EMAIL_REQUIRED", account_settings.EMAIL_REQUIRED)
See e - mail verification method
def EMAIL_VERIFICATION(self): """ See e-mail verification method """ from allauth.account import app_settings as account_settings return self._setting("EMAIL_VERIFICATION", account_settings.EMAIL_VERIFICATION)
Returns string representation of a social account. Includes the name of the user.
def to_str(self): ''' Returns string representation of a social account. Includes the name of the user. ''' dflt = super(DataportenAccount, self).to_str() return '%s (%s)' % ( self.account.extra_data.get('name', ''), dflt, )
This function extracts information from the/ userinfo endpoint which will be consumed by allauth. socialaccount. adapter. populate_user (). Look there to find which key - value pairs that should be saved in the returned dict.
def extract_common_fields(self, data): ''' This function extracts information from the /userinfo endpoint which will be consumed by allauth.socialaccount.adapter.populate_user(). Look there to find which key-value pairs that should be saved in the returned dict. Typical ...
Even when email verification is not mandatory during signup there may be circumstances during which you really want to prevent unverified users to proceed. This decorator ensures the user is authenticated and has a verified email address. If the former is not the case then the behavior is identical to that of the stand...
def verified_email_required(function=None, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """ Even when email verification is not mandatory during signup, there may be circumstances during which you really want to prevent unverified user...
Added because the Dropbox OAuth2 flow doesn t work when scope is passed in which is empty.
def _strip_empty_keys(self, params): """Added because the Dropbox OAuth2 flow doesn't work when scope is passed in, which is empty. """ keys = [k for k, v in params.items() if v == ''] for key in keys: del params[key]
Django on py2 raises ValueError on large values.
def int_to_base36(i): """ Django on py2 raises ValueError on large values. """ if six.PY2: char_set = '0123456789abcdefghijklmnopqrstuvwxyz' if i < 0: raise ValueError("Negative base36 conversion input.") if not isinstance(i, six.integer_types): raise Type...
Saves a new account. Note that while the account is new the user may be an existing one ( when connecting accounts )
def save(self, request, connect=False): """ Saves a new account. Note that while the account is new, the user may be an existing one (when connecting accounts) """ assert not self.is_existing user = self.user user.save() self.account.user = user se...
Lookup existing account if any.
def lookup(self): """ Lookup existing account, if any. """ assert not self.is_existing try: a = SocialAccount.objects.get(provider=self.account.provider, uid=self.account.uid) # Update account a.extra_d...
Instantiates and populates a SocialLogin model based on the data retrieved in response. The method does NOT save the model to the DB.
def sociallogin_from_response(self, request, response): """ Instantiates and populates a `SocialLogin` model based on the data retrieved in `response`. The method does NOT save the model to the DB. Data for `SocialLogin` will be extracted from `response` with the help of...
Extract fields from a basic user query.
def extract_common_fields(self, data): """Extract fields from a basic user query.""" email = None for curr_email in data.get("emails", []): email = email or curr_email.get("email") if curr_email.get("verified", False) and \ curr_email.get("primary", Fa...
Arguments: request - The get request to the callback URL/ accounts/ dataporten/ login/ callback. app - The corresponding SocialApp model instance token - A token object with access token given in token. token Returns: Should return a dict with user information intended for parsing by the methods of the DataportenProvid...
def complete_login(self, request, app, token, **kwargs): ''' Arguments: request - The get request to the callback URL /accounts/dataporten/login/callback. app - The corresponding SocialApp model instance token - A token object with access token...
View to handle final steps of OAuth based authentication where the user gets redirected back to from the service provider
def dispatch(self, request): """ View to handle final steps of OAuth based authentication where the user gets redirected back to from the service provider """ login_done_url = reverse(self.adapter.provider_id + "_callback") client = self._get_client(request, login_done_ur...
Simply logging in the user may become a security issue. If you do not take proper care ( e. g. don t purge used email confirmations ) a malicious person that got hold of the link will be able to login over and over again and the user is unable to do anything about it. Even restoring their own mailbox security will not ...
def login_on_confirm(self, confirmation): """ Simply logging in the user may become a security issue. If you do not take proper care (e.g. don't purge used email confirmations), a malicious person that got hold of the link will be able to login over and over again and the user is...
Navigate data a multidimensional array ( list or dictionary ) and returns the object at path.
def extract_from_dict(data, path): """ Navigate `data`, a multidimensional array (list or dictionary), and returns the object at `path`. """ value = data try: for key in path: value = value[key] return value except (KeyError, IndexError, TypeError): return...
{ elements: [ { handle: urn: li: emailAddress: 319371470 handle~: { emailAddress: raymond. penners
def _extract_email(data): """ {'elements': [{'handle': 'urn:li:emailAddress:319371470', 'handle~': {'emailAddress': 'raymond.penners@intenct.nl'}}]} """ ret = '' elements = data.get('elements', []) if len(elements) > 0: ret = elements[0].get('handle~', {}).get('emailAddres...
Obtain a temporary request token to authorize an access token and to sign the request to obtain the access token
def _get_request_token(self): """ Obtain a temporary request token to authorize an access token and to sign the request to obtain the access token """ if self.request_token is None: get_params = {} if self.parameters: get_params.update(self...
Obtain the access token to access private resources at the API endpoint.
def get_access_token(self): """ Obtain the access token to access private resources at the API endpoint. """ if self.access_token is None: request_token = self._get_rt_from_session() oauth = OAuth1( self.consumer_key, client...
Returns a HttpResponseRedirect object to redirect the user to the URL the OAuth provider handles authorization.
def get_redirect(self, authorization_url, extra_params): """ Returns a ``HttpResponseRedirect`` object to redirect the user to the URL the OAuth provider handles authorization. """ request_token = self._get_request_token() params = {'oauth_token': request_token['oauth_tok...
Get the saved access token for private resources from the session.
def _get_at_from_session(self): """ Get the saved access token for private resources from the session. """ try: return self.request.session['oauth_%s_access_token' % get_token_prefix( self.req...
Request a API endpoint at url with params being either the POST or GET data.
def query(self, url, method="GET", params=dict(), headers=dict()): """ Request a API endpoint at ``url`` with ``params`` being either the POST or GET data. """ access_token = self._get_at_from_session() oauth = OAuth1( self.consumer_key, client_sec...
Returns the next URL to redirect to if it was explicitly passed via the request.
def get_next_redirect_url(request, redirect_field_name="next"): """ Returns the next URL to redirect to, if it was explicitly passed via the request. """ redirect_to = get_request_param(request, redirect_field_name) if not get_adapter(request).is_safe_url(redirect_to): redirect_to = None...
Gets or sets ( optional ) user model fields. No - op if fields do not exist.
def user_field(user, field, *args): """ Gets or sets (optional) user model fields. No-op if fields do not exist. """ if not field: return User = get_user_model() try: field_meta = User._meta.get_field(field) max_length = field_meta.max_length except FieldDoesNotExist:...
Keyword arguments:
def perform_login(request, user, email_verification, redirect_url=None, signal_kwargs=None, signup=False): """ Keyword arguments: signup -- Indicates whether or not sending the email is essential (during signup), or if it can be skipped (e.g. in case email verifi...
Takes a list of EmailAddress instances and cleans it up making sure only valid ones remain without multiple primaries etc.
def cleanup_email_addresses(request, addresses): """ Takes a list of EmailAddress instances and cleans it up, making sure only valid ones remain, without multiple primaries etc. Order is important: e.g. if multiple primary e-mail addresses exist, the first one encountered will be kept as primary. ...
Creates proper EmailAddress for the user that was just signed up. Only sets up doesn t do any other handling such as sending out email confirmation mails etc.
def setup_user_email(request, user, addresses): """ Creates proper EmailAddress for the user that was just signed up. Only sets up, doesn't do any other handling such as sending out email confirmation mails etc. """ from .models import EmailAddress assert not EmailAddress.objects.filter(use...
E - mail verification mails are sent: a ) Explicitly: when a user signs up b ) Implicitly: when a user attempts to log in using an unverified e - mail while EMAIL_VERIFICATION is mandatory.
def send_email_confirmation(request, user, signup=False): """ E-mail verification mails are sent: a) Explicitly: when a user signs up b) Implicitly: when a user attempts to log in using an unverified e-mail while EMAIL_VERIFICATION is mandatory. Especially in case of b), we want to limit the nu...