INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Change the name of this domain record
def rename(self, id, name): """ Change the name of this domain record Parameters ---------- id: int domain record id name: str new name of record """ return super(DomainRecords, self).update(id, name=name)[self.singular]
Parameters ---------- type: str { A AAAA CNAME MX TXT SRV NS } name: str Name of the record data: object type - dependent type == A: IPv4 address type == AAAA: IPv6 address type == CNAME: destination host name type == MX: mail host name type == TXT: txt contents type == SRV: target host name to direct requests for the ...
def create(self, type, name=None, data=None, priority=None, port=None, weight=None): """ Parameters ---------- type: str {A, AAAA, CNAME, MX, TXT, SRV, NS} name: str Name of the record data: object, type-dependent type ==...
Retrieve a single domain record given the id
def get(self, id, **kwargs): """ Retrieve a single domain record given the id """ return super(DomainRecords, self).get(id, **kwargs)
Logs the user on to FogBugz.
def logon(self, username, password): """ Logs the user on to FogBugz. Returns None for a successful login. """ if self._token: self.logoff() try: response = self.__makerequest( 'logon', email=username, password=password) ex...
fields is a sequence of ( key value ) elements for regular form fields. files is a sequence of ( filename filehandle ) files to be uploaded returns ( content_type body )
def __encode_multipart_formdata(self, fields, files): """ fields is a sequence of (key, value) elements for regular form fields. files is a sequence of (filename, filehandle) files to be uploaded returns (content_type, body) """ BOUNDARY = _make_boundary() if len...
Chop list_ into n chunks. Returns a list.
def chop(list_, n): "Chop list_ into n chunks. Returns a list." # could look into itertools also, might be implemented there size = len(list_) each = size // n if each == 0: return [list_] chopped = [] for i in range(n): start = i * each end = (i+1) * each if ...
return first droplet
def get_first(): """ return first droplet """ client = po.connect() # this depends on the DIGITALOCEAN_API_KEY envvar all_droplets = client.droplets.list() id = all_droplets[0]['id'] # I'm cheating because I only have one droplet return client.droplets.get(id)
Take a snapshot of a droplet
def take_snapshot(droplet, name): """ Take a snapshot of a droplet Parameters ---------- name: str name for snapshot """ print "powering off" droplet.power_off() droplet.wait() # wait for pending actions to complete print "taking snapshot" droplet.take_snapshot(name)...
Retrieves the allowed operations for this request.
def allowed_operations(self): """Retrieves the allowed operations for this request.""" if self.slug is not None: return self.meta.detail_allowed_operations return self.meta.list_allowed_operations
Assets if the requested operations are allowed in this context.
def assert_operations(self, *args): """Assets if the requested operations are allowed in this context.""" if not set(args).issubset(self.allowed_operations): raise http.exceptions.Forbidden()
Fills the response object from the passed data.
def make_response(self, data=None): """Fills the response object from the passed data.""" if data is not None: # Prepare the data for transmission. data = self.prepare(data) # Encode the data using a desired encoder. self.response.write(data, serialize=Tr...
Processes a GET request.
def get(self, request, response): """Processes a `GET` request.""" # Ensure we're allowed to read the resource. self.assert_operations('read') # Delegate to `read` to retrieve the items. items = self.read() # if self.slug is not None and not items: # # Reque...
Processes a POST request.
def post(self, request, response): """Processes a `POST` request.""" if self.slug is not None: # Don't know what to do an item access. raise http.exceptions.NotImplemented() # Ensure we're allowed to create a resource. self.assert_operations('create') # ...
Processes a PUT request.
def put(self, request, response): """Processes a `PUT` request.""" if self.slug is None: # Mass-PUT is not implemented. raise http.exceptions.NotImplemented() # Check if the resource exists. target = self.read() # Deserialize and clean the incoming objec...
Processes a DELETE request.
def delete(self, request, response): """Processes a `DELETE` request.""" if self.slug is None: # Mass-DELETE is not implemented. raise http.exceptions.NotImplemented() # Ensure we're allowed to destroy a resource. self.assert_operations('destroy') # Dele...
Processes a LINK request.
def link(self, request, response): """Processes a `LINK` request. A `LINK` request is asking to create a relation from the currently represented URI to all of the `Link` request headers. """ from armet.resources.managed.request import read if self.slug is None: ...
Creates a base Django project
def create_project(self): ''' Creates a base Django project ''' if os.path.exists(self._py): prj_dir = os.path.join(self._app_dir, self._project_name) if os.path.exists(prj_dir): if self._force: logging.warn('Removing existing p...
Helper function that performs an ilike query if a string value is passed otherwise the normal default operation.
def ilike_helper(default): """Helper function that performs an `ilike` query if a string value is passed, otherwise the normal default operation.""" @functools.wraps(default) def wrapped(x, y): # String values should use ILIKE queries. if isinstance(y, six.string_types) and not isinstanc...
Parse the querystring into a normalized form.
def parse(text, encoding='utf8'): """Parse the querystring into a normalized form.""" # Decode the text if we got bytes. if isinstance(text, six.binary_type): text = text.decode(encoding) return Query(text, split_segments(text))
Return objects representing segments.
def split_segments(text, closing_paren=False): """Return objects representing segments.""" buf = StringIO() # The segments we're building, and the combinators used to combine them. # Note that after this is complete, this should be true: # len(segments) == len(combinators) + 1 # Thus we can und...
Takes a key of type ( foo: bar ) and returns either the key and the directive or the key and None ( for no directive. )
def parse_directive(key): """ Takes a key of type (foo:bar) and returns either the key and the directive, or the key and None (for no directive.) """ if constants.DIRECTIVE in key: return key.split(constants.DIRECTIVE, 1) else: return key, None
we expect foo = bar
def parse_segment(text): "we expect foo=bar" if not len(text): return NoopQuerySegment() q = QuerySegment() # First we need to split the segment into key/value pairs. This is done # by attempting to split the sequence for each equality comparison. Then # discard any that did not spl...
Set the value of this attribute for the passed object.
def set(self, target, value): """Set the value of this attribute for the passed object. """ if not self._set: return if self.path is None: # There is no path defined on this resource. # We can do no magic to set the value. self.set = lamb...
Consumes set specifiers as text and forms a generator to retrieve the requested ranges.
def parse(specifiers): """ Consumes set specifiers as text and forms a generator to retrieve the requested ranges. @param[in] specifiers Expected syntax is from the byte-range-specifier ABNF found in the [RFC 2616]; eg. 15-17,151,-16,26-278,15 @returns Consecutive tuples th...
Paginate an iterable during a request.
def paginate(request, response, items): """Paginate an iterable during a request. Magically splicling an iterable in our supported ORMs allows LIMIT and OFFSET queries. We should probably delegate this to the ORM or something in the future. """ # TODO: support dynamic rangewords and page length...
Decorate test methods with this if you don t require strict index checking
def indexesOptional(f): """Decorate test methods with this if you don't require strict index checking""" stack = inspect.stack() _NO_INDEX_CHECK_NEEDED.add('%s.%s.%s' % (f.__module__, stack[1][3], f.__name__)) del stack return f
Read and return the request data.
def read(self, deserialize=False, format=None): """Read and return the request data. @param[in] deserialize True to deserialize the resultant text using a determiend format or the passed format. @param[in] format A specific format to deserialize in; if provi...
Updates the active resource configuration to the passed keyword arguments.
def use(**kwargs): """ Updates the active resource configuration to the passed keyword arguments. Invoking this method without passing arguments will just return the active resource configuration. @returns The previous configuration. """ config = dict(use.config) use.config...
This decorator wraps descriptor methods with a new method that tries to delegate to a function of the same name defined on the owner instance for convenience for dispatcher clients.
def try_delegation(method): '''This decorator wraps descriptor methods with a new method that tries to delegate to a function of the same name defined on the owner instance for convenience for dispatcher clients. ''' @functools.wraps(method) def delegator(self, *args, **kwargs): if self....
Given a single decorated handler function prepare append desired data to self. registry.
def register(self, method, args, kwargs): '''Given a single decorated handler function, prepare, append desired data to self.registry. ''' invoc = self.dump_invoc(*args, **kwargs) self.registry.append((invoc, method.__name__))
Find all method names this input dispatches to. This method can accept * args ** kwargs but it s the gen_dispatch method s job of passing specific args to handler methods.
def gen_methods(self, *args, **kwargs): '''Find all method names this input dispatches to. This method can accept *args, **kwargs, but it's the gen_dispatch method's job of passing specific args to handler methods. ''' dispatched = False for invoc, methodname in self.regi...
Find the first method this input dispatches to.
def get_method(self, *args, **kwargs): '''Find the first method this input dispatches to. ''' for method in self.gen_methods(*args, **kwargs): return method msg = 'No method was found for %r on %r.' raise self.DispatchError(msg % ((args, kwargs), self.inst))
Find and evaluate/ return the first method this input dispatches to.
def dispatch(self, *args, **kwargs): '''Find and evaluate/return the first method this input dispatches to. ''' for result in self.gen_dispatch(*args, **kwargs): return result
Find and evaluate/ yield every method this input dispatches to.
def gen_dispatch(self, *args, **kwargs): '''Find and evaluate/yield every method this input dispatches to. ''' dispatched = False for method_data in self.gen_methods(*args, **kwargs): dispatched = True result = self.apply_handler(method_data, *args, **kwargs) ...
Given a node return the string to use in computing the matching visitor methodname. Can also be a generator of strings.
def gen_method_keys(self, *args, **kwargs): '''Given a node, return the string to use in computing the matching visitor methodname. Can also be a generator of strings. ''' token = args[0] for mro_type in type(token).__mro__[:-1]: name = mro_type.__name__ y...
Find all method names this input dispatches to.
def gen_methods(self, *args, **kwargs): '''Find all method names this input dispatches to. ''' token = args[0] inst = self.inst prefix = self._method_prefix for method_key in self.gen_method_keys(*args, **kwargs): method = getattr(inst, prefix + method_key, No...
Call the dispatched function optionally with other data stored/ created during. register and. prepare. Assume the arguments passed in by the dispathcer are the only ones required.
def apply_handler(self, method_data, *args, **kwargs): '''Call the dispatched function, optionally with other data stored/created during .register and .prepare. Assume the arguments passed in by the dispathcer are the only ones required. ''' if isinstance(method_data, tuple): ...
Parse string to create an instance
def parse(cls, s, required=False): """ Parse string to create an instance :param str s: String with requirement to parse :param bool required: Is this requirement required to be fulfilled? If not, then it is a filter. """ req = pkg_resources.Requirement.parse(s) ...
Add requirements to be managed
def add(self, requirements, required=None): """ Add requirements to be managed :param list/Requirement requirements: List of :class:`BumpRequirement` or :class:`pkg_resources.Requirement` :param bool required: Set required flag for each requirement if provided. """ if is...
Check off requirements that are met by name/ version.
def check(self, context, version=None): """ Check off requirements that are met by name/version. :param str|Bump|Requirement context: Either package name, requirement string, :class:`Bump`, :class:`BumpRequirement`, or ...
Check if requirement is already satisfied by what was previously checked
def satisfied_by_checked(self, req): """ Check if requirement is already satisfied by what was previously checked :param Requirement req: Requirement to check """ req_man = RequirementsManager([req]) return any(req_man.check(*checked) for checked in self.checked)
Create an instance from: class: pkg_resources. Requirement instance
def from_requirement(cls, req, changes=None): """ Create an instance from :class:`pkg_resources.Requirement` instance """ return cls(req.project_name, req.specs and ''.join(req.specs[0]) or '', changes=changes)
Convert back to a: class: pkg_resources. Requirement instance
def as_requirement(self): """ Convert back to a :class:`pkg_resources.Requirement` instance """ if self.new_version: return pkg_resources.Requirement.parse(self.name + ''.join(self.new_version)) else: return pkg_resources.Requirement.parse(self.name)
Add new requirements that must be fulfilled for this bump to occur
def require(self, req): """ Add new requirements that must be fulfilled for this bump to occur """ reqs = req if isinstance(req, list) else [req] for req in reqs: if not isinstance(req, BumpRequirement): req = BumpRequirement(req) req.required = True ...
Parse changes for requirements
def requirements_for_changes(self, changes): """ Parse changes for requirements :param list changes: """ requirements = [] reqs_set = set() if isinstance(changes, str): changes = changes.split('\n') if not changes or changes[0].startswith('-...
List of changes for package name from current_version to new_version in descending order. If current version is higher than new version ( downgrade ) then a minus sign will be prefixed to each change.
def package_changes(self, name, current_version, new_version): """ List of changes for package name from current_version to new_version, in descending order. If current version is higher than new version (downgrade), then a minus sign will be prefixed to each change. """ if p...
Bump an existing requirement to the desired requirement if any. Subclass can override this _bump method to change how each requirement is bumped.
def _bump(self, existing_req=None, bump_reqs=None): """ Bump an existing requirement to the desired requirement if any. Subclass can override this `_bump` method to change how each requirement is bumped. BR = Bump to Requested Version BL = Bump to Latest Version ...
Bump dependencies using given requirements.
def bump(self, bump_reqs=None, **kwargs): """ Bump dependencies using given requirements. :param RequirementsManager bump_reqs: Bump requirements manager :param dict kwargs: Additional args from argparse. Some bumpers accept user options, and some not. :return: List of :...
Restore content in target file to be before any changes
def reverse(self): """ Restore content in target file to be before any changes """ if self._original_target_content: with open(self.target, 'w') as fp: fp.write(self._original_target_content)
Transforms the object into an acceptable format for transmission.
def serialize(self, data=None): """ Transforms the object into an acceptable format for transmission. @throws ValueError To indicate this serializer does not support the encoding of the specified object. """ if data is not None and self.response is not No...
Extends a collection with a value.
def cons(collection, value): """Extends a collection with a value.""" if isinstance(value, collections.Mapping): if collection is None: collection = {} collection.update(**value) elif isinstance(value, six.string_types): if collection is None: collection = []...
Merges a named option collection.
def _merge(options, name, bases, default=None): """Merges a named option collection.""" result = None for base in bases: if base is None: continue value = getattr(base, name, None) if value is None: continue result = utils.cons(result, value) va...
Parse string requirements into list of: class: pkg_resources. Requirement instances
def parse_requirements(requirements, in_file=None): """ Parse string requirements into list of :class:`pkg_resources.Requirement` instances :param str requirements: Requirements text to parse :param str in_file: File the requirements came from :return: List of requirements :raises Val...
All package info for given package
def package_info(cls, package): """ All package info for given package """ if package not in cls.package_info_cache: package_json_url = 'https://pypi.python.org/pypi/%s/json' % package try: logging.getLogger('requests').setLevel(logging.WARN) res...
All versions for package
def all_package_versions(package): """ All versions for package """ info = PyPI.package_info(package) return info and sorted(info['releases'].keys(), key=lambda x: x.split(), reverse=True) or []
Insert a value at the passed index in the named header.
def insert(self, name, index, value): """Insert a value at the passed index in the named header.""" return self._sequence[name].insert(index, value)
Flush and close the stream.
def close(self): """Flush and close the stream. This is called automatically by the base resource on resources unless the resource is operating asynchronously; in that case, this method MUST be called in order to signal the end of the request. If not the request will simply hang...
Writes the given chunk to the output buffer.
def write(self, chunk, serialize=False, format=None): """Writes the given chunk to the output buffer. @param[in] chunk Either a byte array, a unicode string, or a generator. If `chunk` is a generator then calling `self.write(<generator>)` is equivalent to: ...
Serializes the data into this response using a serializer.
def serialize(self, data, format=None): """Serializes the data into this response using a serializer. @param[in] data The data to be serialized. @param[in] format A specific format to serialize in; if provided, no detection is done. If not provided, the acce...
Flush the write buffers of the stream.
def flush(self): """Flush the write buffers of the stream. This results in writing the current contents of the write buffer to the transport layer, initiating the HTTP/1.1 response. This initiates a streaming response. If the `Content-Length` header is not given then the chunked...
Writes the passed chunk and flushes it to the client.
def send(self, *args, **kwargs): """Writes the passed chunk and flushes it to the client.""" self.write(*args, **kwargs) self.flush()
Writes the passed chunk flushes it to the client and terminates the connection.
def end(self, *args, **kwargs): """ Writes the passed chunk, flushes it to the client, and terminates the connection. """ self.send(*args, **kwargs) self.close()
Insert a value at the passed index in the named header.
def insert(self, name, index, value): """Insert a value at the passed index in the named header.""" return self.headers.insert(index, value)
Creates a base Flask project
def create_project(self): """ Creates a base Flask project """ if os.path.exists(self._py): prj_dir = os.path.join(self._app_dir, self._project_name) if os.path.exists(prj_dir): if self._force: logging.warn('Removing existing p...
This Context Manager is used to move the contents of a directory elsewhere temporarily and put them back upon exit. This allows testing code to use the same file directories as normal code without fear of damage.
def replaced_directory(dirname): """This ``Context Manager`` is used to move the contents of a directory elsewhere temporarily and put them back upon exit. This allows testing code to use the same file directories as normal code without fear of damage. The name of the temporary directory which con...
This Context Manager redirects STDOUT to a StringIO objects which is returned from the Context. On exit STDOUT is restored.
def capture_stdout(): """This ``Context Manager`` redirects STDOUT to a ``StringIO`` objects which is returned from the ``Context``. On exit STDOUT is restored. Example: .. code-block:: python with capture_stdout() as capture: print('foo') # got here? => capture.getvalue...
This Context Manager redirects STDERR to a StringIO objects which is returned from the Context. On exit STDERR is restored.
def capture_stderr(): """This ``Context Manager`` redirects STDERR to a ``StringIO`` objects which is returned from the ``Context``. On exit STDERR is restored. Example: .. code-block:: python with capture_stderr() as capture: print('foo') # got here? => capture.getvalue...
.. _createoptions:
def create(self, a, b, c): """ .. _createoptions: Create an option object used to start the manager :param a: The path of the config directory :type a: str :param b: The path of the user directory :type b: str :param c: The "command line" options of the ...
.. _addOptionBool:
def addOptionBool(self, name, value): """ .. _addOptionBool: Add a boolean option. :param name: The name of the option. :type name: str :param value: The value of the option. :type value: boolean :return: The result of the operation. :rtype: bool...
.. _addOptionInt:
def addOptionInt(self, name, value): """ .. _addOptionInt: Add an integer option. :param name: The name of the option. :type name: str :param value: The value of the option. :type value: boolean :return: The result of the operation. :rtype: bool ...
.. _addOptionString:
def addOptionString(self, name, value, append=False): """ .. _addOptionString: Add a string option. :param name: The name of the option. Option names are case insensitive and must be unique. :type name: str :param value: The value of the option. :type value: st...
.. _addOption:
def addOption(self, name, value): """ .. _addOption: Add an option. :param name: The name of the option. :type name: string :param value: The value of the option. :type value: boolean, integer, string :return: The result of the operation. :rtype:...
.. _getOption:
def getOption(self, name): """ .. _getOption: Retrieve option of a value. :param name: The name of the option. :type name: string :return: The value :rtype: boolean, integer, string or None :see: getOptionAsBool_, getOptionAsInt_, getOptionAsString_ ...
Builds the URL configuration for this resource.
def urls(cls): """Builds the URL configuration for this resource.""" return urls.patterns('', urls.url( r'^{}(?:$|(?P<path>[/:(.].*))'.format(cls.meta.name), cls.view, name='armet-api-{}'.format(cls.meta.name), kwargs={'resource': cls.meta.name}))
Dump an object in req format to the fp given.
def dump(obj, fp, startindex=1, separator=DEFAULT, index_separator=DEFAULT): '''Dump an object in req format to the fp given. :param Mapping obj: The object to serialize. Must have a keys method. :param fp: A writable that can accept all the types given. :param separator: The separator between key and...
Dump an object in req format to a string.
def dumps(obj, startindex=1, separator=DEFAULT, index_separator=DEFAULT): '''Dump an object in req format to a string. :param Mapping obj: The object to serialize. Must have a keys method. :param separator: The separator between key and value. Defaults to u'|' or b'|', depending on the types. :param ...
Load an object from the file pointer.
def load(fp, separator=DEFAULT, index_separator=DEFAULT, cls=dict, list_cls=list): '''Load an object from the file pointer. :param fp: A readable filehandle. :param separator: The separator between key and value. Defaults to u'|' or b'|', depending on the types. :param index_separator: The separator b...
Loads an object from a string.
def loads(s, separator=DEFAULT, index_separator=DEFAULT, cls=dict, list_cls=list): '''Loads an object from a string. :param s: An object to parse :type s: bytes or str :param separator: The separator between key and value. Defaults to u'|' or b'|', depending on the types. :param index_separator: T...
CLI entry point to bump requirements in requirements. txt or pinned. txt
def bump(): """ CLI entry point to bump requirements in requirements.txt or pinned.txt """ parser = argparse.ArgumentParser(description=bump.__doc__) parser.add_argument('names', nargs='*', help=""" Only bump dependencies that match the name. Name can be a product group name defined in workspac...
Bump dependency requirements using filter.
def bump(self, filter_requirements, required=False, show_summary=True, show_detail=False, **kwargs): """ Bump dependency requirements using filter. :param list filter_requirements: List of dependency filter requirements. :param bool required: Require the filter_requirements to be met (b...
Reverse all bumpers
def reverse(self): """ Reverse all bumpers """ if not self.test_drive and self.bumps: map(lambda b: b.reverse(), self.bumpers)
Expand targets by looking for - r in targets.
def _expand_targets(self, targets, base_dir=None): """ Expand targets by looking for '-r' in targets. """ all_targets = [] for target in targets: target_dirs = [p for p in [base_dir, os.path.dirname(target)] if p] target_dir = target_dirs and os.path.join(*target_dirs) o...
Gets the Nginx config for the project
def get_nginx_config(self): """ Gets the Nginx config for the project """ if os.path.exists(self._nginx_config): return open(self._nginx_config, 'r').read() else: return None
Creates base directories for app virtualenv and nginx
def check_directories(self): """ Creates base directories for app, virtualenv, and nginx """ self.log.debug('Checking directories') if not os.path.exists(self._ve_dir): os.makedirs(self._ve_dir) if not os.path.exists(self._app_dir): os.makedirs(se...
Creates the virtualenv for the project
def create_virtualenv(self): """ Creates the virtualenv for the project """ if check_command('virtualenv'): ve_dir = os.path.join(self._ve_dir, self._project_name) if os.path.exists(ve_dir): if self._force: logging.warn...
Creates the Nginx configuration for the project
def create_nginx_config(self): """ Creates the Nginx configuration for the project """ cfg = '# nginx config for {0}\n'.format(self._project_name) if not self._shared_hosting: # user if self._user: cfg += 'user {0};\n'.format(self._user) ...
Creates scripts to start and stop the application
def create_manage_scripts(self): """ Creates scripts to start and stop the application """ # create start script start = '# start script for {0}\n\n'.format(self._project_name) # start uwsgi start += 'echo \'Starting uWSGI...\'\n' start += 'sh {0}.uwsgi\n...
Creates the full project
def create(self): """ Creates the full project """ # create virtualenv self.create_virtualenv() # create project self.create_project() # generate uwsgi script self.create_uwsgi_script() # generate nginx config self.create_nginx_con...
Dasherizes the passed value.
def dasherize(value): """Dasherizes the passed value.""" value = value.strip() value = re.sub(r'([A-Z])', r'-\1', value) value = re.sub(r'[-_\s]+', r'-', value) value = re.sub(r'^-', r'', value) value = value.lower() return value
Redirect to the canonical URI for this resource.
def redirect(cls, request, response): """Redirect to the canonical URI for this resource.""" if cls.meta.legacy_redirect: if request.method in ('GET', 'HEAD',): # A SAFE request is allowed to redirect using a 301 response.status = http.client.MOVED_PERMANENTLY...
Entry - point of the request/ response cycle ; Handles resource creation and delegation.
def view(cls, request, response): """ Entry-point of the request / response cycle; Handles resource creation and delegation. @param[in] requset The HTTP request object; containing accessors for information about the request. @param[in] response ...
Parses out parameters and separates them out of the path.
def parse(cls, path): """Parses out parameters and separates them out of the path. This uses one of the many defined patterns on the options class. But, it defaults to a no-op if there are no defined patterns. """ # Iterate through the available patterns. for resource, p...
Traverses down the path and determines the accessed resource.
def traverse(cls, request, params=None): """Traverses down the path and determines the accessed resource. This makes use of the patterns array to implement simple traversal. This defaults to a no-op if there are no defined patterns. """ # Attempt to parse the path using a patter...
Helper method used in conjunction with the view handler to stream responses to the client.
def stream(cls, response, sequence): """ Helper method used in conjunction with the view handler to stream responses to the client. """ # Construct the iterator and run the sequence once in order # to capture any headers and status codes set. iterator = iter(seque...
Deserializes the text using a determined deserializer.
def deserialize(self, request=None, text=None, format=None): """Deserializes the text using a determined deserializer. @param[in] request The request object to pull information from; normally used to determine the deserialization format (when `format` is not provided...
Serializes the data using a determined serializer.
def serialize(self, data, response=None, request=None, format=None): """Serializes the data using a determined serializer. @param[in] data The data to be serialized. @param[in] response The response object to serialize the data to. If this method is invoked ...
Facilitate Cross - Origin Requests ( CORs ).
def _process_cross_domain_request(cls, request, response): """Facilitate Cross-Origin Requests (CORs). """ # Step 1 # Check for Origin header. origin = request.get('Origin') if not origin: return # Step 2 # Check if the origin is in the list ...
Entry - point of the dispatch cycle for this resource.
def dispatch(self, request, response): """Entry-point of the dispatch cycle for this resource. Performs common work such as authentication, decoding, etc. before handing complete control of the result to a function with the same name as the request method. """ # Assert a...
Ensure we are authenticated.
def require_authentication(self, request): """Ensure we are authenticated.""" request.user = user = None if request.method == 'OPTIONS': # Authentication should not be checked on an OPTIONS request. return for auth in self.meta.authentication: user =...
Ensure we are allowed to access this resource.
def require_accessibility(self, user, method): """Ensure we are allowed to access this resource.""" if method == 'OPTIONS': # Authorization should not be checked on an OPTIONS request. return authz = self.meta.authorization if not authz.is_accessible(user, method...