INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Called when filepath is not defined in the settings
def build_default_filepath(self): '''Called when 'filepath' is not defined in the settings''' return os.path.join( self.app_config.name, 'scripts', self.template_relpath + '.js', )
Mako tag to include a Django template withing the current DMP ( Mako ) template. Since this is a Django template it is search for using the Django search algorithm ( instead of the DMP app - based concept ). See https:// docs. djangoproject. com/ en/ 2. 1/ topics/ templates/.
def django_include(context, template_name, **kwargs): ''' Mako tag to include a Django template withing the current DMP (Mako) template. Since this is a Django template, it is search for using the Django search algorithm (instead of the DMP app-based concept). See https://docs.djangoproject.com/en/2...
Internal method to toggle autoescaping on or off. This function needs access to the caller so the calling method must be decorated with
def _toggle_autoescape(context, escape_on=True): ''' Internal method to toggle autoescaping on or off. This function needs access to the caller, so the calling method must be decorated with @supports_caller. ''' previous = is_autoescape(context) setattr(context.caller_stack, AUTOESCAPE_KEY, ...
Returns a relative path but only if it doesn t start with a non - pretty parent directory..
def pretty_relpath(path, start): ''' Returns a relative path, but only if it doesn't start with a non-pretty parent directory ".." ''' relpath = os.path.relpath(path, start) if relpath.startswith('..'): return path return relpath
Returns True if the given function is decorated with
def is_decorated(cls, f): '''Returns True if the given function is decorated with @view_function''' real_func = inspect.unwrap(f) return real_func in cls.DECORATED_FUNCTIONS
Initializes the providers ( called from dmp app ready () )
def initialize_providers(cls): '''Initializes the providers (called from dmp app ready())''' dmp = apps.get_app_config('django_mako_plus') # regular content providers cls.CONTENT_PROVIDERS = [] for provider_settings in dmp.options[cls.SETTINGS_KEY]: # import the class...
Performs the run through the templates and their providers
def run(self): '''Performs the run through the templates and their providers''' for tpl in self.templates: for provider in tpl.providers: provider.provide()
Provider instances use this to write to the buffer
def write(self, content): '''Provider instances use this to write to the buffer''' self.buffer.write(content) if settings.DEBUG: self.buffer.write('\n')
Triggered by view_function. _sort_converters when our sort key should be created. This can t be called in the constructor because Django models might not be ready yet.
def prepare_sort_key(self): ''' Triggered by view_function._sort_converters when our sort key should be created. This can't be called in the constructor because Django models might not be ready yet. ''' if isinstance(self.convert_type, str): try: app_n...
Returns the command to run as a list ( see subprocess module )
def build_command(self): '''Returns the command to run, as a list (see subprocess module)''' # if defined in settings, run the function or return the string if self.options['command']: return self.options['command'](self) if callable(self.options['command']) else self.options['comman...
Returns True if self. sourcepath is newer than self. targetpath
def needs_compile(self): '''Returns True if self.sourcepath is newer than self.targetpath''' try: source_mtime = os.stat(self.sourcepath).st_mtime except OSError: # no source for this template, so just return return False try: target_mtime = os.stat(s...
Generator that iterates the template and its ancestors. The order is from most specialized ( furthest descendant ) to most general ( furthest ancestor ).
def template_inheritance(obj): ''' Generator that iterates the template and its ancestors. The order is from most specialized (furthest descendant) to most general (furthest ancestor). obj can be either: 1. Mako Template object 2. Mako `self` object (available within a rendering tem...
This structure is what Django wants when errors occur in templates. It gives the user a nice stack trace in the error page during debug.
def get_template_debug(template_name, error): ''' This structure is what Django wants when errors occur in templates. It gives the user a nice stack trace in the error page during debug. ''' # This is taken from mako.exceptions.html_error_template(), which has an issue # in Py3 where files get l...
Returns the name of this template ( if created from a file ) or string if not
def name(self): '''Returns the name of this template (if created from a file) or "string" if not''' if self.mako_template.filename: return os.path.basename(self.mako_template.filename) return 'string'
Renders a template using the Mako system. This method signature conforms to the Django template API which specifies that template. render () returns a string.
def render(self, context=None, request=None, def_name=None): ''' Renders a template using the Mako system. This method signature conforms to the Django template API, which specifies that template.render() returns a string. @context A dictionary of name=value variables to send to t...
Renders the template and returns an HttpRequest object containing its content.
def render_to_response(self, context=None, request=None, def_name=None, content_type=None, status=None, charset=None): ''' Renders the template and returns an HttpRequest object containing its content. This method returns a django.http.Http404 exception if the template is not found. If ...
Retrieves the given parser action object by its dest = attribute
def get_action_by_dest(self, parser, dest): '''Retrieves the given parser action object by its dest= attribute''' for action in parser._actions: if action.dest == dest: return action return None
Placing this in execute because then subclass handle () don t have to call super
def execute(self, *args, **options): '''Placing this in execute because then subclass handle() don't have to call super''' if options['verbose']: options['verbosity'] = 3 if options['quiet']: options['verbosity'] = 0 self.verbosity = options.get('verbosity', 1) ...
Print a message to the console
def message(self, msg='', level=1, tab=0): '''Print a message to the console''' if self.verbosity >= level: self.stdout.write('{}{}'.format(' ' * tab, msg))
Encodes a UID to an 11 - length string encoded using base58 url - safe alphabet
def b58enc(uid): '''Encodes a UID to an 11-length string, encoded using base58 url-safe alphabet''' # note: i tested a buffer array too, but string concat was 2x faster if not isinstance(uid, int): raise ValueError('Invalid integer: {}'.format(uid)) if uid == 0: return BASE58CHARS[0] ...
Decodes a UID from base58 url - safe alphabet back to int.
def b58dec(enc_uid): '''Decodes a UID from base58, url-safe alphabet back to int.''' if isinstance(enc_uid, str): pass elif isinstance(enc_uid, bytes): enc_uid = enc_uid.decode('utf8') else: raise ValueError('Cannot decode this type: {}'.format(enc_uid)) uid = 0 try: ...
Minifies the source text ( if needed )
def minify(text, minifier): '''Minifies the source text (if needed)''' # there really isn't a good way to know if a file is already minified. # our heuristic is if source is more than 50 bytes greater of dest OR # if a hard return is found in the first 50 chars, we assume it is not minified. minifie...
Returns the result score if the file matches this rule
def match(self, fname, flevel, ftype): '''Returns the result score if the file matches this rule''' # if filetype is the same # and level isn't set or level is the same # and pattern matche the filename if self.filetype == ftype and (self.level is None or self.level == flevel) an...
Adds rules for the command line options
def create_rules(self): '''Adds rules for the command line options''' dmp = apps.get_app_config('django_mako_plus') # the default rules = [ # files are included by default Rule('*', level=None, filetype=TYPE_FILE, score=1), ...
Copies the static files from one directory to another. If this command is run we assume the user wants to overwrite any existing files.
def copy_dir(self, source, dest, level=0): '''Copies the static files from one directory to another. If this command is run, we assume the user wants to overwrite any existing files.''' encoding = settings.DEFAULT_CHARSET or 'utf8' msglevel = 2 if level == 0 else 3 self.message('Directo...
Includes a DMP ( Mako ) template into a normal django template.
def dmp_include(context, template_name, def_name=None, **kwargs): ''' Includes a DMP (Mako) template into a normal django template. context: automatically provided template_name: specified as "app/template" def_name: optional block to render within the template Example: {...
App - specific render function that renders templates in the * current app * attached to the request for convenience
def render(self, template, context=None, def_name=None, subdir='templates', content_type=None, status=None, charset=None): '''App-specific render function that renders templates in the *current app*, attached to the request for convenience''' template_adapter = self.get_template_loader(subdir).get_templ...
App - specific render function that renders templates in the * current app * attached to the request for convenience
def render_to_string(self, template, context=None, def_name=None, subdir='templates'): '''App-specific render function that renders templates in the *current app*, attached to the request for convenience''' template_adapter = self.get_template_loader(subdir).get_template(template) return getattr...
App - specific function to get the current app s template loader
def get_template_loader(self, subdir='templates'): '''App-specific function to get the current app's template loader''' if self.request is None: raise ValueError("this method can only be called after the view middleware is run. Check that `django_mako_plus.middleware` is in MIDDLEWARE.") ...
Called by Django when the app is ready for use.
def ready(self): '''Called by Django when the app is ready for use.''' # set up the options self.options = {} self.options.update(DEFAULT_OPTIONS) for template_engine in settings.TEMPLATES: if template_engine.get('BACKEND', '').startswith('django_mako_plus'): ...
Registers an app as a DMP - enabled app. Normally DMP does this automatically when included in urls. py.
def register_app(self, app=None): ''' Registers an app as a "DMP-enabled" app. Normally, DMP does this automatically when included in urls.py. If app is None, the DEFAULT_APP is registered. ''' app = app or self.options['DEFAULT_APP'] if not app: rai...
Returns true if the given app/ app name is registered with DMP
def is_registered_app(self, app): '''Returns true if the given app/app name is registered with DMP''' if app is None: return False if isinstance(app, AppConfig): app = app.name return app in self.registered_apps
Returns the element at idx or default if idx is beyond the length of the list
def get(self, idx, default=''): '''Returns the element at idx, or default if idx is beyond the length of the list''' # if the index is beyond the length of the list, return '' if isinstance(idx, int) and (idx >= len(self) or idx < -1 * len(self)): return default # else do the...
Converts to int or float: - None convert to parameter default Anything else uses int () or float () constructor
def convert_int(value, parameter): ''' Converts to int or float: '', '-', None convert to parameter default Anything else uses int() or float() constructor ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or isinstance(value, int): return value...
Converts to int or float: - None convert to parameter default Anything else uses int () or float () constructor
def convert_float(value, parameter): ''' Converts to int or float: '', '-', None convert to parameter default Anything else uses int() or float() constructor ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or isinstance(value, float): return v...
Converts to decimal. Decimal: - None convert to parameter default Anything else uses Decimal constructor
def convert_decimal(value, parameter): ''' Converts to decimal.Decimal: '', '-', None convert to parameter default Anything else uses Decimal constructor ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or isinstance(value, decimal.Decimal): re...
Converts to boolean ( only the first char of the value is used ): - None convert to parameter default f F 0 False always convert to False Anything else converts to True.
def convert_boolean(value, parameter, default=False): ''' Converts to boolean (only the first char of the value is used): '', '-', None convert to parameter default 'f', 'F', '0', False always convert to False Anything else converts to True. ''' value = _check_default(value, para...
Converts to datetime. datetime: - None convert to parameter default The first matching format in settings. DATETIME_INPUT_FORMATS converts to datetime
def convert_datetime(value, parameter): ''' Converts to datetime.datetime: '', '-', None convert to parameter default The first matching format in settings.DATETIME_INPUT_FORMATS converts to datetime ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or ...
Converts to datetime. date: - None convert to parameter default The first matching format in settings. DATE_INPUT_FORMATS converts to datetime
def convert_date(value, parameter): ''' Converts to datetime.date: '', '-', None convert to parameter default The first matching format in settings.DATE_INPUT_FORMATS converts to datetime ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or isinstance(v...
Converts to a Model object. - 0 None convert to parameter default Anything else is assumed an object id and sent to. get ( id = value ).
def convert_id_to_model(value, parameter): ''' Converts to a Model object. '', '-', '0', None convert to parameter default Anything else is assumed an object id and sent to `.get(id=value)`. ''' value = _check_default(value, parameter, ( '', '-', '0', None )) if isinstance(value, (in...
Returns the default if the value is empty
def _check_default(value, parameter, default_chars): '''Returns the default if the value is "empty"''' # not using a set here because it fails when value is unhashable if value in default_chars: if parameter.default is inspect.Parameter.empty: raise ValueError('Value was empty, but no de...
Decorator that denotes a function as a url parameter converter.
def parameter_converter(*convert_types): ''' Decorator that denotes a function as a url parameter converter. ''' def inner(func): for ct in convert_types: ParameterConverter._register_converter(func, ct) return func return inner
Run all the stages in protocol
def protocol(handler, cfg): """ Run all the stages in protocol Parameters ---------- handler : SystemHandler Container of initial conditions of simulation cfg : dict Imported YAML file. """ # Stages if 'stages' not in cfg: raise ValueError('Protocol must inc...
Launch MD simulation which may consist of: 1. Optional minimization 2. Actual MD simulation with n steps.
def run(self): """ Launch MD simulation, which may consist of: 1. Optional minimization 2. Actual MD simulation, with n steps. This method also handles reporters. Returns ------- positions, velocities : unit.Quantity([natoms, 3]) Position, ve...
Minimize energy of the system until meeting tolerance or performing max_iterations.
def minimize(self, tolerance=None, max_iterations=None): """ Minimize energy of the system until meeting `tolerance` or performing `max_iterations`. """ if tolerance is None: tolerance = self.minimization_tolerance if max_iterations is None: max_it...
Advance simulation n steps
def simulate(self, steps=None): """ Advance simulation n steps """ if steps is None: steps = self.steps self.simulation.step(steps)
Force that restrains atoms to fix their positions while allowing tiny movement to resolve severe clashes and so on.
def restraint_force(self, indices=None, strength=5.0): """ Force that restrains atoms to fix their positions, while allowing tiny movement to resolve severe clashes and so on. Returns ------- force : simtk.openmm.CustomExternalForce A custom force to restrain...
Parameters ---------- atoms: tuple of tuple of int or str Pair of atom indices to be restrained with shape ( n 2 ) like (( a1 a2 ) ( a3 a4 )). Items can be str compatible with MDTraj DSL. distances: tuple of float Equilibrium distances for each pair strengths: tuple of float Force constant for each pair
def distance_restraint_force(self, atoms, distances, strengths): """ Parameters ---------- atoms : tuple of tuple of int or str Pair of atom indices to be restrained, with shape (n, 2), like ((a1, a2), (a3, a4)). Items can be str compatible with MDTraj DSL. ...
Returns a list of atom indices corresponding to a MDTraj DSL query. Also will accept list of numbers which will be coerced to int and returned.
def subset(self, selector): """ Returns a list of atom indices corresponding to a MDTraj DSL query. Also will accept list of numbers, which will be coerced to int and returned. """ if isinstance(selector, (list, tuple)): return map(int, selector) selec...
Handle Ctrl + C and accidental exceptions and attempt to save the current state of the simulation
def handle_exceptions(self, verbose=True): """ Handle Ctrl+C and accidental exceptions and attempt to save the current state of the simulation """ try: yield except (KeyboardInterrupt, Exception) as ex: if not self.attempt_rescue: r...
Creates an emergency report run. state included
def backup_simulation(self): """ Creates an emergency report run, .state included """ path = self.new_filename(suffix='_emergency.state') self.simulation.saveState(path) uses_pbc = self.system.usesPeriodicBoundaryConditions() state_kw = dict(getPositions=True, get...
Get parse and prepare input file.
def prepare_input(argv=None): """ Get, parse and prepare input file. """ p = ArgumentParser(description='InsiliChem Ommprotocol: ' 'easy to deploy MD protocols for OpenMM') p.add_argument('input', metavar='INPUT FILE', type=extant_file, help='YAML input file...
Load all files into single object.
def prepare_handler(cfg): """ Load all files into single object. """ positions, velocities, box = None, None, None _path = cfg.get('_path', './') forcefield = cfg.pop('forcefield', None) topology_args = sanitize_args_for_file(cfg.pop('topology'), _path) if 'checkpoint' in cfg: r...
Retrieve and delete ( pop ) system options from input configuration.
def prepare_system_options(cfg, defaults=None): """ Retrieve and delete (pop) system options from input configuration. """ d = {} if defaults is None else defaults.copy() if 'nonbondedMethod' in cfg: d['nonbondedMethod'] = warned_getattr(openmm_app, cfg.pop('nonbondedMethod'), None) if '...
Given a list of filenames check which ones are frcmods. If so convert them to ffxml. Else just return them.
def process_forcefield(*forcefields): """ Given a list of filenames, check which ones are `frcmods`. If so, convert them to ffxml. Else, just return them. """ for forcefield in forcefields: if forcefield.endswith('.frcmod'): gaffmol2 = os.path.splitext(forcefield)[0] + '.gaff.mol...
Given an OpenMM xml file containing the state of the simulation generate a PDB snapshot for easy visualization.
def statexml2pdb(topology, state, output=None): """ Given an OpenMM xml file containing the state of the simulation, generate a PDB snapshot for easy visualization. """ state = Restart.from_xml(state) system = SystemHandler.load(topology, positions=state.positions) if output is None: ...
Extract a single frame structure from a trajectory.
def export_frame_coordinates(topology, trajectory, nframe, output=None): """ Extract a single frame structure from a trajectory. """ if output is None: basename, ext = os.path.splitext(trajectory) output = '{}.frame{}.inpcrd'.format(basename, nframe) # ParmEd sometimes struggles wit...
Include file referenced at node.
def construct_include(self, node): """Include file referenced at node.""" filename = os.path.join(self._root, self.construct_scalar(node)) filename = os.path.abspath(filename) extension = os.path.splitext(filename)[1].lstrip('.') with open(filename, 'r') as f: if ex...
Loads topology positions and potentially velocities and vectors from a PDB or PDBx file
def from_pdb(cls, path, forcefield=None, loader=PDBFile, strict=True, **kwargs): """ Loads topology, positions and, potentially, velocities and vectors, from a PDB or PDBx file Parameters ---------- path : str Path to PDB/PDBx file forcefields : list ...
Loads Amber Parm7 parameters and topology file
def from_amber(cls, path, positions=None, strict=True, **kwargs): """ Loads Amber Parm7 parameters and topology file Parameters ---------- path : str Path to *.prmtop or *.top file positions : simtk.unit.Quantity Atomic positions Returns ...
Loads PSF Charmm structure from path. Requires charmm_parameters.
def from_charmm(cls, path, positions=None, forcefield=None, strict=True, **kwargs): """ Loads PSF Charmm structure from `path`. Requires `charmm_parameters`. Parameters ---------- path : str Path to PSF file forcefield : list of str Paths to Charm...
Loads a topology from a Desmond DMS file located at path.
def from_desmond(cls, path, **kwargs): """ Loads a topology from a Desmond DMS file located at `path`. Arguments --------- path : str Path to a Desmond DMS file """ dms = DesmondDMSFile(path) pos = kwargs.pop('positions', dms.getPositions()) ...
Loads a topology from a Gromacs TOP file located at path.
def from_gromacs(cls, path, positions=None, forcefield=None, strict=True, **kwargs): """ Loads a topology from a Gromacs TOP file located at `path`. Additional root directory for parameters can be specified with `forcefield`. Arguments --------- path : str P...
Try to load a file automatically with ParmEd. Not guaranteed to work but might be useful if it succeeds.
def from_parmed(cls, path, *args, **kwargs): """ Try to load a file automatically with ParmEd. Not guaranteed to work, but might be useful if it succeeds. Arguments --------- path : str Path to file that ParmEd can load """ st = parmed.load_fi...
Loads pickled topology. Careful with Python versions though!
def _pickle_load(path): """ Loads pickled topology. Careful with Python versions though! """ _, ext = os.path.splitext(path) topology = None if sys.version_info.major == 2: if ext == '.pickle2': with open(path, 'rb') as f: t...
Create an OpenMM system for every supported topology file with given system options
def create_system(self, **system_options): """ Create an OpenMM system for every supported topology file with given system options """ if self.master is None: raise ValueError('Handler {} is not able to create systems.'.format(self)) if isinstance(self.master, ForceF...
Outputs a PDB file with the current contents of the system
def write_pdb(self, path): """ Outputs a PDB file with the current contents of the system """ if self.master is None and self.positions is None: raise ValueError('Topology and positions are needed to write output files.') with open(path, 'w') as f: PDBFile...
Returns u. Quantity with box vectors from XSC file
def from_xsc(cls, path): """ Returns u.Quantity with box vectors from XSC file """ def parse(path): """ Open and parses an XSC file into its fields Parameters ---------- path : str Path to XSC file Returns ...
Get box vectors from comma - separated values in file path.
def from_csv(cls, path): """ Get box vectors from comma-separated values in file `path`. The csv file must containt only one line, which in turn can contain three values (orthogonal vectors) or nine values (triclinic box). The values should be in nanometers. Parameters...
Get information about the next report this object will generate.
def describeNextReport(self, simulation): """Get information about the next report this object will generate. Parameters ---------- simulation : Simulation The Simulation to generate a report for Returns ------- tuple A five element tuple...
Generate a report.
def report(self, simulation, state): """Generate a report. Parameters ---------- simulation : Simulation The Simulation to generate a report for state : State The current state of the simulation """ if not self._initialized: se...
Generate a report.
def report(self, simulation, state): """Generate a report. Parameters ---------- simulation : Simulation The Simulation to generate a report for state : State The current state of the simulation """ if not self._initialized: se...
If path exists modify to add a counter in the filename. Useful for preventing accidental overrides. For example if file. txt exists check if file. 1. txt also exists. Repeat until we find a non - existing version such as file. 12. txt.
def assert_not_exists(path, sep='.'): """ If path exists, modify to add a counter in the filename. Useful for preventing accidental overrides. For example, if `file.txt` exists, check if `file.1.txt` also exists. Repeat until we find a non-existing version, such as `file.12.txt`. Parameters ...
Make sure object obj is of type types. Else raise TypeError.
def assertinstance(obj, types): """ Make sure object `obj` is of type `types`. Else, raise TypeError. """ if isinstance(obj, types): return obj raise TypeError('{} must be instance of {}'.format(obj, types))
Check if file exists with argparse
def extant_file(path): """ Check if file exists with argparse """ if not os.path.exists(path): raise argparse.ArgumentTypeError("{} does not exist".format(path)) return path
Sort files taking into account potentially absent suffixes like somefile. dcd somefile. 1000. dcd somefile. 2000. dcd
def sort_key_for_numeric_suffixes(path, sep='.', suffix_index=-2): """ Sort files taking into account potentially absent suffixes like somefile.dcd somefile.1000.dcd somefile.2000.dcd To be used with sorted(..., key=callable). """ chunks = path.split(sep) # Remove suffix...
Wrap a view in JSON.
def json_response(f, *args, **kwargs): """Wrap a view in JSON. This decorator runs the given function and looks out for ajax.AJAXError's, which it encodes into a proper HttpResponse object. If an unknown error is thrown it's encoded as a 500. All errors are then packaged up with an appropriate Con...
Import a dotted module path and return the attribute/ class designated by the last name in the path. Raise ImproperlyConfigured if something goes wrong. This has come straight from Django 1. 6
def import_by_path(dotted_path, error_prefix=''): """ Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImproperlyConfigured if something goes wrong. This has come straight from Django 1.6 """ try: module_path, class_name = dotted_p...
Load an AJAX endpoint.
def endpoint_loader(request, application, model, **kwargs): """Load an AJAX endpoint. This will load either an ad-hoc endpoint or it will load up a model endpoint depending on what it finds. It first attempts to load ``model`` as if it were an ad-hoc endpoint. Alternatively, it will attempt to see if ...
List objects of a model. By default will show page 1 with 20 objects on it.
def list(self, request): """ List objects of a model. By default will show page 1 with 20 objects on it. **Usage**:: params = {"items_per_page":10,"page":2} //all params are optional $.post("/ajax/{app}/{model}/list.json"),params) """ max_items_per_pag...
Extract data from POST.
def _extract_data(self, request): """Extract data from POST. Handles extracting a vanilla Python dict of values that are present in the given model. This also handles instances of ``ForeignKey`` and will convert those to the appropriate object instances from the database. In oth...
If the value is true/ false/ null replace with Python equivalent.
def _extract_value(self, value): """If the value is true/false/null replace with Python equivalent.""" return ModelEndpoint._value_map.get(smart_str(value).lower(), value)
Fetch a given record.
def _get_record(self): """Fetch a given record. Handles fetching a record from the database along with throwing an appropriate instance of ``AJAXError`. """ if not self.pk: raise AJAXError(400, _('Invalid request for record.')) try: return self.m...
Authenticate the AJAX request.
def authenticate(self, request, application, method): """Authenticate the AJAX request. By default any request to fetch a model is allowed for any user, including anonymous users. All other methods minimally require that the user is already logged in. Most likely you will want ...
Gets all entries of a space.
def all(self, query=None): """ Gets all entries of a space. """ if query is None: query = {} if self.content_type_id is not None: query['content_type'] = self.content_type_id normalize_select(query) return super(EntriesProxy, self).all(...
Gets a single entry by ID.
def find(self, entry_id, query=None): """ Gets a single entry by ID. """ if query is None: query = {} if self.content_type_id is not None: query['content_type'] = self.content_type_id normalize_select(query) return super(EntriesProxy, s...
Creates an entry with a given ID ( optional ) and attributes.
def create(self, resource_id=None, attributes=None, **kwargs): """ Creates an entry with a given ID (optional) and attributes. """ if self.content_type_id is not None: if attributes is None: attributes = {} attributes['content_type_id'] = self.con...
Creates a webhook with given attributes.
def create(self, attributes=None, **kwargs): """ Creates a webhook with given attributes. """ return super(WebhooksProxy, self).create(resource_id=None, attributes=attributes)
Returns a camel - cased version of a string.
def camel_case(snake_str): """ Returns a camel-cased version of a string. :param a_string: any :class:`str` object. Usage: >>> camel_case('foo_bar') "fooBar" """ components = snake_str.split('_') # We capitalize the first letter of each component except the first one #...
If the query contains the: select operator we enforce: sys properties. The SDK requires sys. type to function properly but as other of our SDKs require more parts of the: sys properties we decided that every SDK should include the complete: sys block to provide consistency accross our SDKs.
def normalize_select(query): """ If the query contains the :select operator, we enforce :sys properties. The SDK requires sys.type to function properly, but as other of our SDKs require more parts of the :sys properties, we decided that every SDK should include the complete :sys block to provide con...
Returns the JSON representation of the environment.
def to_json(self): """ Returns the JSON representation of the environment. """ result = super(Environment, self).to_json() result.update({ 'name': self.name }) return result
Provides access to content type management methods for content types of an environment.
def content_types(self): """ Provides access to content type management methods for content types of an environment. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/content-types :return: :class:`EnvironmentContentTypesProxy <cont...
Provides access to entry management methods.
def entries(self): """ Provides access to entry management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/entries :return: :class:`EnvironmentEntriesProxy <contentful_management.environment_entries_proxy.EnvironmentEntri...
Provides access to asset management methods.
def assets(self): """ Provides access to asset management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/assets :return: :class:`EnvironmentAssetsProxy <contentful_management.environment_assets_proxy.EnvironmentAssetsPro...
Provides access to locale management methods.
def locales(self): """ Provides access to locale management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/locales :return: :class:`EnvironmentLocalesProxy <contentful_management.environment_locales_proxy.EnvironmentLoca...
Provides access to UI extensions management methods.
def ui_extensions(self): """ Provides access to UI extensions management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/ui-extensions :return: :class:`EnvironmentUIExtensionsProxy <contentful_management.ui_extensions_pro...
Revokes a personal access token.
def delete(self, token_id, *args, **kwargs): """ Revokes a personal access token. """ return self.client._put( "{0}/revoked".format( self._url(token_id) ), None, *args, **kwargs )
Revokes a personal access token.
def revoke(self, token_id, *args, **kwargs): """ Revokes a personal access token. """ return self.delete(token_id, *args, **kwargs)
Returns the URI for the resource.
def base_url(klass, space_id='', resource_id=None, environment_id=None, **kwargs): """ Returns the URI for the resource. """ url = "spaces/{0}".format( space_id) if environment_id is not None: url = url = "{0}/environments/{1}".format(url, environment_id...
Attributes for resource creation.
def create_attributes(klass, attributes, previous_object=None): """ Attributes for resource creation. """ result = {} if previous_object is not None: result = {k: v for k, v in previous_object.to_json().items() if k != 'sys'} result.update(attributes) ...