INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Authenticates and then outputs the resulting information.
def cli_auth(context): """ Authenticates and then outputs the resulting information. See :py:mod:`swiftly.cli.auth` for context usage information. See :py:class:`CLIAuth` for more information. """ with context.io_manager.with_stdout() as fp: with context.client_manager.with_client() as...
Returns a TempURL good for the given request method url and number of seconds from now signed by the given key.
def generate_temp_url(method, url, seconds, key): """ Returns a TempURL good for the given request method, url, and number of seconds from now, signed by the given key. """ method = method.upper() base_url, object_path = url.split('/v1/') object_path = '/v1/' + object_path expires = int(...
Much like parse. quote in that it returns a URL encoded string for the given value protecting the safe characters ; but this version also ensures the value is UTF - 8 encoded.
def quote(value, safe='/:'): """ Much like parse.quote in that it returns a URL encoded string for the given value, protecting the safe characters; but this version also ensures the value is UTF-8 encoded. """ if isinstance(value, six.text_type): value = value.encode('utf8') elif not...
Converts a sequence of ( name value ) tuples into a dict where if a given name occurs more than once its value in the dict will be a list of values.
def headers_to_dict(headers): """ Converts a sequence of (name, value) tuples into a dict where if a given name occurs more than once its value in the dict will be a list of values. """ hdrs = {} for h, v in headers: h = h.lower() if h in hdrs: if isinstance(hdrs[...
Issues commands for each item in an account or container listing.
def cli_fordo(context, path=None): """ Issues commands for each item in an account or container listing. See :py:mod:`swiftly.cli.fordo` for context usage information. See :py:class:`CLIForDo` for more information. """ path = path.lstrip('/') if path else None if path and '/' in path: ...
Obtains a client for use whether an existing unused client or a brand new one if none are available.
def get_client(self): """ Obtains a client for use, whether an existing unused client or a brand new one if none are available. """ client = None try: client = self.clients.get(block=False) except queue.Empty: pass if not client: ...
Performs a HEAD on the item ( account container or object ).
def cli_head(context, path=None): """ Performs a HEAD on the item (account, container, or object). See :py:mod:`swiftly.cli.head` for context usage information. See :py:class:`CLIHead` for more information. """ path = path.lstrip('/') if path else None with context.client_manager.with_clie...
Generator that encrypts a content stream using AES 256 in CBC mode.
def aes_encrypt(key, stdin, preamble=None, chunk_size=65536, content_length=None): """ Generator that encrypts a content stream using AES 256 in CBC mode. :param key: Any string to use as the encryption key. :param stdin: Where to read the contents from. :param preamble: str to ...
Generator that decrypts a content stream using AES 256 in CBC mode.
def aes_decrypt(key, stdin, chunk_size=65536): """ Generator that decrypts a content stream using AES 256 in CBC mode. :param key: Any string to use as the decryption key. :param stdin: Where to read the encrypted data from. :param chunk_size: Largest amount to read at once. """ if not ...
Performs PUTs rooted at the path using a directory structure pointed to by context. input \ _.
def cli_put_directory_structure(context, path): """ Performs PUTs rooted at the path using a directory structure pointed to by context.input\_. See :py:mod:`swiftly.cli.put` for context usage information. See :py:class:`CLIPut` for more information. """ if not context.input_: raise...
Performs a PUT on the account.
def cli_put_account(context): """ Performs a PUT on the account. See :py:mod:`swiftly.cli.put` for context usage information. See :py:class:`CLIPut` for more information. """ body = None if context.input_: if context.input_ == '-': body = context.io_manager.get_stdin() ...
Performs a PUT on the container.
def cli_put_container(context, path): """ Performs a PUT on the container. See :py:mod:`swiftly.cli.put` for context usage information. See :py:class:`CLIPut` for more information. """ path = path.rstrip('/') if '/' in path: raise ReturnCode('called cli_put_container with object %r...
Performs a PUT on the object.
def cli_put_object(context, path): """ Performs a PUT on the object. See :py:mod:`swiftly.cli.put` for context usage information. See :py:class:`CLIPut` for more information. """ if context.different and context.encrypt: raise ReturnCode( 'context.different will not work pr...
Performs a PUT on the item ( account container or object ).
def cli_put(context, path): """ Performs a PUT on the item (account, container, or object). See :py:mod:`swiftly.cli.put` for context usage information. See :py:class:`CLIPut` for more information. """ path = path.lstrip('/') if path else '' if context.input_ and os.path.isdir(context.inpu...
Returns body for manifest file and modifies put_headers.
def _get_manifest_body(context, prefix, path2info, put_headers): """ Returns body for manifest file and modifies put_headers. path2info is a dict like {"path": (size, etag)} """ if context.static_segments: body = json.dumps([ {'path': '/' + p, 'size_bytes': s, 'etag': e} ...
Creates container for segments of file with path
def _create_container(context, path, l_mtime, size): """ Creates container for segments of file with `path` """ new_context = context.copy() new_context.input_ = None new_context.headers = None new_context.query = None container = path.split('/', 1)[0] + '_segments' cli_put_container...
Generates a TempURL and sends that to the context. io_manager s stdout.
def cli_tempurl(context, method, path, seconds=None, use_container=False): """ Generates a TempURL and sends that to the context.io_manager's stdout. See :py:mod:`swiftly.cli.tempurl` for context usage information. See :py:class:`CLITempURL` for more information. :param context: The :py:class...
See: py: func: swiftly. client. client. Client. auth
def auth(self): """ See :py:func:`swiftly.client.client.Client.auth` """ self.reset() if not self.auth_url: raise ValueError('No Auth URL has been provided.') funcs = [] if self.auth_methods: for method in self.auth_methods.split(','): ...
See: py: func: swiftly. client. client. Client. request
def request(self, method, path, contents, headers, decode_json=False, stream=False, query=None, cdn=False): """ See :py:func:`swiftly.client.client.Client.request` """ if query: path += '?' + '&'.join( ('%s=%s' % (quote(k), quote(v)) if v else ...
See: py: func: swiftly. client. client. Client. reset
def reset(self): """ See :py:func:`swiftly.client.client.Client.reset` """ for conn in (self.storage_conn, self.cdn_conn): if conn: try: conn.close() except Exception: pass self.storage_conn = Non...
See: py: func: swiftly. client. client. Client. get_account_hash
def get_account_hash(self): """ See :py:func:`swiftly.client.client.Client.get_account_hash` """ if not(self.storage_url or self.storage_path): self.auth() return (self.storage_url or self.storage_path).rsplit('/', 1)[1]
Translates any information that can be determined from the x_trans_id and sends that to the context. io_manager s stdout.
def cli_trans(context, x_trans_id): """ Translates any information that can be determined from the x_trans_id and sends that to the context.io_manager's stdout. See :py:mod:`swiftly.cli.trans` for context usage information. See :py:class:`CLITrans` for more information. """ with context.io...
Outputs help information.
def cli_help(context, command_name, general_parser, command_parsers): """ Outputs help information. See :py:mod:`swiftly.cli.help` for context usage information. See :py:class:`CLIHelp` for more information. :param context: The :py:class:`swiftly.cli.context.CLIContext` to use. :param...
read ( [ size ] ) - > read at most size bytes returned as a string.
def read(self, size=-1): """ read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter...
readline ( [ size ] ) - > next line from the file as a string.
def readline(self, size=-1): """ readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF. """ if ...
readlines ( [ size ] ) - > list of strings each a line from the file.
def readlines(self, sizehint=-1): """ readlines([size]) -> list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read. The optional size argument, if given, is an approximate bound on the total number of bytes in the lines retur...
Check whether the file is empty reading the single byte.
def is_empty(self): """ Check whether the "file" is empty reading the single byte. """ something = self.read(1) if something: if self.buf: self.buf = something + self.buf else: self.buf = something return False ...
Encrypts context. io_manager s stdin and sends that to context. io_manager s stdout.
def cli_encrypt(context, key): """ Encrypts context.io_manager's stdin and sends that to context.io_manager's stdout. This can be useful to encrypt to disk before attempting to upload, allowing uploads retries and segmented encrypted objects. See :py:mod:`swiftly.cli.encrypt` for context usage...
Determine the value for BUILD_COMMITS from the app and repository config. Resolves the previous BUILD_ALL_COMMITS = True/ False option to BUILD_COMMITS = ALL/ LAST respectively.
def get_build_commits(app, repo_config): """ Determine the value for BUILD_COMMITS from the app and repository config. Resolves the previous BUILD_ALL_COMMITS = True/False option to BUILD_COMMITS = 'ALL'/'LAST' respectively. """ build_commits = repo_config.get("build_commits") build_all_comm...
Gets the status of a commit.
def get_status(app, repo_config, repo_name, sha): """Gets the status of a commit. .. note:: ``repo_name`` might not ever be anything other than ``repo_config['github_repo']``. :param app: Flask app for leeroy :param repo_config: configuration for the repo :param repo_name: The name...
Data for a given pull request.
def get_pull_request(app, repo_config, pull_request): """Data for a given pull request. :param app: Flask app :param repo_config: dict with ``github_repo`` key :param pull_request: the pull request number """ response = get_api_response( app, repo_config, "/repos/{{repo_name}}/p...
Last 30 pull requests from a repository.
def get_pull_requests(app, repo_config): """Last 30 pull requests from a repository. :param app: Flask app :param repo_config: dict with ``github_repo`` key :returns: id for a pull request """ response = get_api_response(app, repo_config, "/repos/{repo_name}/pulls") if not response.ok: ...
Write obj in elasticsearch.: param obj: value to be written in elasticsearch.: param resource_id: id for the resource.: return: id of the transaction.
def write(self, obj, resource_id=None): """Write obj in elasticsearch. :param obj: value to be written in elasticsearch. :param resource_id: id for the resource. :return: id of the transaction. """ self.logger.debug('elasticsearch::write::{}'.format(resource_id)) ...
Read object in elasticsearch using the resource_id.: param resource_id: id of the object to be read.: return: object value from elasticsearch.
def read(self, resource_id): """Read object in elasticsearch using the resource_id. :param resource_id: id of the object to be read. :return: object value from elasticsearch. """ self.logger.debug('elasticsearch::read::{}'.format(resource_id)) return self.driver._es.get( ...
Update object in elasticsearch using the resource_id.: param metadata: new metadata for the transaction.: param resource_id: id of the object to be updated.: return: id of the object.
def update(self, obj, resource_id): """Update object in elasticsearch using the resource_id. :param metadata: new metadata for the transaction. :param resource_id: id of the object to be updated. :return: id of the object. """ self.logger.debug('elasticsearch::update::{}'...
Delete an object from elasticsearch.: param resource_id: id of the object to be deleted.: return:
def delete(self, resource_id): """Delete an object from elasticsearch. :param resource_id: id of the object to be deleted. :return: """ self.logger.debug('elasticsearch::delete::{}'.format(resource_id)) if self.driver._es.exists( index=self.driver._index, ...
List all the objects saved elasticsearch.: param search_from: start offset of objects to return.: param search_to: last offset of objects to return.: param limit: max number of values to be returned.: return: list with transactions.
def list(self, search_from=None, search_to=None, limit=None): """List all the objects saved elasticsearch. :param search_from: start offset of objects to return. :param search_to: last offset of objects to return. :param limit: max number of values to be returned. :return: li...
Query elasticsearch for objects.: param search_model: object of QueryModel.: return: list of objects that match the query.
def query(self, search_model: QueryModel): """Query elasticsearch for objects. :param search_model: object of QueryModel. :return: list of objects that match the query. """ query_parsed = query_parser(search_model.query) self.logger.debug(f'elasticsearch::query::{query_pa...
Query elasticsearch for objects.: param search_model: object of FullTextModel: return: list of objects that match the query.
def text_query(self, search_model: FullTextModel): """Query elasticsearch for objects. :param search_model: object of FullTextModel :return: list of objects that match the query. """ self.logger.debug('elasticsearch::text_query::{}'.format(search_model.text)) if search_mo...
Write your forwards methods here.
def forwards(self, orm): "Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..." for title in orm['hero_slider.SliderItemTitle'].objects.all(): title.is_published = True title.save()
Returns the published slider items.
def get_slider_items(context, amount=None): """Returns the published slider items.""" req = context.get('request') qs = SliderItem.objects.published(req).order_by('position') if amount: qs = qs[:amount] return qs
Renders the hero slider.
def render_hero_slider(context): """ Renders the hero slider. """ req = context.get('request') qs = SliderItem.objects.published(req).order_by('position') return { 'slider_items': qs, }
Acquire the lock to read
def reader_acquire(self): """Acquire the lock to read""" self._order_mutex.acquire() self._readers_mutex.acquire() if self._readers == 0: self._access_mutex.acquire() self._readers += 1 self._order_mutex.release() self._readers_mutex.release()
Release the lock after reading
def reader_release(self): """Release the lock after reading""" self._readers_mutex.acquire() self._readers -= 1 if self._readers == 0: self._access_mutex.release() self._readers_mutex.release()
Acquire the lock to write
def writer_acquire(self): """Acquire the lock to write""" self._order_mutex.acquire() self._access_mutex.acquire() self._order_mutex.release()
Add a task to the registry.
def add(self, task_id, backend, category, backend_args, archiving_cfg=None, scheduling_cfg=None): """Add a task to the registry. This method adds task using `task_id` as identifier. If a task with the same identifier already exists on the registry, a `AlreadyExistsError` exc...
Remove a task from the registry.
def remove(self, task_id): """Remove a task from the registry. To remove it, pass its identifier with `taks_id` parameter. When the identifier is not found, a `NotFoundError` exception is raised. :param task_id: identifier of the task to remove :raises NotFoundError: r...
Get a task from the registry.
def get(self, task_id): """Get a task from the registry. Retrieve a task from the registry using its task identifier. When the task does not exist, a `NotFoundError` exception will be raised. :param task_id: task identifier :returns: a task object :raises NotF...
Get the list of tasks
def tasks(self): """Get the list of tasks""" self._rwlock.reader_acquire() tl = [v for v in self._tasks.values()] tl.sort(key=lambda x: x.task_id) self._rwlock.reader_release() return tl
Returns a dict with the representation of this task configuration object.
def to_dict(self): """Returns a dict with the representation of this task configuration object.""" properties = find_class_properties(self.__class__) config = { name: self.__getattribute__(name) for name, _ in properties } return config
Create an configuration object from a dictionary.
def from_dict(cls, config): """Create an configuration object from a dictionary. Key,value pairs will be used to initialize a task configuration object. If 'config' contains invalid configuration parameters a `ValueError` exception will be raised. :param config: dictionary used...
Add metadata to an item.
def metadata(func): """Add metadata to an item. Decorator that adds metadata to Perceval items such as the identifier of the job that generated it or the version of the system. The contents from the original item will be stored under the 'data' keyword. Take into account that this function onl...
Execute a Perceval job on RQ.
def execute_perceval_job(backend, backend_args, qitems, task_id, category, archive_args=None, max_retries=MAX_JOB_RETRIES): """Execute a Perceval job on RQ. The items fetched during the process will be stored in a Redis queue named `queue`. Setting the parameter `archive_path`...
Initialize the archive manager.
def initialize_archive_manager(self, archive_path): """Initialize the archive manager. :param archive_path: path where the archive manager is located """ if archive_path == "": raise ValueError("Archive manager path cannot be empty") if archive_path: sel...
Run the backend with the given parameters.
def run(self, backend_args, archive_args=None, resume=False): """Run the backend with the given parameters. The method will run the backend assigned to this job, storing the fetched items in a Redis queue. The ongoing status of the job, can be accessed through the property `resu...
Execute a backend of Perceval.
def _execute(self, backend_args, archive_args): """Execute a backend of Perceval. Run the backend of Perceval assigned to this job using the given arguments. It will raise an `AttributeError` when any of the required parameters to run the backend are not found. Other exceptions ...
Configure the index to work with
def create_index(idx_url, clean=False): """Configure the index to work with""" try: r = requests.get(idx_url) except requests.exceptions.ConnectionError: cause = "Error connecting to Elastic Search (index: %s)" % idx_url raise ElasticSearchError(cause=cause) ...
Create a mapping
def create_mapping(idx_url, mapping): """Create a mapping""" mapping_url = idx_url + '/items/_mapping' mapping = json.dumps(mapping) try: r = requests.put(mapping_url, data=mapping, headers={'Content-Type': 'application/json'}) except re...
Custom JSON encoder handler
def json_encoder(*args, **kwargs): """Custom JSON encoder handler""" obj = cherrypy.serving.request._json_inner_handler(*args, **kwargs) for chunk in JSONEncoder().iterencode(obj): yield chunk.encode('utf-8')
Write items to the queue
def write_items(cls, writer, items_generator): """Write items to the queue :param writer: the writer object :param items_generator: items to be written in the queue """ while True: items = items_generator() writer.write(items) time.sleep(1)
Add tasks
def add(self): """Add tasks""" payload = cherrypy.request.json logger.debug("Reading tasks...") for task_data in payload['tasks']: try: category = task_data['category'] backend_args = task_data['backend_args'] archive_args = t...
Remove tasks
def remove(self): """Remove tasks""" payload = cherrypy.request.json logger.debug("Reading tasks to remove...") task_ids = {} for task_data in payload['tasks']: task_id = task_data['task_id'] removed = super().remove_task(task_id) task_ids[t...
List tasks
def tasks(self): """List tasks""" logger.debug("API 'tasks' method called") result = [task.to_dict() for task in self._tasks.tasks] result = {'tasks': result} logger.debug("Tasks registry read") return result
Add and schedule a task.
def add_task(self, task_id, backend, category, backend_args, archive_args=None, sched_args=None): """Add and schedule a task. :param task_id: id of the task :param backend: name of the backend :param category: category of the items to fecth :param backend_args: ...
Remove and cancel a task.
def remove_task(self, task_id): """Remove and cancel a task. :param task_id: id of the task to be removed """ try: self._scheduler.cancel_task(task_id) except NotFoundError as e: logger.info("Cannot cancel %s task because it does not exist.", ...
Get the items fetched by the jobs.
def items(self): """Get the items fetched by the jobs.""" # Get and remove queued items in an atomic transaction pipe = self.conn.pipeline() pipe.lrange(Q_STORAGE_ITEMS, 0, -1) pipe.ltrim(Q_STORAGE_ITEMS, 1, 0) items = pipe.execute()[0] for item in items: ...
Check that the task arguments received are valid
def __validate_args(task_id, backend, category, backend_args): """Check that the task arguments received are valid""" if not task_id or task_id.strip() == "": msg = "Missing task_id for task" raise ValueError(msg) if not backend or backend.strip() == "": msg...
Parse the archive arguments of a task
def __parse_archive_args(self, archive_args): """Parse the archive arguments of a task""" if not archive_args: return None archiving_args = copy.deepcopy(archive_args) if self.archive_path: archiving_args['archive_path'] = self.archive_path else: ...
Custom method to execute a job and notify of its result
def perform_job(self, job, queue): """Custom method to execute a job and notify of its result :param job: Job object :param queue: the queue containing the object """ result = super().perform_job(job, queue) job_status = job.get_status() job_result = job.return...
Schedule a job in the given queue.
def schedule_job_task(self, queue_id, task_id, job_args, delay=0): """Schedule a job in the given queue.""" self._rwlock.writer_acquire() job_id = self._generate_job_id(task_id) event = self._scheduler.enter(delay, 1, self._enqueue_job, argument=(...
Cancel the job related to the given task.
def cancel_job_task(self, task_id): """Cancel the job related to the given task.""" try: self._rwlock.writer_acquire() job_id = self._tasks.get(task_id, None) if job_id: self._cancel_job(job_id) else: logger.warning("Task...
Run thread to listen for jobs and reschedule successful ones.
def run(self): """Run thread to listen for jobs and reschedule successful ones.""" try: self.listen() except Exception as e: logger.critical("JobListener instence crashed. Error: %s", str(e)) logger.critical(traceback.format_exc())
Listen for completed jobs and reschedule successful ones.
def listen(self): """Listen for completed jobs and reschedule successful ones.""" pubsub = self.conn.pubsub() pubsub.subscribe(self.pubsub_channel) logger.debug("Listening on channel %s", self.pubsub_channel) for msg in pubsub.listen(): logger.debug("New message re...
Start scheduling jobs.
def schedule(self): """Start scheduling jobs.""" if self.async_mode: self._scheduler.start() self._listener.start() else: self._scheduler.schedule()
Schedule a task.
def schedule_task(self, task_id): """Schedule a task. :param task_id: identifier of the task to schedule :raises NotFoundError: raised when the requested task is not found in the registry """ task = self.registry.get(task_id) job_args = self._build_job_argu...
Cancel or un - schedule a task.
def cancel_task(self, task_id): """Cancel or 'un-schedule' a task. :param task_id: identifier of the task to cancel :raises NotFoundError: raised when the requested task is not found in the registry """ self.registry.remove(task_id) self._scheduler.cancel_jo...
Handle successufl jobs
def _handle_successful_job(self, job): """Handle successufl jobs""" result = job.result task_id = job.kwargs['task_id'] try: task = self.registry.get(task_id) except NotFoundError: logger.warning("Task %s not found; related job #%s will not be reschedule...
Handle failed jobs
def _handle_failed_job(self, job): """Handle failed jobs""" task_id = job.kwargs['task_id'] logger.error("Job #%s (task: %s) failed; cancelled", job.id, task_id)
Build the set of arguments required for running a job
def _build_job_arguments(task): """Build the set of arguments required for running a job""" job_args = {} job_args['qitems'] = Q_STORAGE_ITEMS job_args['task_id'] = task.task_id # Backend parameters job_args['backend'] = task.backend backend_args = copy.deepcopy...
Gets contents of secret file
def get_secret(secret_name, default=None): """ Gets contents of secret file :param secret_name: The name of the secret present in BANANAS_SECRETS_DIR :param default: Default value to return if no secret was found :return: The secret or default if not found """ secrets_dir = get_secrets_dir(...
Register the API view class in the bananas router.
def register(view): # Type[BananasAPI] """ Register the API view class in the bananas router. :param BananasAPI view: """ meta = view.get_admin_meta() prefix = meta.basename.replace(".", "/") router.register(prefix, view, meta.basename)
Register a generic class based view wrapped with ModelAdmin and fake model
def register(view=None, *, admin_site=None, admin_class=ModelAdminView): """ Register a generic class based view wrapped with ModelAdmin and fake model :param view: The AdminView to register. :param admin_site: The AdminSite to register the view on. Defaults to bananas.admin.ExtendedAdminSite. ...
Extended DRF with fallback to requested namespace if request. version is missing
def reverse_action(self, url_name, *args, **kwargs): """ Extended DRF with fallback to requested namespace if request.version is missing """ if self.request and not self.request.version: return reverse(self.get_url_name(url_name), *args, **kwargs) return super().reve...
Get full namespaced url name to use for reverse ()
def get_url_name(self, action_url_name="list"): """ Get full namespaced url name to use for reverse() """ url_name = "{}-{}".format(self.basename, action_url_name) namespace = self.request.resolver_match.namespace if namespace: url_name = "{}:{}".format(names...
Get or generate human readable view name. Extended version from DRF to support usage from both class and instance.
def get_view_name(self, respect_name=True): """ Get or generate human readable view name. Extended version from DRF to support usage from both class and instance. """ if isinstance(self, type): view = self else: view = self.__class__ # Nam...
Derives a PEP386 - compliant version number from VERSION.
def get_version(version=None): """Derives a PEP386-compliant version number from VERSION.""" if version is None: version = VERSION assert len(version) == 5 assert version[3] in ("alpha", "beta", "rc", "final") # Now build the two parts of the version number: # main = X.Y[.Z] # sub =...
Compat: drf - yasg 1. 12 +
def get_summary_and_description(self): """ Compat: drf-yasg 1.12+ """ summary = self.get_summary() _, description = super().get_summary_and_description() return summary, description
Compat: drf - yasg 1. 11
def get_summary(self): """ Compat: drf-yasg 1.11 """ title = None method_name = getattr(self.view, "action", self.method.lower()) action = getattr(self.view, method_name, None) action_kwargs = getattr(action, "kwargs", None) if action_kwargs: ...
Prefix viewname with full namespace bananas: vX. Y:
def get_versioned_viewname(self, viewname, request): """ Prefix viewname with full namespace bananas:vX.Y: """ namespace = request.resolver_match.namespace if namespace: viewname = "{}:{}".format(namespace, viewname) return viewname
Get engine or raise exception resolves Alias - instances to a sibling target.
def resolve(cursor, key): """ Get engine or raise exception, resolves Alias-instances to a sibling target. :param cursor: The object so search in :param key: The key to get :return: The object found """ try: result = cursor[key] # Resolve alias if isinstance(result,...
Perform a lookup in _ENGINE_MAPPING using engine_string.
def get_engine(scheme): """ Perform a lookup in _ENGINE_MAPPING using engine_string. :param scheme: '+'-separated string Maximum of 2 parts, i.e "postgres+psycopg" is OK, "postgres+psycopg2+postgis" is NOT OK. :return: Engine string """ path = scheme.split("+") first, rest = path[0], pa...
Get database name and database schema from path.
def parse_path(path): """ Get database name and database schema from path. :param path: "/"-delimited path, parsed as "/<database name>/<database schema>" :return: tuple with (database or None, schema or None) """ if path is None: raise ValueError("path must be a string") part...
Return a django - style database configuration based on url.
def database_conf_from_url(url): """ Return a django-style database configuration based on ``url``. :param url: Database URL :return: Django-style database configuration dict Example: >>> conf = database_conf_from_url( ... 'pgsql://joar:hunter2@5monkeys.se:4242/tweets/tweetschema' ...
Parse a database URL and return a DatabaseInfo named tuple.
def parse_database_url(url): """ Parse a database URL and return a DatabaseInfo named tuple. :param url: Database URL :return: DatabaseInfo instance Example: >>> conf = parse_database_url( ... 'pgsql://joar:hunter2@5monkeys.se:4242/tweets/tweetschema' ... '?hello=world') >>...
Log in django staff user
def create(self, request): """ Log in django staff user """ # TODO: Decorate api with sensitive post parameters as Django admin do? # from django.utils.decorators import method_decorator # from django.views.decorators.debug import sensitive_post_parameters # sensi...
Retrieve logged in user info
def list(self, request): """ Retrieve logged in user info """ serializer = self.get_serializer(request.user) return Response(serializer.data, status=status.HTTP_200_OK)
Change password for logged in django staff user
def create(self, request): """ Change password for logged in django staff user """ # TODO: Decorate api with sensitive post parameters as Django admin do? password_form = PasswordChangeForm(request.user, data=request.data) if not password_form.is_valid(): ra...
This is needed due to DRF s model serializer uses the queryset to build url name
def build_url_field(self, field_name, model_class): """ This is needed due to DRF's model serializer uses the queryset to build url name # TODO: Move this to own serializer mixin or fix problem elsewhere? """ field, kwargs = super().build_url_field(field_name, model_class) ...
Parse string to bool.
def parse_bool(value): """ Parse string to bool. :param str value: String value to parse as bool :return bool: """ boolean = parse_str(value).capitalize() if boolean in ("True", "Yes", "On", "1"): return True elif boolean in ("False", "No", "Off", "0"): return False ...
Parse numeric string to int. Supports oct formatted string.
def parse_int(value): """ Parse numeric string to int. Supports oct formatted string. :param str value: String value to parse as int :return int: """ value = parse_str(value=value) if value.startswith("0"): return int(value.lstrip("0o"), 8) else: return int(value)