INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Validate the keys provided are authentic credentials.
def validate_keys(self): """ Validate the keys provided are authentic credentials. """ url = 'https://api.twitter.com/1.1/account/verify_credentials.json' keys_present = self.consumer_key and self.consumer_secret and \ self.access_token and self.access_tok...
Get the command line argument parser.
def get_argparser(): """ Get the command line argument parser. """ parser = argparse.ArgumentParser("twarc") parser.add_argument('command', choices=commands) parser.add_argument('query', nargs='?', default=None) parser.add_argument("--log", dest="log", default="twarc...
kwargs holds initial dynaconf configuration
def init_app(self, app, **kwargs): """kwargs holds initial dynaconf configuration""" self.kwargs.update(kwargs) self.settings = self.dynaconf_instance or LazySettings(**self.kwargs) app.config = self.make_config(app) app.dynaconf = self.settings
Gets config from dynaconf variables if variables does not exists in dynaconf try getting from `app.config` to support runtime settings.
def get(self, key, default=None): """Gets config from dynaconf variables if variables does not exists in dynaconf try getting from `app.config` to support runtime settings.""" return self._settings.get(key, Config.get(self, key, default))
Recursively merge two data structures. :param unique: When set to True existing list items are not set.
def object_merge(old, new, unique=False): """ Recursively merge two data structures. :param unique: When set to True existing list items are not set. """ if isinstance(old, list) and isinstance(new, list): if old == new: return for item in old[::-1]: if uniqu...
To keep backwards compat change the kwargs to new names
def compat_kwargs(kwargs): """To keep backwards compat change the kwargs to new names""" warn_deprecations(kwargs) for old, new in RENAMED_VARS.items(): if old in kwargs: kwargs[new] = kwargs[old] # update cross references for c_old, c_new in RENAMED_VARS.items():...
Rebuild `list_object` removing duplicated and keeping order
def deduplicate(list_object): """Rebuild `list_object` removing duplicated and keeping order""" new = [] for item in list_object: if item not in new: new.append(item) return new
Given a string s, split is by one of one of the seps.
def trimmed_split(s, seps=(";", ",")): """Given a string s, split is by one of one of the seps.""" for sep in seps: if sep not in s: continue data = [item.strip() for item in s.strip().split(sep)] return data return [s]
Ensure data is a list or wrap it in a list
def ensure_a_list(data): """Ensure data is a list or wrap it in a list""" if not data: return [] if isinstance(data, (list, tuple, set)): return list(data) if isinstance(data, str): data = trimmed_split(data) # settings.toml,other.yaml return data return [data]
Reads and loads in to "obj" a single key or all keys from source file. :param obj: the settings instance :param env: settings current env default='development' :param silent: if errors should raise :param key: if defined load a single key, else load all in env :param filename: Optional custom filen...
def load(obj, env=None, silent=True, key=None, filename=None): """ Reads and loads in to "obj" a single key or all keys from source file. :param obj: the settings instance :param env: settings current env default='development' :param silent: if errors should raise :param key: if defined load a ...
Write data to a settings file. :param settings_path: the filepath :param settings_data: a dictionary with data :param merge: boolean if existing file should be merged with new data
def write(settings_path, settings_data, merge=True): """Write data to a settings file. :param settings_path: the filepath :param settings_data: a dictionary with data :param merge: boolean if existing file should be merged with new data """ settings_path = Path(settings_path) if settings_pa...
Reads and loads in to "settings" a single key or all keys from redis :param obj: the settings instance :param env: settings env default='DYNACONF' :param silent: if errors should raise :param key: if defined load a single key, else load all in env :return: None
def load(obj, env=None, silent=True, key=None): """Reads and loads in to "settings" a single key or all keys from redis :param obj: the settings instance :param env: settings env default='DYNACONF' :param silent: if errors should raise :param key: if defined load a single key, else load all in env ...
Write a value in to loader source :param obj: settings object :param data: vars to be stored :param kwargs: vars to be stored :return:
def write(obj, data=None, **kwargs): """Write a value in to loader source :param obj: settings object :param data: vars to be stored :param kwargs: vars to be stored :return: """ if obj.REDIS_ENABLED_FOR_DYNACONF is False: raise RuntimeError( "Redis is not configured \n"...
Delete a single key if specified, or all env if key is none :param obj: settings object :param key: key to delete from store location :return: None
def delete(obj, key=None): """ Delete a single key if specified, or all env if key is none :param obj: settings object :param key: key to delete from store location :return: None """ client = StrictRedis(**obj.REDIS_FOR_DYNACONF) holder = obj.get("ENVVAR_PREFIX_FOR_DYNACONF") if key:...
Tries to import a python module
def load(obj, settings_module, identifier="py", silent=False, key=None): """Tries to import a python module""" mod, loaded_from = get_module(obj, settings_module, silent) if mod and loaded_from: obj.logger.debug("py_loader: {}".format(mod)) else: obj.logger.debug( "py_loader...
If settings_module is a filename path import it.
def import_from_filename(obj, filename, silent=False): # pragma: no cover """If settings_module is a filename path import it.""" if filename in [item.filename for item in inspect.stack()]: raise ImportError( "Looks like you are loading dynaconf " "from inside the {} file and the...
Write data to a settings file. :param settings_path: the filepath :param settings_data: a dictionary with data :param merge: boolean if existing file should be merged with new data
def write(settings_path, settings_data, merge=True): """Write data to a settings file. :param settings_path: the filepath :param settings_data: a dictionary with data :param merge: boolean if existing file should be merged with new data """ settings_path = Path(settings_path) if settings_pa...
Creates the list of environments to read :param obj: the settings instance :param env: settings env default='DYNACONF' :return: a list of working environments
def _get_env_list(obj, env): """Creates the list of environments to read :param obj: the settings instance :param env: settings env default='DYNACONF' :return: a list of working environments """ # add the [default] env env_list = [obj.get("DEFAULT_ENV_FOR_DYNACONF")] # compatibility wit...
Reads and loads in to "settings" a single key or all keys from vault :param obj: the settings instance :param env: settings env default='DYNACONF' :param silent: if errors should raise :param key: if defined load a single key, else load all in env :return: None
def load(obj, env=None, silent=None, key=None): """Reads and loads in to "settings" a single key or all keys from vault :param obj: the settings instance :param env: settings env default='DYNACONF' :param silent: if errors should raise :param key: if defined load a single key, else load all in env ...
Write a value in to loader source :param obj: settings object :param data: vars to be stored :param kwargs: vars to be stored :return:
def write(obj, data=None, **kwargs): """Write a value in to loader source :param obj: settings object :param data: vars to be stored :param kwargs: vars to be stored :return: """ if obj.VAULT_ENABLED_FOR_DYNACONF is False: raise RuntimeError( "Vault is not configured \n"...
Pick correct settings instance and set it to a global variable.
def set_settings(instance=None): """Pick correct settings instance and set it to a global variable.""" global settings settings = None if instance: settings = import_settings(instance) elif "INSTANCE_FOR_DYNACONF" in os.environ: settings = import_settings(os.environ["INSTANCE_FOR...
Import settings instance from python dotted path. Last item in dotted path must be settings instace. Example: import_settings('path.to.settings')
def import_settings(dotted_path): """Import settings instance from python dotted path. Last item in dotted path must be settings instace. Example: import_settings('path.to.settings') """ if "." in dotted_path: module, name = dotted_path.rsplit(".", 1) else: raise click.UsageErr...
Read a file on root dir.
def read_file_in_root_directory(*names, **kwargs): """Read a file on root dir.""" return read_file( os.path.join(os.path.dirname(__file__), *names), encoding=kwargs.get("encoding", "utf-8"), )
Splits values like foo=bar=zaz in {'foo': 'bar=zaz'}
def split_vars(_vars): """Splits values like foo=bar=zaz in {'foo': 'bar=zaz'}""" return ( { k.upper().strip(): parse_conf_data(v.strip(), tomlfy=True) for k, _, v in [item.partition("=") for item in _vars] } if _vars else {} )
Shows dynaconf awesome banner
def show_banner(ctx, param, value): """Shows dynaconf awesome banner""" if not value or ctx.resilient_parsing: return set_settings() click.echo(settings.dynaconf_banner) click.echo("Learn more at: http://github.com/rochacbruno/dynaconf") ctx.exit()
Inits a dynaconf project By default it creates a settings.toml and a .secrets.toml for [default|development|staging|testing|production|global] envs. The format of the files can be changed passing --format=yaml|json|ini|py. This command must run on the project's root folder or you must pass --p...
def init(fileformat, path, env, _vars, _secrets, wg, y, django): """Inits a dynaconf project By default it creates a settings.toml and a .secrets.toml for [default|development|staging|testing|production|global] envs. The format of the files can be changed passing --format=yaml|json|ini|py. Thi...
Lists all user defined config values and if `--all` is passed it also shows dynaconf internal variables.
def _list(env, key, more, loader, _all=False, output=None): """Lists all user defined config values and if `--all` is passed it also shows dynaconf internal variables. """ if env: env = env.strip() if key: key = key.strip() if loader: loader = loader.strip() if env: ...
Writes data to specific source
def write(to, _vars, _secrets, path, env, y): """Writes data to specific source""" _vars = split_vars(_vars) _secrets = split_vars(_secrets) loader = importlib.import_module("dynaconf.loaders.{}_loader".format(to)) if to in EXTS: # Lets write to a file path = Path(path) if...
Validates Dynaconf settings based on rules defined in dynaconf_validators.toml
def validate(path): # pragma: no cover """Validates Dynaconf settings based on rules defined in dynaconf_validators.toml""" # reads the 'dynaconf_validators.toml' from path # for each section register the validator for specific env # call validate path = Path(path) if not str(path).endswi...
This function might be something coming from your ORM
def connect(server, port, username, password): """This function might be something coming from your ORM""" print("-" * 79) print("Connecting to: {}".format(server)) print("At port: {}".format(port)) print("Using username: {}".format(username)) print("Using password: {}".format(password)) pri...
Loads envvars with prefixes: `DYNACONF_` (default global) or `$(ENVVAR_PREFIX_FOR_DYNACONF)_`
def load(obj, env=None, silent=True, key=None): """Loads envvars with prefixes: `DYNACONF_` (default global) or `$(ENVVAR_PREFIX_FOR_DYNACONF)_` """ global_env = obj.get("ENVVAR_PREFIX_FOR_DYNACONF") if global_env is False or global_env.upper() != "DYNACONF": load_from_env(IDENTIFIER + "_gl...
Write data to .env file
def write(settings_path, settings_data, **kwargs): """Write data to .env file""" for key, value in settings_data.items(): dotenv_cli.set_key(str(settings_path), key.upper(), str(value))
Reads and loads in to "obj" a single key or all keys from source file. :param obj: the settings instance :param env: settings current env default='development' :param silent: if errors should raise :param key: if defined load a single key, else load all in env :param filename: Optional custom filen...
def load(obj, env=None, silent=True, key=None, filename=None): """ Reads and loads in to "obj" a single key or all keys from source file. :param obj: the settings instance :param env: settings current env default='development' :param silent: if errors should raise :param key: if defined load a ...
Write data to a settings file. :param settings_path: the filepath :param settings_data: a dictionary with data :param merge: boolean if existing file should be merged with new data
def write(settings_path, settings_data, merge=True): """Write data to a settings file. :param settings_path: the filepath :param settings_data: a dictionary with data :param merge: boolean if existing file should be merged with new data """ settings_path = Path(settings_path) if settings_pa...
Reads and loads in to "obj" a single key or all keys from source file. :param obj: the settings instance :param env: settings current env default='development' :param silent: if errors should raise :param key: if defined load a single key, else load all in env :param filename: Optional custom filen...
def load(obj, env=None, silent=True, key=None, filename=None): """ Reads and loads in to "obj" a single key or all keys from source file. :param obj: the settings instance :param env: settings current env default='development' :param silent: if errors should raise :param key: if defined load a ...
Uses TOML syntax to parse data
def parse_with_toml(data): """Uses TOML syntax to parse data""" try: return toml.loads("key={}".format(data), DynaBox).key except toml.TomlDecodeError: return data
@int @bool @float @json (for lists and dicts) strings does not need converters export DYNACONF_DEFAULT_THEME='material' export DYNACONF_DEBUG='@bool True' export DYNACONF_DEBUG_TOOLBAR_ENABLED='@bool False' export DYNACONF_PAGINATION_PER_PAGE='@int 20' export DYNACONF_MONGODB_SETTINGS='@json {"...
def _parse_conf_data(data, tomlfy=False): """ @int @bool @float @json (for lists and dicts) strings does not need converters export DYNACONF_DEFAULT_THEME='material' export DYNACONF_DEBUG='@bool True' export DYNACONF_DEBUG_TOOLBAR_ENABLED='@bool False' export DYNACONF_PAGINATION_PER_PAGE='@...
Reads and loads in to `self.obj` a single key or all keys from source :param filename: Optional filename to load :param key: if provided load a single key :param silent: if load erros should be silenced
def load(self, filename=None, key=None, silent=True): """ Reads and loads in to `self.obj` a single key or all keys from source :param filename: Optional filename to load :param key: if provided load a single key :param silent: if load erros should be silenced """ ...
Initial setup, run once.
def _setup(self): """Initial setup, run once.""" default_settings.reload() environment_variable = self._kwargs.get( "ENVVAR_FOR_DYNACONF", default_settings.ENVVAR_FOR_DYNACONF ) settings_module = os.environ.get(environment_variable) self._wrapped = Settings( ...
Allows user to reconfigure settings object passing a new settings module or separated kwargs :param settings_module: defines the setttings file :param kwargs: override default settings
def configure(self, settings_module=None, **kwargs): """ Allows user to reconfigure settings object passing a new settings module or separated kwargs :param settings_module: defines the setttings file :param kwargs: override default settings """ default_settings...
Returns a dictionary with set key and values. :param env: Str env name, default self.current_env `DEVELOPMENT` :param internal: bool - should include dynaconf internal vars?
def as_dict(self, env=None, internal=False): """Returns a dictionary with set key and values. :param env: Str env name, default self.current_env `DEVELOPMENT` :param internal: bool - should include dynaconf internal vars? """ ctx_mgr = suppress() if env is None else self.using_e...
Perform dotted key lookups and keep track of where we are.
def _dotted_get(self, dotted_key, default=None, **kwargs): """ Perform dotted key lookups and keep track of where we are. """ split_key = dotted_key.split(".") name, keys = split_key[0], split_key[1:] result = self.get(name, default=default, **kwargs) self._memoiz...
Get a value from settings store, this is the prefered way to access:: >>> from dynaconf import settings >>> settings.get('KEY') :param key: The name of the setting value, will always be upper case :param default: In case of not found it will be returned :param cast: Sho...
def get( self, key, default=None, cast=None, fresh=False, dotted_lookup=True ): """ Get a value from settings store, this is the prefered way to access:: >>> from dynaconf import settings >>> settings.get('KEY') :param key: The name of the setting value, wil...
Check if key exists :param key: the name of setting variable :param fresh: if key should be taken from source direclty :return: Boolean
def exists(self, key, fresh=False): """Check if key exists :param key: the name of setting variable :param fresh: if key should be taken from source direclty :return: Boolean """ key = key.upper() if key in self._deleted: return False return s...
This is a shortcut to `get(key, fresh=True)`. always reload from loaders store before getting the var. :param key: The name of the setting value, will always be upper case :param default: In case of not found it will be returned :param cast: Should cast in to @int, @float, @bool or @jso...
def get_fresh(self, key, default=None, cast=None): """This is a shortcut to `get(key, fresh=True)`. always reload from loaders store before getting the var. :param key: The name of the setting value, will always be upper case :param default: In case of not found it will be returned ...
Get value from environment variable using os.environ.get :param key: The name of the setting value, will always be upper case :param default: In case of not found it will be returned :param cast: Should cast in to @int, @float, @bool or @json ? or cast must be true to use cast inferenc...
def get_environ(self, key, default=None, cast=None): """Get value from environment variable using os.environ.get :param key: The name of the setting value, will always be upper case :param default: In case of not found it will be returned :param cast: Should cast in to @int, @float, @bo...
This context manager allows the contextual use of a different env Example of settings.toml:: [development] message = 'This is in dev' [other] message = 'this is in other env' Program:: >>> from dynaconf import settings >>> print ...
def using_env(self, env, clean=True, silent=True, filename=None): """ This context manager allows the contextual use of a different env Example of settings.toml:: [development] message = 'This is in dev' [other] message = 'this is in other env' ...
Gets SETTINGS_MODULE variable
def settings_module(self): """Gets SETTINGS_MODULE variable""" settings_module = parse_conf_data( os.environ.get( self.ENVVAR_FOR_DYNACONF, self.SETTINGS_FILE_FOR_DYNACONF ), tomlfy=True, ) if settings_module != getattr(self, "SETTINGS_...
Used to interactively change the env Example of settings.toml:: [development] message = 'This is in dev' [other] message = 'this is in other env' Program:: >>> from dynaconf import settings >>> print settings.MESSAGE ...
def setenv(self, env=None, clean=True, silent=True, filename=None): """Used to interactively change the env Example of settings.toml:: [development] message = 'This is in dev' [other] message = 'this is in other env' Program:: >>> fr...
Clean all loaded values to reload when switching envs
def clean(self, *args, **kwargs): """Clean all loaded values to reload when switching envs""" for key in list(self.store.keys()): self.unset(key)
Unset on all references :param key: The key to be unset
def unset(self, key): """Unset on all references :param key: The key to be unset """ key = key.strip().upper() if key not in dir(default_settings) and key not in self._defaults: self.logger.debug("Unset %s", key) delattr(self, key) self.store....
Set a value storing references for the loader :param key: The key to store :param value: The value to store :param loader_identifier: Optional loader name e.g: toml, yaml etc. :param tomlfy: Bool define if value is parsed by toml (defaults False) :param is_secret: Bool define if...
def set( self, key, value, loader_identifier=None, tomlfy=False, dotted_lookup=True, is_secret=False, ): """Set a value storing references for the loader :param key: The key to store :param value: The value to store :param load...
Update values in the current settings object without saving in stores:: >>> from dynaconf import settings >>> print settings.NAME 'Bruno' >>> settings.update({'NAME': 'John'}, other_value=1) >>> print settings.NAME 'John' >>> print set...
def update( self, data=None, loader_identifier=None, tomlfy=False, is_secret=False, **kwargs ): """ Update values in the current settings object without saving in stores:: >>> from dynaconf import settings >>> print settings.NA...
Merge the new value being set with the existing value before set
def _merge_before_set(self, key, existing, value, is_secret): """Merge the new value being set with the existing value before set""" def _log_before_merging(_value): self.logger.debug( "Merging existing %s: %s with new: %s", key, existing, _value ) def _...
Return available loaders
def loaders(self): # pragma: no cover """Return available loaders""" if self.LOADERS_FOR_DYNACONF in (None, 0, "0", "false", False): self.logger.info("No loader defined") return [] if not self._loaders: for loader_module_name in self.LOADERS_FOR_DYNACONF: ...
Clean end Execute all loaders
def reload(self, env=None, silent=None): # pragma: no cover """Clean end Execute all loaders""" self.clean() self.execute_loaders(env, silent)
Execute all internal and registered loaders :param env: The environment to load :param silent: If loading erros is silenced :param key: if provided load a single key :param filename: optional custom filename to load
def execute_loaders(self, env=None, silent=None, key=None, filename=None): """Execute all internal and registered loaders :param env: The environment to load :param silent: If loading erros is silenced :param key: if provided load a single key :param filename: optional custom fi...
Do we have any nested includes we need to process?
def load_includes(self, env, silent, key): """Do we have any nested includes we need to process?""" includes = self.get("DYNACONF_INCLUDE", []) includes.extend(ensure_a_list(self.get("INCLUDES_FOR_DYNACONF"))) if includes: self.logger.debug("Processing includes %s", includes)...
Programmatically load files from ``path``. :param path: A single filename or a file list :param env: Which env to load from file (default current_env) :param silent: Should raise errors? :param key: Load a single key?
def load_file(self, path=None, env=None, silent=True, key=None): """Programmatically load files from ``path``. :param path: A single filename or a file list :param env: Which env to load from file (default current_env) :param silent: Should raise errors? :param key: Load a singl...
ROOT_PATH_FOR_DYNACONF or the path of first loaded file or '.
def _root_path(self): """ROOT_PATH_FOR_DYNACONF or the path of first loaded file or '.'""" if self.ROOT_PATH_FOR_DYNACONF is not None: return self.ROOT_PATH_FOR_DYNACONF elif self._loaded_files: # called once root_path = os.path.dirname(self._loaded_files[0]) ...
This is deprecated, kept for compat .. deprecated:: 1.0.0 Use multiple settings or INCLUDES_FOR_DYNACONF files instead.
def load_extra_yaml(self, env, silent, key): """This is deprecated, kept for compat .. deprecated:: 1.0.0 Use multiple settings or INCLUDES_FOR_DYNACONF files instead. """ if self.get("YAML") is not None: self.logger.warning( "The use of YAML var ...
Path containing _root_path
def path_for(self, *args): """Path containing _root_path""" if args and args[0].startswith(os.path.sep): return os.path.join(*args) return os.path.join(self._root_path or os.getcwd(), *args)
Gets or creates validator wrapper
def validators(self): """Gets or creates validator wrapper""" if not hasattr(self, "_validators"): self._validators = ValidatorList(self) return self._validators
Feature flagging system write flags to redis $ dynaconf write redis -s DASHBOARD=1 -e premiumuser meaning: Any premium user has DASHBOARD feature enabled In your program do:: # premium user has access to dashboard? >>> if settings.flag('dashboard', 'premiumuser'...
def flag(self, key, env=None): """Feature flagging system write flags to redis $ dynaconf write redis -s DASHBOARD=1 -e premiumuser meaning: Any premium user has DASHBOARD feature enabled In your program do:: # premium user has access to dashboard? >>> i...
Given the `obj` populate it using self.store items.
def populate_obj(self, obj, keys=None): """Given the `obj` populate it using self.store items.""" keys = keys or self.keys() for key in keys: key = key.upper() value = self.get(key, empty) if value is not empty: setattr(obj, key, value)
Loads default settings and check if there are overridings exported as environment variables
def default_loader(obj, defaults=None): """Loads default settings and check if there are overridings exported as environment variables""" defaults = defaults or {} default_settings_values = { key: value for key, value in default_settings.__dict__.items() # noqa if key.isupper() ...
Loads from defined settings module :param obj: A dynaconf instance :param settings_module: A path or a list of paths e.g settings.toml :param env: Env to look for data defaults: development :param silent: Boolean to raise loading errors :param key: Load a single key if provided :param filename:...
def settings_loader( obj, settings_module=None, env=None, silent=True, key=None, filename=None ): """Loads from defined settings module :param obj: A dynaconf instance :param settings_module: A path or a list of paths e.g settings.toml :param env: Env to look for data defaults: development :par...
Enable external service loaders like `VAULT_` and `REDIS_` looks forenv variables like `REDIS_ENABLED_FOR_DYNACONF`
def enable_external_loaders(obj): """Enable external service loaders like `VAULT_` and `REDIS_` looks forenv variables like `REDIS_ENABLED_FOR_DYNACONF` """ for name, loader in ct.EXTERNAL_LOADERS.items(): enabled = getattr( obj, "{}_ENABLED_FOR_DYNACONF".format(name.upper()), False ...
Render an ASCII art figure into the requested format output file.
def render_aafigure(self, text, options): """ Render an ASCII art figure into the requested format output file. """ fname = get_basename(text, options) fname = '%s.%s' % (get_basename(text, options), options['format']) if True: #TODO: hasattr(self.builder, 'imgpath'): # HTML #TO...
Reads and loads in to "obj" a single key or all keys from source :param obj: the settings instance :param env: settings current env (upper case) default='DEVELOPMENT' :param silent: if errors should raise :param key: if defined load a single key, else load all from `env` :param filename: Custom file...
def load(obj, env=None, silent=True, key=None, filename=None): """ Reads and loads in to "obj" a single key or all keys from source :param obj: the settings instance :param env: settings current env (upper case) default='DEVELOPMENT' :param silent: if errors should raise :param key: if defined l...
Directories starting from the given directory up to the root or break_at
def _walk_to_root(path, break_at=None): """ Directories starting from the given directory up to the root or break_at """ if not os.path.exists(path): # pragma: no cover raise IOError("Starting path not found") if os.path.isfile(path): # pragma: no cover path = os.path.dirname(path...
Search in increasingly higher folders for the given file Returns path to the file if found, or an empty string otherwise. This function will build a `search_tree` based on: - Project_root if specified - Invoked script location and its parents until root - Current working directory For each pa...
def find_file(filename=".env", project_root=None, skip_files=None, **kwargs): """Search in increasingly higher folders for the given file Returns path to the file if found, or an empty string otherwise. This function will build a `search_tree` based on: - Project_root if specified - Invoked script...
Reads and loads in to "obj" a single key or all keys from source file. :param obj: the settings instance :param env: settings current env default='development' :param silent: if errors should raise :param key: if defined load a single key, else load all in env :param filename: Optional custom filen...
def load(obj, env=None, silent=True, key=None, filename=None): """ Reads and loads in to "obj" a single key or all keys from source file. :param obj: the settings instance :param env: settings current env default='development' :param silent: if errors should raise :param key: if defined load a ...
Render an ASCII art figure into the requested format output file.
def render_aafigure(app, text, options): """ Render an ASCII art figure into the requested format output file. """ if aafigure is None: raise AafigError('aafigure module not installed') fname = get_basename(text, options) fname = '%s.%s' % (get_basename(text, options), options['format'...
Raise ValidationError if invalid
def validate(self, settings): """Raise ValidationError if invalid""" if self.envs is None: self.envs = [settings.current_env] if self.when is not None: try: # inherit env if not defined if self.when.envs is None: self....
We override the parent to omit explicity defined meta fields (such as SerializerMethodFields) from the list of declared fields
def get_field_names(self, declared_fields, info): """ We override the parent to omit explicity defined meta fields (such as SerializerMethodFields) from the list of declared fields """ meta_fields = getattr(self.Meta, 'meta_fields', []) declared = OrderedDict() f...
Extend :py:meth:`rest_framework.filters.OrderingFilter.remove_invalid_fields` to validate that all provided sort fields exist (as contrasted with the super's behavior which is to silently remove invalid fields). :raises ValidationError: if a sort field is invalid.
def remove_invalid_fields(self, queryset, fields, view, request): """ Extend :py:meth:`rest_framework.filters.OrderingFilter.remove_invalid_fields` to validate that all provided sort fields exist (as contrasted with the super's behavior which is to silently remove invalid fields). ...
Object instance -> Dict of primitive datatypes.
def to_representation(self, instance): """ Object instance -> Dict of primitive datatypes. """ ret = OrderedDict() readable_fields = [ field for field in self.fields.values() if not field.write_only ] for field in readable_fields: ...
Validate that query params are in the list of valid query keywords in :py:attr:`query_regex` :raises ValidationError: if not.
def validate_query_params(self, request): """ Validate that query params are in the list of valid query keywords in :py:attr:`query_regex` :raises ValidationError: if not. """ # TODO: For jsonapi error object conformance, must set jsonapi errors "parameter" for #...
Builds the `attributes` object of the JSON API resource object.
def extract_attributes(cls, fields, resource): """ Builds the `attributes` object of the JSON API resource object. """ data = OrderedDict() for field_name, field in six.iteritems(fields): # ID is always provided in the root of JSON API so remove it from attributes ...
Gathers the data from serializer fields specified in meta_fields and adds it to the meta object.
def extract_meta(cls, serializer, resource): """ Gathers the data from serializer fields specified in meta_fields and adds it to the meta object. """ if hasattr(serializer, 'child'): meta = getattr(serializer.child, 'Meta', None) else: meta = getat...
Determines what instance represents given relation and extracts it. Relation instance is determined by given field_name or source configured on field. As fallback is a serializer method called with name of field's source.
def extract_relation_instance(cls, field_name, field, resource_instance, serializer): """ Determines what instance represents given relation and extracts it. Relation instance is determined by given field_name or source configured on field. As fallback is a serializer method called with...
Adds related data to the top level included key when the request includes ?include=example,example_field2
def extract_included(cls, fields, resource, resource_instance, included_resources, included_cache): """ Adds related data to the top level included key when the request includes ?include=example,example_field2 """ # this function may be called with an emp...
Calls a `get_root_meta` function on a serializer, if it exists.
def extract_root_meta(cls, serializer, resource): """ Calls a `get_root_meta` function on a serializer, if it exists. """ many = False if hasattr(serializer, 'child'): many = True serializer = serializer.child data = {} if getattr(serializ...
Builds the resource object (type, id, attributes) and extracts relationships.
def build_json_resource_obj(cls, fields, resource, resource_instance, resource_name, force_type_resolution=False): """ Builds the resource object (type, id, attributes) and extracts relationships. """ # Determine type from the instance if the underlying mo...
This viewset provides a helper attribute to prefetch related models based on the include specified in the URL. __all__ can be used to specify a prefetch which should be done regardless of the include .. code:: python # When MyViewSet is called with ?include=author it will prefetch...
def get_queryset(self): """ This viewset provides a helper attribute to prefetch related models based on the include specified in the URL. __all__ can be used to specify a prefetch which should be done regardless of the include .. code:: python # When MyViewSet is ...
This mixin adds automatic prefetching for OneToOne and ManyToMany fields.
def get_queryset(self, *args, **kwargs): """ This mixin adds automatic prefetching for OneToOne and ManyToMany fields. """ qs = super(AutoPrefetchMixin, self).get_queryset(*args, **kwargs) included_resources = get_included_resources(self.request) for included in included_resources: ...
Given a name, view name and kwargs, return the URL that hyperlinks to the object. May raise a `NoReverseMatch` if the `view_name` and `lookup_field` attributes are not configured to correctly match the URL conf.
def get_url(self, name, view_name, kwargs, request): """ Given a name, view name and kwargs, return the URL that hyperlinks to the object. May raise a `NoReverseMatch` if the `view_name` and `lookup_field` attributes are not configured to correctly match the URL conf. """ ...
Override :meth:``get_queryset``
def get_queryset(self): """ Override :meth:``get_queryset`` """ queryset = super(MultipleIDMixin, self).get_queryset() if hasattr(self.request, 'query_params'): ids = dict(self.request.query_params).get('ids[]') else: ids = dict(self.request.QUERY_...
Given an instance of a serializer, return a dictionary of metadata about its fields.
def get_serializer_info(self, serializer): """ Given an instance of a serializer, return a dictionary of metadata about its fields. """ if hasattr(serializer, 'child'): # If this is a `ListSerializer` then we want to examine the # underlying child serializ...
Given an instance of a serializer field, return a dictionary of metadata about it.
def get_field_info(self, field): """ Given an instance of a serializer field, return a dictionary of metadata about it. """ field_info = OrderedDict() serializer = field.parent if isinstance(field, serializers.ManyRelatedField): field_info['type'] = s...
GET request
def get(self, request, pk=None): """ GET request """ obj = self.get_object() return Response(IdentitySerializer(obj).data)
Return the name of a resource.
def get_resource_name(context, expand_polymorphic_types=False): """ Return the name of a resource. """ from rest_framework_json_api.serializers import PolymorphicModelSerializer view = context.get('view') # Sanity check to make sure we have a view. if not view: return None # Ch...
Takes a dict and returns it with formatted keys as set in `format_type` or `JSON_API_FORMAT_FIELD_NAMES` :format_type: Either 'dasherize', 'camelize', 'capitalize' or 'underscore'
def format_field_names(obj, format_type=None): """ Takes a dict and returns it with formatted keys as set in `format_type` or `JSON_API_FORMAT_FIELD_NAMES` :format_type: Either 'dasherize', 'camelize', 'capitalize' or 'underscore' """ if format_type is None: format_type = json_api_setti...
Depending on settings calls either `format_keys` or `format_field_names`
def _format_object(obj, format_type=None): """Depending on settings calls either `format_keys` or `format_field_names`""" if json_api_settings.FORMAT_KEYS is not None: return format_keys(obj, format_type) return format_field_names(obj, format_type)
.. warning:: `format_keys` function and `JSON_API_FORMAT_KEYS` setting are deprecated and will be removed in the future. Use `format_field_names` and `JSON_API_FORMAT_FIELD_NAMES` instead. Be aware that `format_field_names` only formats keys and preserves value. Takes either a dict...
def format_keys(obj, format_type=None): """ .. warning:: `format_keys` function and `JSON_API_FORMAT_KEYS` setting are deprecated and will be removed in the future. Use `format_field_names` and `JSON_API_FORMAT_FIELD_NAMES` instead. Be aware that `format_field_names` only format...
.. warning:: The 'format_relation_name' function has been renamed 'format_resource_type' and the settings are now 'JSON_API_FORMAT_TYPES' and 'JSON_API_PLURALIZE_TYPES' instead of 'JSON_API_FORMAT_RELATION_KEYS' and 'JSON_API_PLURALIZE_RELATION_TYPE'
def format_relation_name(value, format_type=None): """ .. warning:: The 'format_relation_name' function has been renamed 'format_resource_type' and the settings are now 'JSON_API_FORMAT_TYPES' and 'JSON_API_PLURALIZE_TYPES' instead of 'JSON_API_FORMAT_RELATION_KEYS' and 'JSON_API_PLURAL...
Build a list of included resources.
def get_included_resources(request, serializer=None): """ Build a list of included resources. """ include_resources_param = request.query_params.get('include') if request else None if include_resources_param: return include_resources_param.split(',') else: return get_default_included_res...
Parses the incoming bytestream as JSON and returns the resulting data
def parse(self, stream, media_type=None, parser_context=None): """ Parses the incoming bytestream as JSON and returns the resulting data """ result = super(JSONParser, self).parse( stream, media_type=media_type, parser_context=parser_context ) if not isinstan...
Check that all the filter[key] are valid. :param keys: list of FilterSet keys :param filterset_class: :py:class:`django_filters.rest_framework.FilterSet` :raises ValidationError: if key not in FilterSet keys or no FilterSet.
def _validate_filter(self, keys, filterset_class): """ Check that all the filter[key] are valid. :param keys: list of FilterSet keys :param filterset_class: :py:class:`django_filters.rest_framework.FilterSet` :raises ValidationError: if key not in FilterSet keys or no FilterSet....