text
stringlengths
81
112k
Method used internally to retrieve submitted data. After calling this sets `form` and `files` on the request object to multi dicts filled with the incoming form data. As a matter of fact the input stream will be empty afterwards. You can also call this method to force the parsing of t...
Closes associated resources of this request object. This closes all file handles explicitly. You can also use the request object in a with statement which will automatically close it. .. versionadded:: 0.9 def close(self): """Closes associated resources of this request object. This ...
A :class:`werkzeug.datastructures.CombinedMultiDict` that combines :attr:`args` and :attr:`form`. def values(self): """A :class:`werkzeug.datastructures.CombinedMultiDict` that combines :attr:`args` and :attr:`form`.""" args = [] for d in self.args, self.form: if not...
A :class:`dict` with the contents of all cookies transmitted with the request. def cookies(self): """A :class:`dict` with the contents of all cookies transmitted with the request.""" return parse_cookie( self.environ, self.charset, self.encoding_error...
Requested path as unicode. This works a bit like the regular path info in the WSGI environment but will always include a leading slash, even if the URL root is accessed. def path(self): """Requested path as unicode. This works a bit like the regular path info in the WSGI environment b...
Requested path as unicode, including the query string. def full_path(self): """Requested path as unicode, including the query string.""" return self.path + u"?" + to_unicode(self.query_string, self.url_charset)
The root path of the script without the trailing slash. def script_root(self): """The root path of the script without the trailing slash.""" raw_path = wsgi_decoding_dance( self.environ.get("SCRIPT_NAME") or "", self.charset, self.encoding_errors ) return raw_path.rstrip("/"...
Like :attr:`url` but without the querystring See also: :attr:`trusted_hosts`. def base_url(self): """Like :attr:`url` but without the querystring See also: :attr:`trusted_hosts`. """ return get_current_url( self.environ, strip_querystring=True, trusted_hosts=self.tru...
Just the host with scheme as IRI. See also: :attr:`trusted_hosts`. def host_url(self): """Just the host with scheme as IRI. See also: :attr:`trusted_hosts`. """ return get_current_url( self.environ, host_only=True, trusted_hosts=self.trusted_hosts )
If a forwarded header exists this is a list of all ip addresses from the client ip to the last proxy server. def access_route(self): """If a forwarded header exists this is a list of all ip addresses from the client ip to the last proxy server. """ if "HTTP_X_FORWARDED_FOR" in s...
Displays the page the user requests. def on_show(request, page_name): """Displays the page the user requests.""" revision_id = request.args.get("rev", type=int) query = RevisionedPage.query.filter_by(name=page_name) if revision_id: query = query.filter_by(revision_id=revision_id) revisi...
Edit the current revision of a page. def on_edit(request, page_name): """Edit the current revision of a page.""" change_note = error = "" revision = ( Revision.query.filter( (Page.name == page_name) & (Page.page_id == Revision.page_id) ) .order_by(Revision.revision_id.de...
Show the list of recent changes. def on_log(request, page_name): """Show the list of recent changes.""" page = Page.query.filter_by(name=page_name).first() if page is None: return page_missing(request, page_name, False) return Response(generate_template("action_log.html", page=page))
Show the diff between two revisions. def on_diff(request, page_name): """Show the diff between two revisions.""" old = request.args.get("old", type=int) new = request.args.get("new", type=int) error = "" diff = page = old_rev = new_rev = None if not (old and new): error = "No revisions...
Revert an old revision. def on_revert(request, page_name): """Revert an old revision.""" rev_id = request.args.get("rev", type=int) old_revision = page = None error = "No such revision" if request.method == "POST" and request.form.get("cancel"): return redirect(href(page_name)) if re...
Displayed if page or revision does not exist. def page_missing(request, page_name, revision_requested, protected=False): """Displayed if page or revision does not exist.""" return Response( generate_template( "page_missing.html", page_name=page_name, revision_request...
Start a new interactive python session. def shell(no_ipython): """Start a new interactive python session.""" banner = "Interactive Werkzeug Shell" namespace = make_shell() if not no_ipython: try: try: from IPython.frontend.terminal.embed import InteractiveShellEmbed ...
Get fields from a class. If ordered=True, fields will sorted by creation index. :param attrs: Mapping of class attributes :param type field_class: Base field class :param bool pop: Remove matching fields def _get_fields(attrs, field_class, pop=False, ordered=False): """Get fields from a class. If orde...
Collect fields from a class, following its method resolution order. The class itself is excluded from the search; only its parents are checked. Get fields from ``_declared_fields`` if available, else use ``__dict__``. :param type klass: Class whose fields to retrieve :param type field_class: Base field...
Add in the decorated processors By doing this after constructing the class, we let standard inheritance do all the hard work. def resolve_hooks(self): """Add in the decorated processors By doing this after constructing the class, we let standard inheritance do all the hard wor...
Call ``getter_func`` with ``data`` as its argument, and store any `ValidationErrors`. :param callable getter_func: Function for getting the serialized/deserialized value from ``data``. :param data: The data passed to ``getter_func``. :param str field_name: Field name. :param...
Takes raw data (a dict, list, or other object) and a dict of fields to output and serializes the data based on those fields. :param obj: The actual object(s) from which the fields are taken from :param dict fields_dict: Mapping of field names to :class:`Field` objects. :param ErrorStore...
Serialize an object to native Python data types according to this Schema's fields. :param obj: The object to serialize. :param bool many: Whether to serialize `obj` as a collection. If `None`, the value for `self.many` is used. :return: A dict of serialized data :rty...
Same as :meth:`dump`, except return a JSON-encoded string. :param obj: The object to serialize. :param bool many: Whether to serialize `obj` as a collection. If `None`, the value for `self.many` is used. :return: A ``json`` string :rtype: str .. versionadded:: 1.0.0...
Deserialize ``data`` based on the schema defined by ``fields_dict``. :param dict data: The data to deserialize. :param dict fields_dict: Mapping of field names to :class:`Field` objects. :param ErrorStore error_store: Structure to store errors. :param bool many: Set to `True` if ``data`...
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` is used. :param bool|tuple partial: Whether to ignore missing f...
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 `None`, the value for `self.many` is used. :param bool|tuple partial: Whether to ignore mi...
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` is used. :param bool|tuple partial: Whether to ignore m...
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 value for `self.many` is used. :param bool|tuple partial: Whether to validate required fields. If its value is...
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...
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] # Partitio...
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()) ...
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``. def _bind_field(self, field_name, field_obj): """Bind field to the schema, setting any necessary ...
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 may be a collection) and the value for ``many`` is passed. If ``pass_original=True``, the original data (before u...
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 the Schema. If ``pass_many=True``, the raw data (which may be a col...
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 Schema. If ``pass_many=True``, the raw data (which may be a coll...
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 bound. def set_hook(fn, key, **kwargs): ...
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 former case, it must be a one-argument c...
Deeply merge two error messages. The format of ``errors1`` and ``errors2`` matches the ``message`` parameter of :exc:`marshmallow.exceptions.ValidationError`. def merge_errors(errors1, errors2): """Deeply merge two error messages. The format of ``errors1`` and ``errors2`` matches the ``message`` ...
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) # Registry: # { # ...
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. def get_class(classname, all=False): """Retrieve a class from the registry. :raises: marshmallow.exceptions.RegistryError if th...
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 retrieve the value of `attr` from the object `obj`. Defaults to `marsh...
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 validato...
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 hasat...
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. :param callable accessor: Function used to pull values from ``obj``. ...
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 kwargs': Field-specific keyword arguments. :raise ValidationError: If...
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. def _bind_to_schema(self, field_name, schema): """Update field with values from its ...
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 ...
The nested Schema object. .. versionchanged:: 1.0.0 Renamed from `serializer` to `schema` def schema(self): """The nested Schema object. .. versionchanged:: 1.0.0 Renamed from `serializer` to `schema` """ if not self.__schema: # Inherit cont...
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 ``partial`` parameter def _deserialize(self, value, attr, data, partial=None...
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: ...
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: ...
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, V...
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) ...
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 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 o...
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()] mon...
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 08:23:45 -0600" def rfcformat(dt, localtime...
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: ...
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 def from_rfc(datestring, use_dateutil=True): """Parse a RFC822-formatted datetime string and return...
Parse an ISO8601-formatted datetime string and return a datetime object. Use dateutil's parser if possible and return a timezone-aware datetime. def from_iso_datetime(datetimestring, use_dateutil=True): """Parse an ISO8601-formatted datetime string and return a datetime object. Use dateutil's parser if p...
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 ISO86...
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}} def set_value(dct, key, value): """Set a value in a dict. If `key` contains...
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``. def get_func_args(func): """Given a callable, return a tuple of argument names. Handles `functools.partial...
Return a Schema instance from a Schema class or instance. :param type|Schema cls_or_instance: Marshmallow 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 ins...
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 ...
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: 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 not do this and simply returned...
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 = '' ...
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, f...
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....
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_U...
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...
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 ...
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. ...
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_set...
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 t...
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. Note that if you have architected your system such that email confirmations are sent outside of the request context `request` can be `None` here. def get_email_confirmation_url(self, request, emailconfirmation): """Constructs the emai...
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) Authenti...
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'), ...
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 c...
{% 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.s...
{% 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 def get_social_accounts(user): """ {% get_social_accounts u...
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.u...
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 represents a suggested User instance that represents the social user that is in the process of being logged in. The User...
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_authen...
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 w...
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 complaini...
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 compatibility with subclasses not overriding field_order. ...
request.build_absolute_uri() helper Like request.build_absolute_uri, but gracefully handling the case where request is None. def build_absolute_uri(request, location, protocol=None): """request.build_absolute_uri() helper Like request.build_absolute_uri, but gracefully handling the case where req...
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, how to put in a custom signup form? Which...
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.AUTHENTICAT...
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...
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....
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_s...
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)' % ( ...