text
stringlengths
81
112k
Using the mimetypes library, guess the mimetype and encoding for a given *filename*. If the mimetype cannot be guessed, *fallback* is assumed instead. :param filename: Filename- can be absolute path. :param fallback: A fallback mimetype. def guess(filename, fallback='application/octet-stream'): ""...
Given an iterable of addresses or name-address tuples *addrs*, return a header value that joins all of them together with a space and a comma. def format_addresses(addrs): """ Given an iterable of addresses or name-address tuples *addrs*, return a header value that joins all of them together wi...
Given an email address *addr*, try to encode it with ASCII. If it's not possible, encode the *local-part* with the *encoding* and the *domain* with IDNA. The result is a unicode string with the domain encoded as idna. def stringify_address(addr, encoding='utf-8'): """ Given an email addres...
Creates a Collection object with a HTML *content*, and *attachments*. :param content: HTML content. :param encoding: Encoding of the email. :param attachments: List of filenames to attach to the email. def email(sender=None, receivers=(), cc=(), bcc=(), subject=None, content=None, en...
Creates a Postman object with TLS and Auth middleware. TLS is placed before authentication because usually authentication happens and is accepted only after TLS is enabled. :param auth: Tuple of (username, password) to be used to ``login`` to the server. :param force_tls: Whether TLS should...
Returns the finalised mime object, after applying the internal headers. Usually this is not to be overriden. def mime(self): """ Returns the finalised mime object, after applying the internal headers. Usually this is not to be overriden. """ mime = self.m...
Send an *envelope* which may be an envelope or an enclosure-like object, see :class:`~mailthon.enclosure.Enclosure` and :class:`~mailthon.envelope.Envelope`, and returns a :class:`~mailthon.response.SendmailResponse` object. def send(self, envelope): """ Send an ...
A context manager that returns a connection to the server using some *session*. def connection(self): """ A context manager that returns a connection to the server using some *session*. """ conn = self.session(**self.options) try: for item in self.mid...
Returns the sender, respecting the Resent-* headers. In any case, prefer Sender over From, meaning that if Sender is present then From is ignored, as per the RFC. def sender(self): """ Returns the sender, respecting the Resent-* headers. In any case, prefer Sender over F...
Returns a list of receivers, obtained from the To, Cc, and Bcc headers, respecting the Resent-* headers if the email was resent. def receivers(self): """ Returns a list of receivers, obtained from the To, Cc, and Bcc headers, respecting the Resent-* headers if the email ...
Prepares a MIME object by applying the headers to the *mime* object. Ignores any Bcc or Resent-Bcc headers. def prepare(self, mime): """ Prepares a MIME object by applying the headers to the *mime* object. Ignores any Bcc or Resent-Bcc headers. """ for ke...
Middleware implementing TLS for SMTP connections. By default this is not forced- TLS is only used if STARTTLS is available. If the *force* parameter is set to True, it will not query the server for TLS features before upgrading to TLS. def tls(force=False): """ Middleware implementing TLS for S...
Middleware implementing authentication via LOGIN. Most of the time this middleware needs to be placed *after* TLS. :param username: Username to login with. :param password: Password of the user. def auth(username, password): """ Middleware implementing authentication via LOGIN. Most of the...
Try to find existing model class named `model_name`. :param model_name: String name of the model class. def get_existing_model(model_name): """ Try to find existing model class named `model_name`. :param model_name: String name of the model class. """ try: model_cls = engine.get_document_...
Create referenced model if it doesn't exist. When preparing a relationship, we check to see if the model that will be referenced already exists. If not, it is created so that it will be possible to use it in a relationship. Thus the first usage of this model in RAML file must provide its schema in POST...
Generate model class. Engine DB field types are determined using `type_fields` and only those types may be used. :param schema: Model schema dict parsed from RAML. :param model_name: String that is used as new model's name. :param raml_resource: Instance of ramlfications.raml.ResourceNode. :pa...
Setup storage/data model and return generated model class. Process follows these steps: * Resource schema is found and restructured by `resource_schema`. * Model class is generated from properties dict using util function `generate_model_cls`. :param raml_resource: Instance of ramlfication...
Generates model name and runs `setup_data_model` to get or generate actual model class. :param raml_resource: Instance of ramlfications.raml.ResourceNode. def handle_model_generation(config, raml_resource): """ Generates model name and runs `setup_data_model` to get or generate actual model class. ...
Set up model event subscribers. :param config: Pyramid Configurator instance. :param model_cls: Model class for which handlers should be connected. :param schema: Dict of model JSON schema. def setup_model_event_subscribers(config, model_cls, schema): """ Set up model event subscribers. :param co...
Set up model fields' processors. :param config: Pyramid Configurator instance. :param model_cls: Model class for field of which processors should be set up. :param schema: Dict of model JSON schema. def setup_fields_processors(config, model_cls, schema): """ Set up model fields' processors. ...
Setup Pyramid AuthTktAuthenticationPolicy. Notes: * Initial `secret` params value is considered to be a name of config param that represents a cookie name. * `auth_model.get_groups_by_userid` is used as a `callback`. * Also connects basic routes to perform authentication actions. :pa...
Setup `nefertari.ApiKeyAuthenticationPolicy`. Notes: * User may provide model name in :params['user_model']: do define the name of the user model. * `auth_model.get_groups_by_token` is used to perform username and token check * `auth_model.get_token_credentials` is used to get use...
Setup authentication, authorization policies. Performs basic validation to check all the required values are present and performs authentication, authorization policies generation using generator functions from `AUTHENTICATION_POLICIES`. :param config: Pyramid Configurator instance. :param raml_ro...
Define and return AuthUser model using nefertari base classes def get_authuser_model(): """ Define and return AuthUser model using nefertari base classes """ from nefertari.authentication.models import AuthUserMixin from nefertari import engine class AuthUser(AuthUserMixin, engine.BaseDocument): ...
Validate :perms: contains valid permissions. :param perms: List of permission names or ALL_PERMISSIONS. def validate_permissions(perms): """ Validate :perms: contains valid permissions. :param perms: List of permission names or ALL_PERMISSIONS. """ if not isinstance(perms, (list, tuple)): ...
Parse permissions ("perms") which are either exact permission names or the keyword 'all'. :param perms: List or comma-separated string of nefertari permission names, or 'all' def parse_permissions(perms): """ Parse permissions ("perms") which are either exact permission names or the keyword 'a...
Parse raw string :acl_string: of RAML-defined ACLs. If :acl_string: is blank or None, all permissions are given. Values of ACL action and principal are parsed using `actions` and `special_principals` maps and are looked up after `strip()` and `lower()`. ACEs in :acl_string: may be separated by new...
Generate an ACL. Generated ACL class has a `item_model` attribute set to :model_cls:. ACLs used for collection and item access control are generated from a first security scheme with type `x-ACL`. If :raml_resource: has no x-ACL security schemes defined then ALLOW_ALL ACL is used. If the `...
Iterate over ACEs from :acl: and apply callable principals if any. Principals are passed 3 arguments on call: :ace: Single ACE object that looks like (action, callable, permission or [permission]) :request: Current request object :obj: Object instance...
Objectify ACL if ES is used or call item.get_acl() if db is used. def item_acl(self, item): """ Objectify ACL if ES is used or call item.get_acl() if db is used. """ if self.es_based: from nefertari_guards.elasticsearch import get_es_item_acl return get_e...
Override to support ACL filtering. To do so: passes `self.request` to `get_item` and uses `ACLFilterES`. def getitem_es(self, key): """ Override to support ACL filtering. To do so: passes `self.request` to `get_item` and uses `ACLFilterES`. """ from nefertari_g...
Restructure `raml_schema` to a dictionary that has 'properties' as well as other schema keys/values. The resulting dictionary looks like this:: { "properties": { "field1": { "required": boolean, "type": ..., ...more field options ...
Generate model name. :param raml_resource: Instance of ramlfications.raml.ResourceNode. def generate_model_name(raml_resource): """ Generate model name. :param raml_resource: Instance of ramlfications.raml.ResourceNode. """ resource_uri = get_resource_uri(raml_resource).strip('/') resource_ur...
Generate a dynamic part for a resource :raml_resource:. A dynamic part is generated using 2 parts: :route_name: of the resource and the dynamic part of first dynamic child resources. If :raml_resource: has no dynamic child resources, 'id' is used as the 2nd part. E.g. if your dynamic part on route ...
Extract dynamic url part from :uri: string. :param uri: URI string that may contain dynamic part. def extract_dynamic_part(uri): """ Extract dynamic url part from :uri: string. :param uri: URI string that may contain dynamic part. """ for part in uri.split('/'): part = part.strip() ...
Generate view method names needed for `raml_resource` view. Collects HTTP method names from resource siblings and dynamic children if exist. Collected methods are then translated to `nefertari.view.BaseView` method names, each of which is used to process a particular HTTP method request. Maps of ...
Get schema properties of RAML resource :raml_resource:. Must be called with RAML resource that defines body schema. First body that defines schema is used. Schema is converted on return using 'convert_schema'. :param raml_resource: Instance of ramlfications.raml.ResourceNode of POST method. d...
Get static parent resource of :raml_resource: with HTTP method :method:. :param raml_resource:Instance of ramlfications.raml.ResourceNode. :param method: HTTP method name which matching static resource must have. def get_static_parent(raml_resource, method=None): """ Get static parent resource...
Determine if :raml_resource: is an attribute subresource. :param raml_resource: Instance of ramlfications.raml.ResourceNode. :param route_name: Name of the :raml_resource:. def attr_subresource(raml_resource, route_name): """ Determine if :raml_resource: is an attribute subresource. :param raml_resou...
Determine if :raml_resource: is a singular subresource. :param raml_resource: Instance of ramlfications.raml.ResourceNode. :param route_name: Name of the :raml_resource:. def singular_subresource(raml_resource, route_name): """ Determine if :raml_resource: is a singular subresource. :param raml_resou...
Determine whether :tag: is a valid callable string tag. String is assumed to be valid callable if it starts with '{{' and ends with '}}'. :param tag: String name of tag. def is_callable_tag(tag): """ Determine whether :tag: is a valid callable string tag. String is assumed to be valid callable i...
Resolve string :callable_name: to a callable. :param callable_name: String representing callable name as registered in ramses registry or dotted import path of callable. Can be wrapped in double curly brackets, e.g. '{{my_callable}}'. def resolve_to_callable(callable_name): """ Resolve string ...
Get siblings of :raml_resource:. :param raml_resource: Instance of ramlfications.raml.ResourceNode. def get_resource_siblings(raml_resource): """ Get siblings of :raml_resource:. :param raml_resource: Instance of ramlfications.raml.ResourceNode. """ path = raml_resource.path return [res for r...
Get children of :raml_resource:. :param raml_resource: Instance of ramlfications.raml.ResourceNode. def get_resource_children(raml_resource): """ Get children of :raml_resource:. :param raml_resource: Instance of ramlfications.raml.ResourceNode. """ path = raml_resource.path return [res for r...
Prepare map of event subscribers. * Extends copies of BEFORE_EVENTS and AFTER_EVENTS maps with 'set' action. * Returns map of {before/after: {action: event class(es)}} def get_events_map(): """ Prepare map of event subscribers. * Extends copies of BEFORE_EVENTS and AFTER_EVENTS maps with ...
Patches view_cls.Model with model_cls. :param view_cls: View class "Model" param of which should be patched :param model_cls: Model class which should be used to patch view_cls.Model def patch_view_model(view_cls, model_cls): """ Patches view_cls.Model with model_cls. :param view_cls:...
Get route name from RAML resource URI. :param resource_uri: String representing RAML resource URI. :returns string: String with route name, which is :resource_uri: stripped of non-word characters. def get_route_name(resource_uri): """ Get route name from RAML resource URI. :param resource_uri...
Perform complete one resource configuration process This function generates: ACL, view, route, resource, database model for a given `raml_resource`. New nefertari resource is attached to `parent_resource` class which is an instance of `nefertari.resource.Resource`. Things to consider: * Top-...
Handle server generation process. :param raml_root: Instance of ramlfications.raml.RootNode. :param config: Pyramid Configurator instance. def generate_server(raml_root, config): """ Handle server generation process. :param raml_root: Instance of ramlfications.raml.RootNode. :param config: Pyrami...
Generate model for each resource in :raml_resources: The DB model name is generated using singular titled version of current resource's url. E.g. for resource under url '/stories', model with name 'Story' will be generated. :param config: Pyramid Configurator instance. :param raml_resources: List ...
Generate REST view for a model class. :param model_cls: Generated DB model class. :param attr: List of strings that represent names of view methods, new generated view should support. Not supported methods are replaced with property that raises AttributeError to display MethodNotAllowed ...
Set object ACL on creation if not already present. def set_object_acl(self, obj): """ Set object ACL on creation if not already present. """ if not obj._acl: from nefertari_guards import engine as guards_engine acl = self._factory(self.request).generate_item_acl(obj) ...
Resolve :kwargs: like `story_id: 1` to the form of `id: 1`. def resolve_kw(self, kwargs): """ Resolve :kwargs: like `story_id: 1` to the form of `id: 1`. """ resolved = {} for key, value in kwargs.items(): split = key.split('_', 1) if len(split) > 1: ...
Get location of the `obj` Arguments: :obj: self.Model instance. def _location(self, obj): """ Get location of the `obj` Arguments: :obj: self.Model instance. """ field_name = self.clean_id_name return self.request.route_url( self._re...
Get queryset of parent view. Generated queryset is used to run queries in the current level view. def _parent_queryset(self): """ Get queryset of parent view. Generated queryset is used to run queries in the current level view. """ parent = self._resource.parent if has...
Get objects collection taking into account generated queryset of parent view. This method allows working with nested resources properly. Thus a queryset returned by this method will be a subset of its parent view's queryset, thus filtering out objects that don't belong to the pa...
Get collection item taking into account generated queryset of parent view. This method allows working with nested resources properly. Thus an item returned by this method will belong to its parent view's queryset, thus filtering out objects that don't belong to the parent object. ...
Reload `self.context` object into a DB or ES object. A reload is performed by getting the object ID from :kwargs: and then getting a context key item from the new instance of `self._factory` which is an ACL class used by the current view. Arguments: :es_based: Boolean. Whet...
Get queryset (list of object IDs) of parent view. The generated queryset is used to run queries in the current level's view. def _parent_queryset_es(self): """ Get queryset (list of object IDs) of parent view. The generated queryset is used to run queries in the current level's ...
Return IDs of :objects: if they are not IDs already. def get_es_object_ids(self, objects): """ Return IDs of :objects: if they are not IDs already. """ id_field = self.clean_id_name ids = [getattr(obj, id_field, obj) for obj in objects] return list(set(str(id_) for id_ in ids))
Get ES objects collection taking into account the generated queryset of parent view. This method allows working with nested resources properly. Thus a queryset returned by this method will be a subset of its parent view's queryset, thus filtering out objects that don't belong to the par...
Get ES collection item taking into account generated queryset of parent view. This method allows working with nested resources properly. Thus an item returned by this method will belong to its parent view's queryset, thus filtering out objects that don't belong to the parent object. ...
Explicitly reload context with DB usage to get access to complete DB object. def update(self, **kwargs): """ Explicitly reload context with DB usage to get access to complete DB object. """ self.reload_context(es_based=False, **kwargs) return super(ESCollectionView, self...
Explicitly reload context with DB usage to get access to complete DB object. def delete(self, **kwargs): """ Explicitly reload context with DB usage to get access to complete DB object. """ self.reload_context(es_based=False, **kwargs) return super(ESCollectionView, self...
Get DB objects collection by first querying ES. def get_dbcollection_with_es(self, **kwargs): """ Get DB objects collection by first querying ES. """ es_objects = self.get_collection_es() db_objects = self.Model.filter_objects(es_objects) return db_objects
Delete multiple objects from collection. First ES is queried, then the results are used to query the DB. This is done to make sure deleted objects are those filtered by ES in the 'index' method (so user deletes what he saw). def delete_many(self, **kwargs): """ Delete multiple objects ...
Update multiple objects from collection. First ES is queried, then the results are used to query DB. This is done to make sure updated objects are those filtered by ES in the 'index' method (so user updates what he saw). def update_many(self, **kwargs): """ Update multiple objects from...
Get value of `self._resource.parent.id_name` from :kwargs: def _get_context_key(self, **kwargs): """ Get value of `self._resource.parent.id_name` from :kwargs: """ return str(kwargs.get(self._resource.parent.id_name))
Reload context on each access. def get_item(self, **kwargs): """ Reload context on each access. """ self.reload_context(es_based=False, **kwargs) return super(ItemSubresourceBaseView, self).get_item(**kwargs)
Allow this module to be used as sphinx extension. This attaches the Sphinx hooks. :type app: sphinx.application.Sphinx def setup(app): """Allow this module to be used as sphinx extension. This attaches the Sphinx hooks. :type app: sphinx.application.Sphinx """ import sphinxcontrib_django....
Fix the appearance of some classes in autodoc. This avoids query evaluation. def patch_django_for_autodoc(): """Fix the appearance of some classes in autodoc. This avoids query evaluation. """ # Fix Django's manager appearance ManagerDescriptor.__get__ = lambda self, *args, **kwargs: self.man...
Allow this package to be used as Sphinx extension. This is also called from the top-level ``__init__.py``. :type app: sphinx.application.Sphinx def setup(app): """Allow this package to be used as Sphinx extension. This is also called from the top-level ``__init__.py``. :type app: sphinx.applicati...
Hook that tells autodoc to include or exclude certain fields. Sadly, it doesn't give a reference to the parent object, so only the ``name`` can be used for referencing. :type app: sphinx.application.Sphinx :param what: The parent type, ``class`` or ``module`` :type what: str :param name: The n...
Hook that improves the autodoc docstrings for Django models. :type app: sphinx.application.Sphinx :param what: The parent type, ``class`` or ``module`` :type what: str :param name: The dotted path to the child method/attribute. :type name: str :param obj: The Python object that i s being docume...
Improve the documentation of a class. def _improve_class_docs(app, cls, lines): """Improve the documentation of a class.""" if issubclass(cls, models.Model): _add_model_fields_as_params(app, cls, lines) elif issubclass(cls, forms.Form): _add_form_fields(cls, lines)
Improve the documentation of a Django model subclass. This adds all model fields as parameters to the ``__init__()`` method. :type app: sphinx.application.Sphinx :type lines: list def _add_model_fields_as_params(app, obj, lines): """Improve the documentation of a Django model subclass. This adds...
Improve the documentation of a Django Form class. This highlights the available fields in the form. def _add_form_fields(obj, lines): """Improve the documentation of a Django Form class. This highlights the available fields in the form. """ lines.append("**Form fields:**") lines.append("") ...
Improve the documentation of various attributes. This improves the navigation between related objects. :param obj: the instance of the object to document. :param name: full dotted path to the object. :param lines: expected documentation lines. def _improve_attribute_docs(obj, name, lines): """Impr...
Improve the documentation of various methods. :param obj: the instance of the method to document. :param name: full dotted path to the object. :param lines: expected documentation lines. def _improve_method_docs(obj, name, lines): """Improve the documentation of various methods. :param obj: the i...
Returns annotated attribute names :return: List[str] def attr_names(cls) -> List[str]: """ Returns annotated attribute names :return: List[str] """ return [k for k, v in cls.attr_types().items()]
Calculate elliptical Fourier descriptors for a contour. :param numpy.ndarray contour: A contour array of size ``[M x 2]``. :param int order: The order of Fourier coefficients to calculate. :param bool normalize: If the coefficients should be normalized; see references for details. :return: A ``...
Normalizes an array of Fourier coefficients. See [#a]_ and [#b]_ for details. :param numpy.ndarray coeffs: A ``[n x 4]`` Fourier coefficient array. :param bool size_invariant: If size invariance normalizing should be done as well. Default is ``True``. :return: The normalized ``[n x 4]`` Fourie...
Calculate the :math:`A_0` and :math:`C_0` coefficients of the elliptic Fourier series. :param numpy.ndarray contour: A contour array of size ``[M x 2]``. :return: The :math:`A_0` and :math:`C_0` coefficients. :rtype: tuple def calculate_dc_coefficients(contour): """Calculate the :math:`A_0` and :math:...
Plot a ``[2 x (N / 2)]`` grid of successive truncations of the series. .. note:: Requires `matplotlib <http://matplotlib.org/>`_! :param numpy.ndarray coeffs: ``[N x 4]`` Fourier coefficient array. :param list, tuple or numpy.ndarray locus: The :math:`A_0` and :math:`C_0` elliptic locus i...
Error checker for functions returning an integer indicating success (0) / failure (1). Raises a XdoException in case of error, otherwise just returns ``None`` (returning the original code, 0, would be useless anyways..) def _errcheck(result, func, arguments): """ Error checker for functions re...
Generate input mask from bytemask def _gen_input_mask(mask): """Generate input mask from bytemask""" return input_mask( shift=bool(mask & MOD_Shift), lock=bool(mask & MOD_Lock), control=bool(mask & MOD_Control), mod1=bool(mask & MOD_Mod1), mod2=bool(mask & MOD_Mod2), ...
Move the mouse to a specific location. :param x: the target X coordinate on the screen in pixels. :param y: the target Y coordinate on the screen in pixels. :param screen: the screen (number) you want to move on. def move_mouse(self, x, y, screen=0): """ Move the mouse to a spe...
Move the mouse to a specific location relative to the top-left corner of a window. :param x: the target X coordinate on the screen in pixels. :param y: the target Y coordinate on the screen in pixels. def move_mouse_relative_to_window(self, window, x, y): """ Move the mouse to ...
Move the mouse relative to it's current position. :param x: the distance in pixels to move on the X axis. :param y: the distance in pixels to move on the Y axis. def move_mouse_relative(self, x, y): """ Move the mouse relative to it's current position. :param x: the distance i...
Send a mouse press (aka mouse down) for a given button at the current mouse location. :param window: The window you want to send the event to or CURRENTWINDOW :param button: The mouse button. Generally, 1 is left, 2 is middle, 3 is right, 4 is wheel up, 5 is ...
Send a mouse release (aka mouse up) for a given button at the current mouse location. :param window: The window you want to send the event to or CURRENTWINDOW :param button: The mouse button. Generally, 1 is left, 2 is middle, 3 is right, 4 is wheel up, 5 is ...
Get the current mouse location (coordinates and screen number). :return: a namedtuple with ``x``, ``y`` and ``screen_num`` fields def get_mouse_location(self): """ Get the current mouse location (coordinates and screen number). :return: a namedtuple with ``x``, ``y`` and ``screen_num`...
Get the window the mouse is currently over def get_window_at_mouse(self): """ Get the window the mouse is currently over """ window_ret = ctypes.c_ulong(0) _libxdo.xdo_get_window_at_mouse(self._xdo, ctypes.byref(window_ret)) return window_ret.value
Get all mouse location-related data. :return: a namedtuple with ``x``, ``y``, ``screen_num`` and ``window`` fields def get_mouse_location2(self): """ Get all mouse location-related data. :return: a namedtuple with ``x``, ``y``, ``screen_num`` and ``window`` fie...
Wait for the mouse to move from a location. This function will block until the condition has been satisified. :param origin_x: the X position you expect the mouse to move from :param origin_y: the Y position you expect the mouse to move from def wait_for_mouse_move_from(self, origin_x, origin_...
Wait for the mouse to move to a location. This function will block until the condition has been satisified. :param dest_x: the X position you expect the mouse to move to :param dest_y: the Y position you expect the mouse to move to def wait_for_mouse_move_to(self, dest_x, dest_y): """ ...
Send a click for a specific mouse button at the current mouse location. :param window: The window you want to send the event to or CURRENTWINDOW :param button: The mouse button. Generally, 1 is left, 2 is middle, 3 is right, 4 is wheel up, 5 is wheel down. def click...
Send a one or more clicks for a specific mouse button at the current mouse location. :param window: The window you want to send the event to or CURRENTWINDOW :param button: The mouse button. Generally, 1 is left, 2 is middle, 3 is right, 4 is wheel up, 5 is w...
Type a string to the specified window. If you want to send a specific key or key sequence, such as "alt+l", you want instead ``send_keysequence_window(...)``. :param window: The window you want to send keystrokes to or CURRENTWINDOW :param string: The string to ...
Send a keysequence to the specified window. This allows you to send keysequences by symbol name. Any combination of X11 KeySym names separated by '+' are valid. Single KeySym names are valid, too. Examples: "l" "semicolon" "alt+Return" "Alt_L+Tab...