_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q225000 | resolver | train | def resolver(schema):
"""Default implementation of a schema name resolver function
"""
name = schema.__name__
if name.endswith("Schema"):
return name[:-6] or name
return name | python | {
"resource": ""
} |
q225001 | MarshmallowPlugin.resolve_schema_in_request_body | train | def resolve_schema_in_request_body(self, request_body):
"""Function to resolve a schema in a requestBody object - modifies then
response dict to convert Marshmallow Schema object or class into dict
"""
content = request_body["content"]
for content_type in content:
sch... | python | {
"resource": ""
} |
q225002 | MarshmallowPlugin.resolve_schema | train | def resolve_schema(self, data):
"""Function to resolve a schema in a parameter or response - modifies the
corresponding dict to convert Marshmallow Schema object or class into dict
:param APISpec spec: `APISpec` containing refs.
:param dict|str data: either a parameter or response dicti... | python | {
"resource": ""
} |
q225003 | MarshmallowPlugin.warn_if_schema_already_in_spec | train | def warn_if_schema_already_in_spec(self, schema_key):
"""Method to warn the user if the schema has already been added to the
spec.
"""
if schema_key in self.openapi.refs:
warnings.warn(
"{} has already been added to the spec. Adding it twice may "
... | python | {
"resource": ""
} |
q225004 | size_in_bytes | train | def size_in_bytes(insize):
"""
Returns the size in bytes from strings such as '5 mb' into 5242880.
>>> size_in_bytes('1m')
1048576
>>> size_in_bytes('1.5m')
1572864
>>> size_in_bytes('2g')
2147483648
>>> size_in_bytes(None)
Traceback (most recent call last):
raise ValueE... | python | {
"resource": ""
} |
q225005 | main | train | def main():
"""
Main function, parses the URL from command line arguments
"""
signal.signal(signal.SIGINT, signal_handler)
global offset
global arguments
# Parse argument
arguments = docopt(__doc__, version=__version__)
if arguments['--debug']:
logger.level = logging.DEBUG
... | python | {
"resource": ""
} |
q225006 | get_config | train | def get_config():
"""
Reads the music download filepath from scdl.cfg
"""
global token
config = configparser.ConfigParser()
config.read(os.path.join(os.path.expanduser('~'), '.config/scdl/scdl.cfg'))
try:
token = config['scdl']['auth_token']
path = config['scdl']['path']
... | python | {
"resource": ""
} |
q225007 | get_item | train | def get_item(track_url, client_id=CLIENT_ID):
"""
Fetches metadata for a track or playlist
"""
try:
item_url = url['resolve'].format(track_url)
r = requests.get(item_url, params={'client_id': client_id})
logger.debug(r.url)
if r.status_code == 403:
return get... | python | {
"resource": ""
} |
q225008 | who_am_i | train | def who_am_i():
"""
Display username from current token and check for validity
"""
me = url['me'].format(token)
r = requests.get(me, params={'client_id': CLIENT_ID})
r.raise_for_status()
current_user = r.json()
logger.debug(me)
logger.info('Hello {0}!'.format(current_user['username'... | python | {
"resource": ""
} |
q225009 | remove_files | train | def remove_files():
"""
Removes any pre-existing tracks that were not just downloaded
"""
logger.info("Removing local track files that were not downloaded...")
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
if f not in fileToKeep:
os.remove(f) | python | {
"resource": ""
} |
q225010 | get_track_info | train | def get_track_info(track_id):
"""
Fetches track info from Soundcloud, given a track_id
"""
logger.info('Retrieving more info on the track')
info_url = url["trackinfo"].format(track_id)
r = requests.get(info_url, params={'client_id': CLIENT_ID}, stream=True)
item = r.json()
logger.debug(i... | python | {
"resource": ""
} |
q225011 | already_downloaded | train | def already_downloaded(track, title, filename):
"""
Returns True if the file has already been downloaded
"""
global arguments
already_downloaded = False
if os.path.isfile(filename):
already_downloaded = True
if arguments['--flac'] and can_convert(filename) \
... | python | {
"resource": ""
} |
q225012 | in_download_archive | train | def in_download_archive(track):
"""
Returns True if a track_id exists in the download archive
"""
global arguments
if not arguments['--download-archive']:
return
archive_filename = arguments.get('--download-archive')
try:
with open(archive_filename, 'a+', encoding='utf-8') a... | python | {
"resource": ""
} |
q225013 | record_download_archive | train | def record_download_archive(track):
"""
Write the track_id in the download archive
"""
global arguments
if not arguments['--download-archive']:
return
archive_filename = arguments.get('--download-archive')
try:
with open(archive_filename, 'a', encoding='utf-8') as file:
... | python | {
"resource": ""
} |
q225014 | unicode_compact | train | def unicode_compact(func):
"""
Make sure the first parameter of the decorated method to be a unicode
object.
"""
@wraps(func)
def wrapped(self, text, *a, **kw):
if not isinstance(text, six.text_type):
text = text.decode('utf-8')
return func(self, text, *a, **kw)
... | python | {
"resource": ""
} |
q225015 | Message.reply_webapi | train | def reply_webapi(self, text, attachments=None, as_user=True, in_thread=None):
"""
Send a reply to the sender using Web API
(This function supports formatted message
when using a bot integration)
If the message was send in a thread, answer in a thread per default... | python | {
"resource": ""
} |
q225016 | Message.send_webapi | train | def send_webapi(self, text, attachments=None, as_user=True, thread_ts=None):
"""
Send a reply using Web API
(This function supports formatted message
when using a bot integration)
"""
self._client.send_message(
self._body['channel'],
t... | python | {
"resource": ""
} |
q225017 | Message.reply | train | def reply(self, text, in_thread=None):
"""
Send a reply to the sender using RTM API
(This function doesn't supports formatted message
when using a bot integration)
If the message was send in a thread, answer in a thread per default.
"""
if in_thr... | python | {
"resource": ""
} |
q225018 | Message.direct_reply | train | def direct_reply(self, text):
"""
Send a reply via direct message using RTM API
"""
channel_id = self._client.open_dm_channel(self._get_user_id())
self._client.rtm_send_message(channel_id, text) | python | {
"resource": ""
} |
q225019 | Message.send | train | def send(self, text, thread_ts=None):
"""
Send a reply using RTM API
(This function doesn't supports formatted message
when using a bot integration)
"""
self._client.rtm_send_message(self._body['channel'], text, thread_ts=thread_ts) | python | {
"resource": ""
} |
q225020 | Message.react | train | def react(self, emojiname):
"""
React to a message using the web api
"""
self._client.react_to_message(
emojiname=emojiname,
channel=self._body['channel'],
timestamp=self._body['ts']) | python | {
"resource": ""
} |
q225021 | default_reply | train | def default_reply(*args, **kwargs):
"""
Decorator declaring the wrapped function to the default reply hanlder.
May be invoked as a simple, argument-less decorator (i.e. ``@default_reply``) or
with arguments customizing its behavior (e.g. ``@default_reply(matchstr='pattern')``).
"""
invoked = bo... | python | {
"resource": ""
} |
q225022 | BtcConverter.get_previous_price | train | def get_previous_price(self, currency, date_obj):
"""
Get Price for one bit coin on given date
"""
start = date_obj.strftime('%Y-%m-%d')
end = date_obj.strftime('%Y-%m-%d')
url = (
'https://api.coindesk.com/v1/bpi/historical/close.json'
'?start={}&... | python | {
"resource": ""
} |
q225023 | BtcConverter.get_previous_price_list | train | def get_previous_price_list(self, currency, start_date, end_date):
"""
Get List of prices between two dates
"""
start = start_date.strftime('%Y-%m-%d')
end = end_date.strftime('%Y-%m-%d')
url = (
'https://api.coindesk.com/v1/bpi/historical/close.json'
... | python | {
"resource": ""
} |
q225024 | BtcConverter.convert_to_btc | train | def convert_to_btc(self, amount, currency):
"""
Convert X amount to Bit Coins
"""
if isinstance(amount, Decimal):
use_decimal = True
else:
use_decimal = self._force_decimal
url = 'https://api.coindesk.com/v1/bpi/currentprice/{}.json'.format(curren... | python | {
"resource": ""
} |
q225025 | BtcConverter.convert_btc_to_cur | train | def convert_btc_to_cur(self, coins, currency):
"""
Convert X bit coins to valid currency amount
"""
if isinstance(coins, Decimal):
use_decimal = True
else:
use_decimal = self._force_decimal
url = 'https://api.coindesk.com/v1/bpi/currentprice/{}.js... | python | {
"resource": ""
} |
q225026 | BtcConverter.convert_to_btc_on | train | def convert_to_btc_on(self, amount, currency, date_obj):
"""
Convert X amount to BTC based on given date rate
"""
if isinstance(amount, Decimal):
use_decimal = True
else:
use_decimal = self._force_decimal
start = date_obj.strftime('%Y-%m-%d')
... | python | {
"resource": ""
} |
q225027 | rate_limit | train | def rate_limit(f):
"""
A decorator to handle rate limiting from the Twitter API. If
a rate limit error is encountered we will sleep until we can
issue the API call again.
"""
def new_f(*args, **kwargs):
errors = 0
while True:
resp = f(*args, **kwargs)
if r... | python | {
"resource": ""
} |
q225028 | catch_timeout | train | def catch_timeout(f):
"""
A decorator to handle read timeouts from Twitter.
"""
def new_f(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except (requests.exceptions.ReadTimeout,
requests.packages.urllib3.exceptions.ReadTimeoutError) as e:
... | python | {
"resource": ""
} |
q225029 | catch_gzip_errors | train | def catch_gzip_errors(f):
"""
A decorator to handle gzip encoding errors which have been known to
happen during hydration.
"""
def new_f(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except requests.exceptions.ContentDecodingError as e:
log.warn... | python | {
"resource": ""
} |
q225030 | interruptible_sleep | train | def interruptible_sleep(t, event=None):
"""
Sleeps for a specified duration, optionally stopping early for event.
Returns True if interrupted
"""
log.info("sleeping %s", t)
if event is None:
time.sleep(t)
return False
else:
return not event.wait(t) | python | {
"resource": ""
} |
q225031 | filter_protected | train | def filter_protected(f):
"""
filter_protected will filter out protected tweets and users unless
explicitly requested not to.
"""
def new_f(self, *args, **kwargs):
for obj in f(self, *args, **kwargs):
if self.protected == False:
if 'user' in obj and obj['user']['pr... | python | {
"resource": ""
} |
q225032 | tweets_files | train | def tweets_files(string, path):
"""Iterates over json files in path."""
for filename in os.listdir(path):
if re.match(string, filename) and ".jsonl" in filename:
f = gzip.open if ".gz" in filename else open
yield path + filename, f
Ellipsis | python | {
"resource": ""
} |
q225033 | extract | train | def extract(json_object, args, csv_writer):
"""Extract and write found attributes."""
found = [[]]
for attribute in args.attributes:
item = attribute.getElement(json_object)
if len(item) == 0:
for row in found:
row.append("NA")
else:
found1 = [... | python | {
"resource": ""
} |
q225034 | add | train | def add(from_user, from_id, to_user, to_id, type):
"adds a relation to the graph"
if options.users and to_user:
G.add_node(from_user, screen_name=from_user)
G.add_node(to_user, screen_name=to_user)
if G.has_edge(from_user, to_user):
weight = G[from_user][to_user]['we... | python | {
"resource": ""
} |
q225035 | Twarc.timeline | train | def timeline(self, user_id=None, screen_name=None, max_id=None,
since_id=None, max_pages=None):
"""
Returns a collection of the most recent tweets posted
by the user indicated by the user_id or screen_name parameter.
Provide a user_id or screen_name.
"""
... | python | {
"resource": ""
} |
q225036 | Twarc.follower_ids | train | def follower_ids(self, user):
"""
Returns Twitter user id lists for the specified user's followers.
A user can be a specific using their screen_name or user_id
"""
user = str(user)
user = user.lstrip('@')
url = 'https://api.twitter.com/1.1/followers/ids.json'
... | python | {
"resource": ""
} |
q225037 | Twarc.filter | train | def filter(self, track=None, follow=None, locations=None, event=None,
record_keepalive=False):
"""
Returns an iterator for tweets that match a given filter track from
the livestream of tweets happening right now.
If a threading.Event is provided for event and the event is... | python | {
"resource": ""
} |
q225038 | Twarc.sample | train | def sample(self, event=None, record_keepalive=False):
"""
Returns a small random sample of all public statuses. The Tweets
returned by the default access level are the same, so if two different
clients connect to this endpoint, they will see the same Tweets.
If a threading.Event... | python | {
"resource": ""
} |
q225039 | Twarc.dehydrate | train | def dehydrate(self, iterator):
"""
Pass in an iterator of tweets' JSON and get back an iterator of the
IDs of each tweet.
"""
for line in iterator:
try:
yield json.loads(line)['id_str']
except Exception as e:
log.error("uhoh... | python | {
"resource": ""
} |
q225040 | Twarc.hydrate | train | def hydrate(self, iterator):
"""
Pass in an iterator of tweet ids and get back an iterator for the
decoded JSON for each corresponding tweet.
"""
ids = []
url = "https://api.twitter.com/1.1/statuses/lookup.json"
# lookup 100 tweets at a time
for tweet_id ... | python | {
"resource": ""
} |
q225041 | Twarc.retweets | train | def retweets(self, tweet_id):
"""
Retrieves up to the last 100 retweets for the provided
tweet.
"""
log.info("retrieving retweets of %s", tweet_id)
url = "https://api.twitter.com/1.1/statuses/retweets/""{}.json".format(
tweet_id)
resp = self.get(u... | python | {
"resource": ""
} |
q225042 | Twarc.trends_available | train | def trends_available(self):
"""
Returns a list of regions for which Twitter tracks trends.
"""
url = 'https://api.twitter.com/1.1/trends/available.json'
try:
resp = self.get(url)
except requests.exceptions.HTTPError as e:
raise e
return res... | python | {
"resource": ""
} |
q225043 | Twarc.trends_place | train | def trends_place(self, woeid, exclude=None):
"""
Returns recent Twitter trends for the specified WOEID. If
exclude == 'hashtags', Twitter will remove hashtag trends from the
response.
"""
url = 'https://api.twitter.com/1.1/trends/place.json'
params = {'id': woeid}... | python | {
"resource": ""
} |
q225044 | Twarc.replies | train | def replies(self, tweet, recursive=False, prune=()):
"""
replies returns a generator of tweets that are replies for a given
tweet. It includes the original tweet. If you would like to fetch the
replies to the replies use recursive=True which will do a depth-first
recursive walk o... | python | {
"resource": ""
} |
q225045 | Twarc.list_members | train | def list_members(self, list_id=None, slug=None, owner_screen_name=None, owner_id=None):
"""
Returns the members of a list.
List id or (slug and (owner_screen_name or owner_id)) are required
"""
assert list_id or (slug and (owner_screen_name or owner_id))
url = 'https://a... | python | {
"resource": ""
} |
q225046 | Twarc.connect | train | def connect(self):
"""
Sets up the HTTP session to talk to Twitter. If one is active it is
closed and another one is opened.
"""
if not (self.consumer_key and self.consumer_secret and self.access_token
and self.access_token_secret):
raise RuntimeError(... | python | {
"resource": ""
} |
q225047 | Twarc.get_keys | train | def get_keys(self):
"""
Get the Twitter API keys. Order of precedence is command line,
environment, config file. Return True if all the keys were found
and False if not.
"""
env = os.environ.get
if not self.consumer_key:
self.consumer_key = env('CONSUM... | python | {
"resource": ""
} |
q225048 | Twarc.validate_keys | train | 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... | python | {
"resource": ""
} |
q225049 | FlaskDynaconf.init_app | train | 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 | python | {
"resource": ""
} |
q225050 | DynaconfConfig.get | train | 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)) | python | {
"resource": ""
} |
q225051 | object_merge | train | 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... | python | {
"resource": ""
} |
q225052 | compat_kwargs | train | 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():... | python | {
"resource": ""
} |
q225053 | deduplicate | train | 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 | python | {
"resource": ""
} |
q225054 | trimmed_split | train | 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] | python | {
"resource": ""
} |
q225055 | ensure_a_list | train | 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] | python | {
"resource": ""
} |
q225056 | load | train | 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
... | python | {
"resource": ""
} |
q225057 | load | train | 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... | python | {
"resource": ""
} |
q225058 | import_from_filename | train | 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... | python | {
"resource": ""
} |
q225059 | _get_env_list | train | 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... | python | {
"resource": ""
} |
q225060 | load | train | 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
... | python | {
"resource": ""
} |
q225061 | set_settings | train | 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... | python | {
"resource": ""
} |
q225062 | import_settings | train | 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... | python | {
"resource": ""
} |
q225063 | read_file_in_root_directory | train | 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"),
) | python | {
"resource": ""
} |
q225064 | show_banner | train | 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() | python | {
"resource": ""
} |
q225065 | write | train | 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... | python | {
"resource": ""
} |
q225066 | validate | train | 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... | python | {
"resource": ""
} |
q225067 | connect | train | 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... | python | {
"resource": ""
} |
q225068 | write | train | 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)) | python | {
"resource": ""
} |
q225069 | parse_with_toml | train | 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 | python | {
"resource": ""
} |
q225070 | BaseLoader.load | train | 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
"""
... | python | {
"resource": ""
} |
q225071 | LazySettings._setup | train | 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(
... | python | {
"resource": ""
} |
q225072 | LazySettings.configure | train | 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... | python | {
"resource": ""
} |
q225073 | Settings.as_dict | train | 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... | python | {
"resource": ""
} |
q225074 | Settings._dotted_get | train | 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... | python | {
"resource": ""
} |
q225075 | Settings.exists | train | 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... | python | {
"resource": ""
} |
q225076 | Settings.get_environ | train | 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... | python | {
"resource": ""
} |
q225077 | Settings.settings_module | train | 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_... | python | {
"resource": ""
} |
q225078 | Settings.clean | train | def clean(self, *args, **kwargs):
"""Clean all loaded values to reload when switching envs"""
for key in list(self.store.keys()):
self.unset(key) | python | {
"resource": ""
} |
q225079 | Settings.unset | train | 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.... | python | {
"resource": ""
} |
q225080 | Settings.set | train | 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... | python | {
"resource": ""
} |
q225081 | Settings._merge_before_set | train | 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 _... | python | {
"resource": ""
} |
q225082 | Settings.loaders | train | 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:
... | python | {
"resource": ""
} |
q225083 | Settings.reload | train | def reload(self, env=None, silent=None): # pragma: no cover
"""Clean end Execute all loaders"""
self.clean()
self.execute_loaders(env, silent) | python | {
"resource": ""
} |
q225084 | Settings.execute_loaders | train | 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... | python | {
"resource": ""
} |
q225085 | Settings.load_includes | train | 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)... | python | {
"resource": ""
} |
q225086 | Settings.load_file | train | 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... | python | {
"resource": ""
} |
q225087 | Settings._root_path | train | 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])
... | python | {
"resource": ""
} |
q225088 | Settings.load_extra_yaml | train | 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 ... | python | {
"resource": ""
} |
q225089 | Settings.path_for | train | 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) | python | {
"resource": ""
} |
q225090 | Settings.validators | train | def validators(self):
"""Gets or creates validator wrapper"""
if not hasattr(self, "_validators"):
self._validators = ValidatorList(self)
return self._validators | python | {
"resource": ""
} |
q225091 | Settings.populate_obj | train | 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) | python | {
"resource": ""
} |
q225092 | default_loader | train | 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()
... | python | {
"resource": ""
} |
q225093 | settings_loader | train | 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... | python | {
"resource": ""
} |
q225094 | enable_external_loaders | train | 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
... | python | {
"resource": ""
} |
q225095 | _walk_to_root | train | 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... | python | {
"resource": ""
} |
q225096 | find_file | train | 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... | python | {
"resource": ""
} |
q225097 | Validator.validate | train | 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.... | python | {
"resource": ""
} |
q225098 | ModelSerializer.to_representation | train | 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:
... | python | {
"resource": ""
} |
q225099 | JSONRenderer.extract_attributes | train | 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
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.