text stringlengths 81 112k |
|---|
View handler decorator that adds SID resolve and PID validation.
- For v1 calls, assume that ``did`` is a pid and raise NotFound exception if it's
not valid.
- For v2 calls, if DID is a valid PID, return it. If not, try to resolve it as a
SID and, if successful, return the new PID. Else, raise NotF... |
View handler decorator that decodes "%2f" ("/") in SID or PID extracted from URL
path segment by Django.
def decode_did(f):
"""View handler decorator that decodes "%2f" ("/") in SID or PID extracted from URL
path segment by Django."""
@functools.wraps(f)
def wrapper(request, did, *args, **kwargs):... |
Access only by D1 infrastructure.
def trusted_permission(f):
"""Access only by D1 infrastructure."""
@functools.wraps(f)
def wrapper(request, *args, **kwargs):
trusted(request)
return f(request, *args, **kwargs)
return wrapper |
Access to listObjects() controlled by settings.PUBLIC_OBJECT_LIST.
def list_objects_access(f):
"""Access to listObjects() controlled by settings.PUBLIC_OBJECT_LIST."""
@functools.wraps(f)
def wrapper(request, *args, **kwargs):
if not django.conf.settings.PUBLIC_OBJECT_LIST:
trusted(req... |
Access to getLogRecords() controlled by settings.PUBLIC_LOG_RECORDS.
def get_log_records_access(f):
"""Access to getLogRecords() controlled by settings.PUBLIC_LOG_RECORDS."""
@functools.wraps(f)
def wrapper(request, *args, **kwargs):
if not django.conf.settings.PUBLIC_LOG_RECORDS:
trus... |
Access only by subjects with Create/Update/Delete permission and by trusted
infrastructure (CNs).
def assert_create_update_delete_permission(f):
"""Access only by subjects with Create/Update/Delete permission and by trusted
infrastructure (CNs)."""
@functools.wraps(f)
def wrapper(request, *args, *... |
Access only with a valid session.
def authenticated(f):
"""Access only with a valid session."""
@functools.wraps(f)
def wrapper(request, *args, **kwargs):
if d1_common.const.SUBJECT_AUTHENTICATED not in request.all_subjects_set:
raise d1_common.types.exceptions.NotAuthorized(
... |
Assert that subject has access at given level or higher for object.
def required_permission(f, level):
"""Assert that subject has access at given level or higher for object."""
@functools.wraps(f)
def wrapper(request, pid, *args, **kwargs):
d1_gmn.app.auth.assert_allowed(request, level, pid)
... |
Given a response body, try to create an instance of a DataONE type.
The return value will be either an instance of a type or a DataONE exception.
def _read_and_deserialize_dataone_type(self, response):
"""Given a response body, try to create an instance of a DataONE type.
The return value wil... |
Initiate a MNRead.get(). Return a Requests Response object from which the
object bytes can be retrieved.
When ``stream`` is False, Requests buffers the entire object in memory before
returning the Response. This can exhaust available memory on the local machine
when retrieving large sci... |
Like MNRead.get(), but also retrieve the object bytes and store them in a
stream. This method does not have the potential issue with excessive memory
usage that get() with ``stream``=False has.
Also see MNRead.get().
def get_and_save(
self, pid, sciobj_stream, create_missing_dirs=False... |
Note: If the server returns a status code other than 200 OK, a ServiceFailure
will be raised, as this method is based on a HEAD request, which cannot carry
exception information.
def describe(self, pid, vendorSpecific=None):
"""Note: If the server returns a status code other than 200 OK, a Serv... |
Return True if user is allowed to perform ``action`` on ``pid``, else
False.
def isAuthorized(self, pid, action, vendorSpecific=None):
"""Return True if user is allowed to perform ``action`` on ``pid``, else
False."""
response = self.isAuthorizedResponse(pid, action, vendorSpecific)
... |
Filter fields based on request query parameters.
def fields(self):
"""Filter fields based on request query parameters."""
fields = super().fields
return apply_subfield_projection(self, copy.copy(fields)) |
Iterate over all field values sub-fields.
This will iterate over all field values. Some fields defined in the schema
might not be visited.
:param fields: field values to iterate over
:type fields: dict
:param schema: schema to iterate over
:type schema: dict
:return: (field schema, field v... |
Iterate over all schema sub-fields.
This will iterate over all field definitions in the schema. Some field v
alues might be None.
:param fields: field values to iterate over
:type fields: dict
:param schema: schema to iterate over
:type schema: dict
:param path_prefix: dot separated path p... |
Iterate over a nested dictionary.
The dictionary is iterated over in a depth first manner.
:param container: Dictionary to iterate over
:param exclude: Optional callable, which is given key and value as
arguments and may return True to stop iteration of that branch
:return: (path, key, value) ... |
Get all subjects in the certificate.
- Returns: primary_str (primary subject), equivalent_set (equivalent identities,
groups and group memberships)
- The primary subject is the certificate subject DN, serialized to a DataONE
compliant subject string.
def get_subjects(request):
"""Get all subje... |
Return primary subject and set of equivalents authenticated by certificate.
- ``cert_pem`` can be str or bytes
def get_authenticated_subjects(cert_pem):
"""Return primary subject and set of equivalents authenticated by certificate.
- ``cert_pem`` can be str or bytes
"""
if isinstance(cert_pem, s... |
Augment base serializer class.
Include permissions information with objects.
def get_serializer_class(self):
"""Augment base serializer class.
Include permissions information with objects.
"""
base_class = super().get_serializer_class()
class SerializerWithPermission... |
Get or set permissions API endpoint.
def detail_permissions(self, request, pk=None):
"""Get or set permissions API endpoint."""
obj = self.get_object()
if request.method == 'POST':
content_type = ContentType.objects.get_for_model(obj)
payload = request.data
... |
Perform descriptor validation and save object.
def save(self, *args, **kwargs):
"""Perform descriptor validation and save object."""
if self.descriptor_schema:
try:
validate_schema(self.descriptor, self.descriptor_schema.schema) # pylint: disable=no-member
s... |
Duplicate (make a copy).
def duplicate(self, contributor=None):
"""Duplicate (make a copy)."""
duplicate = Collection.objects.get(id=self.id)
duplicate.pk = None
duplicate.slug = None
duplicate.name = 'Copy of {}'.format(self.name)
duplicate.duplicated = now()
if... |
Convert a dictionary with scalar elements and string indices '_1234'
to a dictionary of arrays. Unspecified entries are np.nan.
def _scalar2array(d):
"""Convert a dictionary with scalar elements and string indices '_1234'
to a dictionary of arrays. Unspecified entries are np.nan."""
da = {}
for k, ... |
To get rid of NaNs produced by _scalar2array, symmetrize operators
where C_ijkl = C_jilk*
def _symm_herm(C):
"""To get rid of NaNs produced by _scalar2array, symmetrize operators
where C_ijkl = C_jilk*"""
nans = np.isnan(C)
C[nans] = np.einsum('jilk', C)[nans].conj()
return C |
To get rid of NaNs produced by _scalar2array, symmetrize operators
where C_ijkl = C_klij
def _symm_current(C):
"""To get rid of NaNs produced by _scalar2array, symmetrize operators
where C_ijkl = C_klij"""
nans = np.isnan(C)
C[nans] = np.einsum('klij', C)[nans]
return C |
To get rid of NaNs produced by _scalar2array, antisymmetrize the first
two indices of operators where C_ijkl = -C_jikl
def _antisymm_12(C):
"""To get rid of NaNs produced by _scalar2array, antisymmetrize the first
two indices of operators where C_ijkl = -C_jikl"""
nans = np.isnan(C)
C[nans] = -np.e... |
For a dictionary with JMS Wilson coefficients, return a dictionary
of arrays.
def JMS_to_array(C, sectors=None):
"""For a dictionary with JMS Wilson coefficients, return a dictionary
of arrays."""
if sectors is None:
wc_keys = wcxf.Basis['WET', 'JMS'].all_wcs
else:
try:
... |
For a dictionary with JMS Wilson coefficients but keys that might not be
in the non-redundant basis, return a dictionary with keys from the basis
and values conjugated if necessary.
def symmetrize_JMS_dict(C):
"""For a dictionary with JMS Wilson coefficients but keys that might not be
in the non-redund... |
Redefinition of all Wilson coefficients in the JMS basis when rotating
down-type quark fields from the flavour to the mass basis.
C_in is expected to be an array-valued dictionary containg a key
for all Wilson coefficient matrices.
def rotate_down(C_in, p):
"""Redefinition of all Wilson coefficients i... |
To account for the fact that arXiv:Jenkins:2017jig uses a flavour
non-redundant basis in contrast to WCxf, symmetry factors of two have to
be introduced in several places for operators that are symmetric
under the interchange of two currents.
def scale_dict_wet(C):
"""To account for the fact that arXiv... |
Undo the scaling applied in `scale_dict_wet`.
def unscale_dict_wet(C):
"""Undo the scaling applied in `scale_dict_wet`."""
return {k: _scale_dict[k] * v for k, v in C.items()} |
Args:
req_path:
req_list:
def write_reqs(req_path, req_list):
"""
Args:
req_path:
req_list:
"""
with open(req_path, 'w') as f:
f.write('\n'.join(req_list) + "\n") |
Run process locally.
For details, see
:meth:`~resolwe.flow.managers.workload_connectors.base.BaseConnector.submit`.
def submit(self, data, runtime_dir, argv):
"""Run process locally.
For details, see
:meth:`~resolwe.flow.managers.workload_connectors.base.BaseConnector.submit`.... |
Calculate the checksum of a stream.
Args:
f: file-like object
Only requirement is a ``read()`` method that returns ``bytes``.
algorithm: str
Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``.
Returns:
Populated Checksum PyXB object.
def create_checksum_object_from_stream(... |
Calculate the checksum of an iterator.
Args:
itr: iterable
Object which supports the iterator protocol.
algorithm: str
Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``.
Returns:
Populated Checksum PyXB object.
def create_checksum_object_from_iterator(
itr, algorithm=... |
Calculate the checksum of ``bytes``.
Warning:
This method requires the entire object to be buffered in (virtual) memory, which
should normally be avoided in production code.
Args:
b: bytes
Raw bytes
algorithm: str
Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``.
... |
Calculate the checksum of a stream.
Args:
f: file-like object
Only requirement is a ``read()`` method that returns ``bytes``.
algorithm: str
Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``.
chunk_size : int
Number of bytes to read from the file and add to the checksu... |
Calculate the checksum of an iterator.
Args:
itr: iterable
Object which supports the iterator protocol.
algorithm: str
Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``.
Returns:
str : Checksum as a hexadecimal string, with length decided by the algorithm.
def calculate_c... |
Calculate the checksum of ``bytes``.
Warning: This method requires the entire object to be buffered in (virtual) memory,
which should normally be avoided in production code.
Args:
b: bytes
Raw bytes
algorithm: str
Checksum algorithm, ``MD5`` or ``SHA1`` / ``SHA-1``.
Retur... |
Determine if checksums are equal.
Args:
checksum_a_pyxb, checksum_b_pyxb: PyXB Checksum objects to compare.
Returns:
bool
- **True**: The checksums contain the same hexadecimal values calculated with
the same algorithm. Identical checksums guarantee (for all practical
... |
Create string representation of a PyXB Checksum object.
Args:
PyXB Checksum object
Returns:
str : Combined hexadecimal value and algorithm name.
def format_checksum(checksum_pyxb):
"""Create string representation of a PyXB Checksum object.
Args:
PyXB Checksum object
Returns:
... |
Run the executor listener. This method never returns.
def handle(self, *args, **kwargs):
"""Run the executor listener. This method never returns."""
listener = ExecutorListener(redis_params=getattr(settings, 'FLOW_MANAGER', {}).get('REDIS_CONNECTION', {}))
def _killer(signum, frame):
... |
Apply projection from request context.
The passed dictionary may be mutated.
:param field: An instance of `Field` or `Serializer`
:type field: `Field` or `Serializer`
:param value: Dictionary to apply the projection to
:type value: dict
:param deep: Also process all deep projections
:type ... |
Apply projection.
def apply_projection(projection, value):
"""Apply projection."""
if isinstance(value, Sequence):
# Apply projection to each item in the list.
return [
apply_projection(projection, item)
for item in value
]
elif not isinstance(value, Mapping)... |
Create partitions.
def _create_partitions(self, instance, partitions):
"""Create partitions."""
for partition in partitions:
RelationPartition.objects.create(
relation=instance,
entity=partition['entity'],
label=partition.get('label', None),
... |
Create ``Relation`` object and add partitions of ``Entities``.
def create(self, validated_data):
"""Create ``Relation`` object and add partitions of ``Entities``."""
# `partitions` field is renamed to `relationpartition_set` based on source of nested serializer
partitions = validated_data.pop('... |
Update ``Relation``.
def update(self, instance, validated_data):
"""Update ``Relation``."""
# `partitions` field is renamed to `relationpartition_set` based on source of nested serializer
partitions = validated_data.pop('relationpartition_set', None)
with transaction.atomic():
... |
Display or save file like object.
def output(file_like_object, path, verbose=False):
"""Display or save file like object."""
if not path:
for line in file_like_object:
if verbose:
print_info(line.rstrip())
else:
print(line.rstrip())
else:
... |
Print the information in Unicode safe manner.
def _print_level(level, msg):
"""Print the information in Unicode safe manner."""
for l in str(msg.rstrip()).split("\n"):
print("{0:<9s}{1}".format(level, str(l))) |
Find the first line of process definition.
The first line of process definition is the line with a slug.
:param str fname: Path to filename with processes
:param string slug: process slug
:return: line where the process definiton starts
:rtype: int
def get_process_definition_start(fname, slug):
... |
Find processes in path.
:param str process_dir: Path to the directory where to search for processes
:param str base_source_uri: Base URL of the source code repository with process definitions
:return: Dictionary of processes where keys are URLs pointing to processes'
source code and values are processe... |
Register directives.
When sphinx loads the extension (= imports the extension module) it
also executes the setup() function. Setup is the way extension
informs Sphinx about everything that the extension enables: which
config_values are introduced, which custom nodes/directives/roles
and which event... |
Fill content into nodes.
:param string field_name: Field name of the field
:param field_name: Field body if the field
:type field_name: str or instance of docutils.nodes
:return: field instance filled with given name and body
:rtype: nodes.field
def make_field(self, field_name,... |
Fill the ``field`` into a properties list and return it.
:param dict field: the content of the property list to make
:return: field_list instance filled with given field
:rtype: nodes.field_list
def make_properties_list(self, field):
"""Fill the ``field`` into a properties list and ret... |
Generate a process definition header.
:param str slug: process' slug
:param str typ: process' type
:param str version: process' version
:param str source_uri: url to the process definition
:param str description: process' description
:param dict inputs: process' inputs
... |
Fill the content of process definiton node.
:param dict process: process data as given from yaml.load function
:return: process node
def make_process_node(self, process):
"""Fill the content of process definiton node.
:param dict process: process data as given from yaml.load function
... |
Create a list of process definitions.
def run(self):
"""Create a list of process definitions."""
config = self.state.document.settings.env.config
# Get all processes:
processes = get_processes(config.autoprocess_process_dir, config.autoprocess_source_base_url)
process_nodes = [... |
Create a category tree.
def run(self):
"""Create a category tree."""
config = self.state.document.settings.env.config
# Group processes by category
processes = get_processes(config.autoprocess_process_dir, config.autoprocess_source_base_url)
processes.sort(key=itemgetter('categ... |
Create a type list.
def run(self):
"""Create a type list."""
config = self.state.document.settings.env.config
# Group processes by category
processes = get_processes(config.autoprocess_process_dir, config.autoprocess_source_base_url)
processes.sort(key=itemgetter('type'))
... |
MNRead.get()
Retrieve the SciObj bytes and write them to a file or other stream.
Args:
file_stream: Open file-like object
Stream to which the SciObj bytes will be written.
pid: str
vendor_specific: dict
Custom HTTP headers to includ... |
Send an object synchronization request to the CN.
async def synchronize(self, pid, vendor_specific=None):
"""Send an object synchronization request to the CN."""
return await self._request_pyxb(
"post",
["synchronize", pid],
{},
mmp_dict={"pid": pid},
... |
Encode any datetime query parameters to ISO8601.
def _datetime_to_iso8601(self, query_dict):
"""Encode any datetime query parameters to ISO8601."""
return {
k: v if not isinstance(v, datetime.datetime) else v.isoformat()
for k, v in list(query_dict.items())
} |
Project outgoing native value.
def to_representation(self, value):
"""Project outgoing native value."""
value = apply_subfield_projection(self, value, deep=True)
return super().to_representation(value) |
CNRead.synchronize(session, pid) → boolean POST /synchronize.
Args: pid: vendorSpecific:
def synchronizeResponse(self, pid, vendorSpecific=None):
"""CNRead.synchronize(session, pid) → boolean POST /synchronize.
Args: pid: vendorSpecific:
"""
mmp_dict = {'pid': pid}
... |
See Also: synchronizeResponse() Args: pid: vendorSpecific:
Returns:
def synchronize(self, pid, vendorSpecific=None):
"""See Also: synchronizeResponse() Args: pid: vendorSpecific:
Returns:
"""
response = self.synchronizeResponse(pid, vendorSpecific)
return self._read_b... |
Command handle.
def handle(self, *args, **options):
"""Command handle."""
verbosity = int(options['verbosity'])
if self.has_filter(options):
self.filter_indices(options, verbosity)
else:
# Process all indices.
index_builder.build() |
Check if a BagIt file is valid.
Raises:
ServiceFailure
If the BagIt zip archive file fails any of the following checks:
- Is a valid zip file.
- The tag and manifest files are correctly formatted.
- Contains all the files listed in the manifests.
... |
Create a stream containing a BagIt zip archive.
Args:
dir_name : str
The name of the root directory in the zip file, under which all the files
are placed (avoids "zip bombs").
payload_info_list: list
List of payload_info_dict, each dict describing a file.
... |
Add a key with the path to each payload_info_dict.
def _add_path(dir_name, payload_info_list):
"""Add a key with the path to each payload_info_dict."""
for payload_info_dict in payload_info_list:
file_name = payload_info_dict['filename'] or payload_info_dict['pid']
payload_info_dict['path'] = d... |
Add the payload files to the zip.
def _add_payload_files(zip_file, payload_info_list):
"""Add the payload files to the zip."""
payload_byte_count = 0
payload_file_count = 0
for payload_info_dict in payload_info_list:
zip_file.write_iter(payload_info_dict['path'], payload_info_dict['iter'])
... |
Generate the tag files and add them to the zip.
def _add_tag_files(
zip_file, dir_name, payload_info_list, payload_byte_count, payload_file_count
):
"""Generate the tag files and add them to the zip."""
tag_info_list = []
_add_tag_file(zip_file, dir_name, tag_info_list, _gen_bagit_text_file_tup())
... |
Generate the manifest files and add them to the zip.
def _add_manifest_files(zip_file, dir_name, payload_info_list, tag_info_list):
"""Generate the manifest files and add them to the zip."""
for checksum_algorithm in _get_checksum_algorithm_set(payload_info_list):
_add_tag_file(
zip_file,
... |
Generate the tag manifest file and add it to the zip.
def _add_tag_manifest_file(zip_file, dir_name, tag_info_list):
"""Generate the tag manifest file and add it to the zip."""
_add_tag_file(
zip_file, dir_name, tag_info_list, _gen_tag_manifest_file_tup(tag_info_list)
) |
Add a tag file to zip_file and record info for the tag manifest file.
def _add_tag_file(zip_file, dir_name, tag_info_list, tag_tup):
"""Add a tag file to zip_file and record info for the tag manifest file."""
tag_name, tag_str = tag_tup
tag_path = d1_common.utils.filesystem.gen_safe_path(dir_name, tag_name... |
Command handle.
def handle(self, *args, **options):
"""Command handle."""
verbosity = int(options['verbosity'])
skip_mapping = options['skip_mapping']
if self.has_filter(options):
self.filter_indices(options, verbosity, skip_mapping=skip_mapping)
else:
#... |
Returns:
dict : Representation of ``node_list_pyxb``, keyed on the Node identifier
(``urn:node:*``).
Example::
{
u'urn:node:ARCTIC': {
'base_url': u'https://arcticdata.io/metacat/d1/mn',
'description': u'The US National Science Foundation...',
'name': u'Arctic Data Center... |
Filter permissions queryset.
def filter_queryset(self, request, queryset, view):
"""Filter permissions queryset."""
user = request.user
app_label = queryset.model._meta.app_label # pylint: disable=protected-access
model_name = queryset.model._meta.model_name # pylint: disable=protect... |
Check object permissions.
def has_object_permission(self, request, view, obj):
"""Check object permissions."""
# admins can do anything
if request.user.is_superuser:
return True
# `share` permission is required for editing permissions
if 'permissions' in view.action... |
Get a set containing all subjects for which the current connection has been
successfully authenticated.
def get_active_subject_set(self, request):
"""Get a set containing all subjects for which the current connection has been
successfully authenticated."""
# Handle complete certificate ... |
Set up logging.
We output only to stdout. Instead of also writing to a log file, redirect stdout to
a log file when the script is executed from cron.
def log_setup(debug_bool):
"""Set up logging.
We output only to stdout. Instead of also writing to a log file, redirect stdout to
a log file when t... |
Connect to DB.
dbname: the database name user: user name used to authenticate password:
password used to authenticate host: database host address (defaults to UNIX
socket if not provided) port: connection port number (defaults to 5432 if not
provided)
def connect(self, dsn):
""... |
Get query parameter uniformly for GET and POST requests.
def get_query_param(self, key, default=None):
"""Get query parameter uniformly for GET and POST requests."""
value = self.request.query_params.get(key, None)
if value is None:
value = self.request.data.get(key, None)
i... |
Get combined query parameters (GET and POST).
def get_query_params(self):
"""Get combined query parameters (GET and POST)."""
params = self.request.query_params.copy()
params.update(self.request.data)
return params |
Order given search by the ordering parameter given in request.
:param search: ElasticSearch query object
def order_search(self, search):
"""Order given search by the ordering parameter given in request.
:param search: ElasticSearch query object
"""
ordering = self.get_query_p... |
Filter given search by the filter parameter given in request.
:param search: ElasticSearch query object
def filter_search(self, search):
"""Filter given search by the filter parameter given in request.
:param search: ElasticSearch query object
"""
builder = QueryBuilder(
... |
Filter given query based on permissions of the user in the request.
:param search: ElasticSearch query object
def filter_permissions(self, search):
"""Filter given query based on permissions of the user in the request.
:param search: ElasticSearch query object
"""
user = self... |
Optionally return paginated response.
If pagination parameters are provided in the request, then paginated response
is returned, otherwise response is not paginated.
def paginate_response(self, queryset, serializers_kwargs={}):
"""Optionally return paginated response.
If pagination pa... |
Handle the search request.
def search(self):
"""Handle the search request."""
search = self.document_class().search() # pylint: disable=not-callable
search = self.custom_filter(search)
search = self.filter_search(search)
search = self.order_search(search)
search = sel... |
Endpoint handler.
def list_with_post(self, request):
"""Endpoint handler."""
if self.is_search_request():
search = self.search()
page = self.paginate_queryset(search)
if page is None:
items = search
else:
items = page
... |
Called by FUSE when the attributes for a file or directory are required.
Returns a dictionary with keys identical to the stat C structure of stat(2).
st_atime, st_mtime and st_ctime should be floats. On OSX, st_nlink should count
all files inside the directory. On Linux, only the subdirectories... |
Called by FUSE when a directory is opened.
Returns a list of file and directory names for the directory.
def readdir(self, path, fh):
"""Called by FUSE when a directory is opened.
Returns a list of file and directory names for the directory.
"""
log.debug('readdir(): {}'.form... |
Called by FUSE when a file is opened.
Determines if the provided path and open flags are valid.
def open(self, path, flags):
"""Called by FUSE when a file is opened.
Determines if the provided path and open flags are valid.
"""
log.debug('open(): {}'.format(path))
# O... |
Extract an inline expression from the given text.
def get_inline_expression(self, text):
"""Extract an inline expression from the given text."""
text = text.strip()
if not text.startswith(self.inline_tags[0]) or not text.endswith(self.inline_tags[1]):
return
return text[2:-... |
Filter queryset by entity, label and position.
Due to a bug in django-filter these filters have to be applied
manually:
https://github.com/carltongibson/django-filter/issues/883
def _filter_queryset(self, queryset):
"""Filter queryset by entity, label and position.
Due to a bu... |
Update the ``Relation`` object.
Reject the update if user doesn't have ``EDIT`` permission on
the collection referenced in the ``Relation``.
def update(self, request, *args, **kwargs):
"""Update the ``Relation`` object.
Reject the update if user doesn't have ``EDIT`` permission on
... |
Rebuild indexes affected by the given permission.
def _process_permission(perm):
"""Rebuild indexes affected by the given permission."""
# XXX: Optimize: rebuild only permissions, not whole document
codename = perm.permission.codename
if not codename.startswith('view') and not codename.startswith('owne... |
Parse a multipart Requests.Response into a tuple of BodyPart objects.
Args:
response: Requests.Response
encoding:
The parser will assume that any text in the HTML body is encoded with this
encoding when decoding it for use in the ``text`` attribute.
Returns:
tuple of BodyPar... |
Parse multipart document bytes into a tuple of BodyPart objects.
Args:
mmp_bytes: bytes
Multipart document.
content_type : str
Must be on the form, ``multipart/form-data; boundary=<BOUNDARY>``, where
``<BOUNDARY>`` is the string that separates the parts of the multipart documen... |
Normalize a tuple of BodyPart objects to a string.
Normalization is done by sorting the body_parts by the Content- Disposition headers,
which is typically on the form, ``form-data; name="name_of_part``.
def normalize(body_part_tup,):
"""Normalize a tuple of BodyPart objects to a string.
Normalization... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.