id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
243,500 | MicroPyramid/forex-python | forex_python/bitcoin.py | BtcConverter.convert_to_btc | 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(currency)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi').get(currency, {}).get('rate_float', None)
if price:
if use_decimal:
price = Decimal(price)
try:
converted_btc = amount/price
return converted_btc
except TypeError:
raise DecimalFloatMismatchError("convert_to_btc requires amount parameter is of type Decimal when force_decimal=True")
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given date") | python | def convert_to_btc(self, amount, currency):
if isinstance(amount, Decimal):
use_decimal = True
else:
use_decimal = self._force_decimal
url = 'https://api.coindesk.com/v1/bpi/currentprice/{}.json'.format(currency)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi').get(currency, {}).get('rate_float', None)
if price:
if use_decimal:
price = Decimal(price)
try:
converted_btc = amount/price
return converted_btc
except TypeError:
raise DecimalFloatMismatchError("convert_to_btc requires amount parameter is of type Decimal when force_decimal=True")
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given date") | [
"def",
"convert_to_btc",
"(",
"self",
",",
"amount",
",",
"currency",
")",
":",
"if",
"isinstance",
"(",
"amount",
",",
"Decimal",
")",
":",
"use_decimal",
"=",
"True",
"else",
":",
"use_decimal",
"=",
"self",
".",
"_force_decimal",
"url",
"=",
"'https://a... | Convert X amount to Bit Coins | [
"Convert",
"X",
"amount",
"to",
"Bit",
"Coins"
] | dc34868ec7c7eb49b3b963d6daa3897b7095ba09 | https://github.com/MicroPyramid/forex-python/blob/dc34868ec7c7eb49b3b963d6daa3897b7095ba09/forex_python/bitcoin.py#L75-L97 |
243,501 | MicroPyramid/forex-python | forex_python/bitcoin.py | BtcConverter.convert_btc_to_cur | 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/{}.json'.format(currency)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi').get(currency, {}).get('rate_float', None)
if price:
if use_decimal:
price = Decimal(price)
try:
converted_amount = coins * price
return converted_amount
except TypeError:
raise DecimalFloatMismatchError("convert_btc_to_cur requires coins parameter is of type Decimal when force_decimal=True")
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given date") | python | def convert_btc_to_cur(self, coins, currency):
if isinstance(coins, Decimal):
use_decimal = True
else:
use_decimal = self._force_decimal
url = 'https://api.coindesk.com/v1/bpi/currentprice/{}.json'.format(currency)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi').get(currency, {}).get('rate_float', None)
if price:
if use_decimal:
price = Decimal(price)
try:
converted_amount = coins * price
return converted_amount
except TypeError:
raise DecimalFloatMismatchError("convert_btc_to_cur requires coins parameter is of type Decimal when force_decimal=True")
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given date") | [
"def",
"convert_btc_to_cur",
"(",
"self",
",",
"coins",
",",
"currency",
")",
":",
"if",
"isinstance",
"(",
"coins",
",",
"Decimal",
")",
":",
"use_decimal",
"=",
"True",
"else",
":",
"use_decimal",
"=",
"self",
".",
"_force_decimal",
"url",
"=",
"'https:/... | Convert X bit coins to valid currency amount | [
"Convert",
"X",
"bit",
"coins",
"to",
"valid",
"currency",
"amount"
] | dc34868ec7c7eb49b3b963d6daa3897b7095ba09 | https://github.com/MicroPyramid/forex-python/blob/dc34868ec7c7eb49b3b963d6daa3897b7095ba09/forex_python/bitcoin.py#L99-L121 |
243,502 | MicroPyramid/forex-python | forex_python/bitcoin.py | BtcConverter.convert_to_btc_on | 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')
end = date_obj.strftime('%Y-%m-%d')
url = (
'https://api.coindesk.com/v1/bpi/historical/close.json'
'?start={}&end={}¤cy={}'.format(
start, end, currency
)
)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi', {}).get(start, None)
if price:
if use_decimal:
price = Decimal(price)
try:
converted_btc = amount/price
return converted_btc
except TypeError:
raise DecimalFloatMismatchError("convert_to_btc_on requires amount parameter is of type Decimal when force_decimal=True")
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given Date") | python | def convert_to_btc_on(self, amount, currency, date_obj):
if isinstance(amount, Decimal):
use_decimal = True
else:
use_decimal = self._force_decimal
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={}&end={}¤cy={}'.format(
start, end, currency
)
)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi', {}).get(start, None)
if price:
if use_decimal:
price = Decimal(price)
try:
converted_btc = amount/price
return converted_btc
except TypeError:
raise DecimalFloatMismatchError("convert_to_btc_on requires amount parameter is of type Decimal when force_decimal=True")
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given Date") | [
"def",
"convert_to_btc_on",
"(",
"self",
",",
"amount",
",",
"currency",
",",
"date_obj",
")",
":",
"if",
"isinstance",
"(",
"amount",
",",
"Decimal",
")",
":",
"use_decimal",
"=",
"True",
"else",
":",
"use_decimal",
"=",
"self",
".",
"_force_decimal",
"st... | Convert X amount to BTC based on given date rate | [
"Convert",
"X",
"amount",
"to",
"BTC",
"based",
"on",
"given",
"date",
"rate"
] | dc34868ec7c7eb49b3b963d6daa3897b7095ba09 | https://github.com/MicroPyramid/forex-python/blob/dc34868ec7c7eb49b3b963d6daa3897b7095ba09/forex_python/bitcoin.py#L123-L152 |
243,503 | DocNow/twarc | twarc/decorators.py | rate_limit | 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 resp.status_code == 200:
errors = 0
return resp
elif resp.status_code == 401:
# Hack to retain the original exception, but augment it with
# additional context for the user to interpret it. In a Python
# 3 only future we can raise a new exception of the same type
# with a new message from the old error.
try:
resp.raise_for_status()
except requests.HTTPError as e:
message = "\nThis is a protected or locked account, or" +\
" the credentials provided are no longer valid."
e.args = (e.args[0] + message,) + e.args[1:]
log.warning("401 Authentication required for %s", resp.url)
raise
elif resp.status_code == 429:
reset = int(resp.headers['x-rate-limit-reset'])
now = time.time()
seconds = reset - now + 10
if seconds < 1:
seconds = 10
log.warning("rate limit exceeded: sleeping %s secs", seconds)
time.sleep(seconds)
elif resp.status_code >= 500:
errors += 1
if errors > 30:
log.warning("too many errors from Twitter, giving up")
resp.raise_for_status()
seconds = 60 * errors
log.warning("%s from Twitter API, sleeping %s",
resp.status_code, seconds)
time.sleep(seconds)
else:
resp.raise_for_status()
return new_f | python | def rate_limit(f):
def new_f(*args, **kwargs):
errors = 0
while True:
resp = f(*args, **kwargs)
if resp.status_code == 200:
errors = 0
return resp
elif resp.status_code == 401:
# Hack to retain the original exception, but augment it with
# additional context for the user to interpret it. In a Python
# 3 only future we can raise a new exception of the same type
# with a new message from the old error.
try:
resp.raise_for_status()
except requests.HTTPError as e:
message = "\nThis is a protected or locked account, or" +\
" the credentials provided are no longer valid."
e.args = (e.args[0] + message,) + e.args[1:]
log.warning("401 Authentication required for %s", resp.url)
raise
elif resp.status_code == 429:
reset = int(resp.headers['x-rate-limit-reset'])
now = time.time()
seconds = reset - now + 10
if seconds < 1:
seconds = 10
log.warning("rate limit exceeded: sleeping %s secs", seconds)
time.sleep(seconds)
elif resp.status_code >= 500:
errors += 1
if errors > 30:
log.warning("too many errors from Twitter, giving up")
resp.raise_for_status()
seconds = 60 * errors
log.warning("%s from Twitter API, sleeping %s",
resp.status_code, seconds)
time.sleep(seconds)
else:
resp.raise_for_status()
return new_f | [
"def",
"rate_limit",
"(",
"f",
")",
":",
"def",
"new_f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"errors",
"=",
"0",
"while",
"True",
":",
"resp",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"resp",
".",
"stat... | 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. | [
"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",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/decorators.py#L8-L53 |
243,504 | DocNow/twarc | twarc/decorators.py | catch_timeout | 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:
log.warning("caught read timeout: %s", e)
self.connect()
return f(self, *args, **kwargs)
return new_f | python | def catch_timeout(f):
def new_f(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except (requests.exceptions.ReadTimeout,
requests.packages.urllib3.exceptions.ReadTimeoutError) as e:
log.warning("caught read timeout: %s", e)
self.connect()
return f(self, *args, **kwargs)
return new_f | [
"def",
"catch_timeout",
"(",
"f",
")",
":",
"def",
"new_f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"(",
"requests",
"."... | A decorator to handle read timeouts from Twitter. | [
"A",
"decorator",
"to",
"handle",
"read",
"timeouts",
"from",
"Twitter",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/decorators.py#L81-L93 |
243,505 | DocNow/twarc | twarc/decorators.py | catch_gzip_errors | 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.warning("caught gzip error: %s", e)
self.connect()
return f(self, *args, **kwargs)
return new_f | python | def catch_gzip_errors(f):
def new_f(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except requests.exceptions.ContentDecodingError as e:
log.warning("caught gzip error: %s", e)
self.connect()
return f(self, *args, **kwargs)
return new_f | [
"def",
"catch_gzip_errors",
"(",
"f",
")",
":",
"def",
"new_f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"requests",
".",
... | A decorator to handle gzip encoding errors which have been known to
happen during hydration. | [
"A",
"decorator",
"to",
"handle",
"gzip",
"encoding",
"errors",
"which",
"have",
"been",
"known",
"to",
"happen",
"during",
"hydration",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/decorators.py#L96-L108 |
243,506 | DocNow/twarc | twarc/decorators.py | interruptible_sleep | 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 | def interruptible_sleep(t, event=None):
log.info("sleeping %s", t)
if event is None:
time.sleep(t)
return False
else:
return not event.wait(t) | [
"def",
"interruptible_sleep",
"(",
"t",
",",
"event",
"=",
"None",
")",
":",
"log",
".",
"info",
"(",
"\"sleeping %s\"",
",",
"t",
")",
"if",
"event",
"is",
"None",
":",
"time",
".",
"sleep",
"(",
"t",
")",
"return",
"False",
"else",
":",
"return",
... | Sleeps for a specified duration, optionally stopping early for event.
Returns True if interrupted | [
"Sleeps",
"for",
"a",
"specified",
"duration",
"optionally",
"stopping",
"early",
"for",
"event",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/decorators.py#L111-L123 |
243,507 | DocNow/twarc | twarc/decorators.py | filter_protected | 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']['protected']:
continue
elif 'protected' in obj and obj['protected']:
continue
yield obj
return new_f | python | def filter_protected(f):
def new_f(self, *args, **kwargs):
for obj in f(self, *args, **kwargs):
if self.protected == False:
if 'user' in obj and obj['user']['protected']:
continue
elif 'protected' in obj and obj['protected']:
continue
yield obj
return new_f | [
"def",
"filter_protected",
"(",
"f",
")",
":",
"def",
"new_f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"obj",
"in",
"f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"pr... | filter_protected will filter out protected tweets and users unless
explicitly requested not to. | [
"filter_protected",
"will",
"filter",
"out",
"protected",
"tweets",
"and",
"users",
"unless",
"explicitly",
"requested",
"not",
"to",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/decorators.py#L125-L139 |
243,508 | DocNow/twarc | utils/extractor.py | tweets_files | 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 | def tweets_files(string, 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 | [
"def",
"tweets_files",
"(",
"string",
",",
"path",
")",
":",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"if",
"re",
".",
"match",
"(",
"string",
",",
"filename",
")",
"and",
"\".jsonl\"",
"in",
"filename",
":",
"f",
"=",
... | Iterates over json files in path. | [
"Iterates",
"over",
"json",
"files",
"in",
"path",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/utils/extractor.py#L38-L45 |
243,509 | DocNow/twarc | utils/extractor.py | extract | 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 = []
for value in item:
if value is None:
value = "NA"
new = copy.deepcopy(found)
for row in new:
row.append(value)
found1.extend(new)
found = found1
for row in found:
csv_writer.writerow(row)
return len(found) | python | def extract(json_object, args, csv_writer):
found = [[]]
for attribute in args.attributes:
item = attribute.getElement(json_object)
if len(item) == 0:
for row in found:
row.append("NA")
else:
found1 = []
for value in item:
if value is None:
value = "NA"
new = copy.deepcopy(found)
for row in new:
row.append(value)
found1.extend(new)
found = found1
for row in found:
csv_writer.writerow(row)
return len(found) | [
"def",
"extract",
"(",
"json_object",
",",
"args",
",",
"csv_writer",
")",
":",
"found",
"=",
"[",
"[",
"]",
"]",
"for",
"attribute",
"in",
"args",
".",
"attributes",
":",
"item",
"=",
"attribute",
".",
"getElement",
"(",
"json_object",
")",
"if",
"len... | Extract and write found attributes. | [
"Extract",
"and",
"write",
"found",
"attributes",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/utils/extractor.py#L91-L113 |
243,510 | DocNow/twarc | utils/network.py | add | 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]['weight'] + 1
else:
weight = 1
G.add_edge(from_user, to_user, type=type, weight=weight)
elif not options.users and to_id:
G.add_node(from_id, screen_name=from_user, type=type)
if to_user:
G.add_node(to_id, screen_name=to_user)
else:
G.add_node(to_id)
G.add_edge(from_id, to_id, type=type) | python | 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]['weight'] + 1
else:
weight = 1
G.add_edge(from_user, to_user, type=type, weight=weight)
elif not options.users and to_id:
G.add_node(from_id, screen_name=from_user, type=type)
if to_user:
G.add_node(to_id, screen_name=to_user)
else:
G.add_node(to_id)
G.add_edge(from_id, to_id, type=type) | [
"def",
"add",
"(",
"from_user",
",",
"from_id",
",",
"to_user",
",",
"to_id",
",",
"type",
")",
":",
"if",
"options",
".",
"users",
"and",
"to_user",
":",
"G",
".",
"add_node",
"(",
"from_user",
",",
"screen_name",
"=",
"from_user",
")",
"G",
".",
"a... | adds a relation to the graph | [
"adds",
"a",
"relation",
"to",
"the",
"graph"
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/utils/network.py#L72-L91 |
243,511 | DocNow/twarc | twarc/client.py | Twarc.timeline | 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.
"""
if user_id and screen_name:
raise ValueError('only user_id or screen_name may be passed')
# Strip if screen_name is prefixed with '@'
if screen_name:
screen_name = screen_name.lstrip('@')
id = screen_name or str(user_id)
id_type = "screen_name" if screen_name else "user_id"
log.info("starting user timeline for user %s", id)
if screen_name or user_id:
url = "https://api.twitter.com/1.1/statuses/user_timeline.json"
else:
url = "https://api.twitter.com/1.1/statuses/home_timeline.json"
params = {"count": 200, id_type: id, "include_ext_alt_text": "true"}
retrieved_pages = 0
reached_end = False
while True:
if since_id:
# Make the since_id inclusive, so we can avoid retrieving
# an empty page of results in some cases
params['since_id'] = str(int(since_id) - 1)
if max_id:
params['max_id'] = max_id
try:
resp = self.get(url, params=params, allow_404=True)
retrieved_pages += 1
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
log.warn("no timeline available for %s", id)
break
elif e.response.status_code == 401:
log.warn("protected account %s", id)
break
raise e
statuses = resp.json()
if len(statuses) == 0:
log.info("no new tweets matching %s", params)
break
for status in statuses:
# We've certainly reached the end of new results
if since_id is not None and status['id_str'] == str(since_id):
reached_end = True
break
# If you request an invalid user_id, you may still get
# results so need to check.
if not user_id or id == status.get("user",
{}).get("id_str"):
yield status
if reached_end:
log.info("no new tweets matching %s", params)
break
if max_pages is not None and retrieved_pages == max_pages:
log.info("reached max page limit for %s", params)
break
max_id = str(int(status["id_str"]) - 1) | python | def timeline(self, user_id=None, screen_name=None, max_id=None,
since_id=None, max_pages=None):
if user_id and screen_name:
raise ValueError('only user_id or screen_name may be passed')
# Strip if screen_name is prefixed with '@'
if screen_name:
screen_name = screen_name.lstrip('@')
id = screen_name or str(user_id)
id_type = "screen_name" if screen_name else "user_id"
log.info("starting user timeline for user %s", id)
if screen_name or user_id:
url = "https://api.twitter.com/1.1/statuses/user_timeline.json"
else:
url = "https://api.twitter.com/1.1/statuses/home_timeline.json"
params = {"count": 200, id_type: id, "include_ext_alt_text": "true"}
retrieved_pages = 0
reached_end = False
while True:
if since_id:
# Make the since_id inclusive, so we can avoid retrieving
# an empty page of results in some cases
params['since_id'] = str(int(since_id) - 1)
if max_id:
params['max_id'] = max_id
try:
resp = self.get(url, params=params, allow_404=True)
retrieved_pages += 1
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
log.warn("no timeline available for %s", id)
break
elif e.response.status_code == 401:
log.warn("protected account %s", id)
break
raise e
statuses = resp.json()
if len(statuses) == 0:
log.info("no new tweets matching %s", params)
break
for status in statuses:
# We've certainly reached the end of new results
if since_id is not None and status['id_str'] == str(since_id):
reached_end = True
break
# If you request an invalid user_id, you may still get
# results so need to check.
if not user_id or id == status.get("user",
{}).get("id_str"):
yield status
if reached_end:
log.info("no new tweets matching %s", params)
break
if max_pages is not None and retrieved_pages == max_pages:
log.info("reached max page limit for %s", params)
break
max_id = str(int(status["id_str"]) - 1) | [
"def",
"timeline",
"(",
"self",
",",
"user_id",
"=",
"None",
",",
"screen_name",
"=",
"None",
",",
"max_id",
"=",
"None",
",",
"since_id",
"=",
"None",
",",
"max_pages",
"=",
"None",
")",
":",
"if",
"user_id",
"and",
"screen_name",
":",
"raise",
"Value... | 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. | [
"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",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L138-L211 |
243,512 | DocNow/twarc | twarc/client.py | Twarc.follower_ids | 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'
if re.match(r'^\d+$', user):
params = {'user_id': user, 'cursor': -1}
else:
params = {'screen_name': user, 'cursor': -1}
while params['cursor'] != 0:
try:
resp = self.get(url, params=params, allow_404=True)
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
log.info("no users matching %s", screen_name)
raise e
user_ids = resp.json()
for user_id in user_ids['ids']:
yield str_type(user_id)
params['cursor'] = user_ids['next_cursor'] | python | def follower_ids(self, user):
user = str(user)
user = user.lstrip('@')
url = 'https://api.twitter.com/1.1/followers/ids.json'
if re.match(r'^\d+$', user):
params = {'user_id': user, 'cursor': -1}
else:
params = {'screen_name': user, 'cursor': -1}
while params['cursor'] != 0:
try:
resp = self.get(url, params=params, allow_404=True)
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
log.info("no users matching %s", screen_name)
raise e
user_ids = resp.json()
for user_id in user_ids['ids']:
yield str_type(user_id)
params['cursor'] = user_ids['next_cursor'] | [
"def",
"follower_ids",
"(",
"self",
",",
"user",
")",
":",
"user",
"=",
"str",
"(",
"user",
")",
"user",
"=",
"user",
".",
"lstrip",
"(",
"'@'",
")",
"url",
"=",
"'https://api.twitter.com/1.1/followers/ids.json'",
"if",
"re",
".",
"match",
"(",
"r'^\\d+$'"... | Returns Twitter user id lists for the specified user's followers.
A user can be a specific using their screen_name or user_id | [
"Returns",
"Twitter",
"user",
"id",
"lists",
"for",
"the",
"specified",
"user",
"s",
"followers",
".",
"A",
"user",
"can",
"be",
"a",
"specific",
"using",
"their",
"screen_name",
"or",
"user_id"
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L254-L278 |
243,513 | DocNow/twarc | twarc/client.py | Twarc.filter | 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 set,
the filter will be interrupted.
"""
if locations is not None:
if type(locations) == list:
locations = ','.join(locations)
locations = locations.replace('\\', '')
url = 'https://stream.twitter.com/1.1/statuses/filter.json'
params = {
"stall_warning": True,
"include_ext_alt_text": True
}
if track:
params["track"] = track
if follow:
params["follow"] = follow
if locations:
params["locations"] = locations
headers = {'accept-encoding': 'deflate, gzip'}
errors = 0
while True:
try:
log.info("connecting to filter stream for %s", params)
resp = self.post(url, params, headers=headers, stream=True)
errors = 0
for line in resp.iter_lines(chunk_size=1024):
if event and event.is_set():
log.info("stopping filter")
# Explicitly close response
resp.close()
return
if not line:
log.info("keep-alive")
if record_keepalive:
yield "keep-alive"
continue
try:
yield json.loads(line.decode())
except Exception as e:
log.error("json parse error: %s - %s", e, line)
except requests.exceptions.HTTPError as e:
errors += 1
log.error("caught http error %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many errors")
raise e
if e.response.status_code == 420:
if interruptible_sleep(errors * 60, event):
log.info("stopping filter")
return
else:
if interruptible_sleep(errors * 5, event):
log.info("stopping filter")
return
except Exception as e:
errors += 1
log.error("caught exception %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many exceptions")
raise e
log.error(e)
if interruptible_sleep(errors, event):
log.info("stopping filter")
return | python | def filter(self, track=None, follow=None, locations=None, event=None,
record_keepalive=False):
if locations is not None:
if type(locations) == list:
locations = ','.join(locations)
locations = locations.replace('\\', '')
url = 'https://stream.twitter.com/1.1/statuses/filter.json'
params = {
"stall_warning": True,
"include_ext_alt_text": True
}
if track:
params["track"] = track
if follow:
params["follow"] = follow
if locations:
params["locations"] = locations
headers = {'accept-encoding': 'deflate, gzip'}
errors = 0
while True:
try:
log.info("connecting to filter stream for %s", params)
resp = self.post(url, params, headers=headers, stream=True)
errors = 0
for line in resp.iter_lines(chunk_size=1024):
if event and event.is_set():
log.info("stopping filter")
# Explicitly close response
resp.close()
return
if not line:
log.info("keep-alive")
if record_keepalive:
yield "keep-alive"
continue
try:
yield json.loads(line.decode())
except Exception as e:
log.error("json parse error: %s - %s", e, line)
except requests.exceptions.HTTPError as e:
errors += 1
log.error("caught http error %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many errors")
raise e
if e.response.status_code == 420:
if interruptible_sleep(errors * 60, event):
log.info("stopping filter")
return
else:
if interruptible_sleep(errors * 5, event):
log.info("stopping filter")
return
except Exception as e:
errors += 1
log.error("caught exception %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many exceptions")
raise e
log.error(e)
if interruptible_sleep(errors, event):
log.info("stopping filter")
return | [
"def",
"filter",
"(",
"self",
",",
"track",
"=",
"None",
",",
"follow",
"=",
"None",
",",
"locations",
"=",
"None",
",",
"event",
"=",
"None",
",",
"record_keepalive",
"=",
"False",
")",
":",
"if",
"locations",
"is",
"not",
"None",
":",
"if",
"type",... | 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 set,
the filter will be interrupted. | [
"Returns",
"an",
"iterator",
"for",
"tweets",
"that",
"match",
"a",
"given",
"filter",
"track",
"from",
"the",
"livestream",
"of",
"tweets",
"happening",
"right",
"now",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L308-L378 |
243,514 | DocNow/twarc | twarc/client.py | Twarc.sample | 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 is provided for event and the event is set,
the sample will be interrupted.
"""
url = 'https://stream.twitter.com/1.1/statuses/sample.json'
params = {"stall_warning": True}
headers = {'accept-encoding': 'deflate, gzip'}
errors = 0
while True:
try:
log.info("connecting to sample stream")
resp = self.post(url, params, headers=headers, stream=True)
errors = 0
for line in resp.iter_lines(chunk_size=512):
if event and event.is_set():
log.info("stopping sample")
# Explicitly close response
resp.close()
return
if line == "":
log.info("keep-alive")
if record_keepalive:
yield "keep-alive"
continue
try:
yield json.loads(line.decode())
except Exception as e:
log.error("json parse error: %s - %s", e, line)
except requests.exceptions.HTTPError as e:
errors += 1
log.error("caught http error %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many errors")
raise e
if e.response.status_code == 420:
if interruptible_sleep(errors * 60, event):
log.info("stopping filter")
return
else:
if interruptible_sleep(errors * 5, event):
log.info("stopping filter")
return
except Exception as e:
errors += 1
log.error("caught exception %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many errors")
raise e
if interruptible_sleep(errors, event):
log.info("stopping filter")
return | python | def sample(self, event=None, record_keepalive=False):
url = 'https://stream.twitter.com/1.1/statuses/sample.json'
params = {"stall_warning": True}
headers = {'accept-encoding': 'deflate, gzip'}
errors = 0
while True:
try:
log.info("connecting to sample stream")
resp = self.post(url, params, headers=headers, stream=True)
errors = 0
for line in resp.iter_lines(chunk_size=512):
if event and event.is_set():
log.info("stopping sample")
# Explicitly close response
resp.close()
return
if line == "":
log.info("keep-alive")
if record_keepalive:
yield "keep-alive"
continue
try:
yield json.loads(line.decode())
except Exception as e:
log.error("json parse error: %s - %s", e, line)
except requests.exceptions.HTTPError as e:
errors += 1
log.error("caught http error %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many errors")
raise e
if e.response.status_code == 420:
if interruptible_sleep(errors * 60, event):
log.info("stopping filter")
return
else:
if interruptible_sleep(errors * 5, event):
log.info("stopping filter")
return
except Exception as e:
errors += 1
log.error("caught exception %s on %s try", e, errors)
if self.http_errors and errors == self.http_errors:
log.warning("too many errors")
raise e
if interruptible_sleep(errors, event):
log.info("stopping filter")
return | [
"def",
"sample",
"(",
"self",
",",
"event",
"=",
"None",
",",
"record_keepalive",
"=",
"False",
")",
":",
"url",
"=",
"'https://stream.twitter.com/1.1/statuses/sample.json'",
"params",
"=",
"{",
"\"stall_warning\"",
":",
"True",
"}",
"headers",
"=",
"{",
"'accep... | 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 is provided for event and the event is set,
the sample will be interrupted. | [
"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",... | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L380-L436 |
243,515 | DocNow/twarc | twarc/client.py | Twarc.dehydrate | 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: %s\n" % e) | python | def dehydrate(self, iterator):
for line in iterator:
try:
yield json.loads(line)['id_str']
except Exception as e:
log.error("uhoh: %s\n" % e) | [
"def",
"dehydrate",
"(",
"self",
",",
"iterator",
")",
":",
"for",
"line",
"in",
"iterator",
":",
"try",
":",
"yield",
"json",
".",
"loads",
"(",
"line",
")",
"[",
"'id_str'",
"]",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"error",
"(",
"\... | Pass in an iterator of tweets' JSON and get back an iterator of the
IDs of each tweet. | [
"Pass",
"in",
"an",
"iterator",
"of",
"tweets",
"JSON",
"and",
"get",
"back",
"an",
"iterator",
"of",
"the",
"IDs",
"of",
"each",
"tweet",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L438-L447 |
243,516 | DocNow/twarc | twarc/client.py | Twarc.hydrate | 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 in iterator:
tweet_id = str(tweet_id)
tweet_id = tweet_id.strip() # remove new line if present
ids.append(tweet_id)
if len(ids) == 100:
log.info("hydrating %s ids", len(ids))
resp = self.post(url, data={
"id": ','.join(ids),
"include_ext_alt_text": 'true'
})
tweets = resp.json()
tweets.sort(key=lambda t: t['id_str'])
for tweet in tweets:
yield tweet
ids = []
# hydrate any remaining ones
if len(ids) > 0:
log.info("hydrating %s", ids)
resp = self.post(url, data={
"id": ','.join(ids),
"include_ext_alt_text": 'true'
})
for tweet in resp.json():
yield tweet | python | def hydrate(self, iterator):
ids = []
url = "https://api.twitter.com/1.1/statuses/lookup.json"
# lookup 100 tweets at a time
for tweet_id in iterator:
tweet_id = str(tweet_id)
tweet_id = tweet_id.strip() # remove new line if present
ids.append(tweet_id)
if len(ids) == 100:
log.info("hydrating %s ids", len(ids))
resp = self.post(url, data={
"id": ','.join(ids),
"include_ext_alt_text": 'true'
})
tweets = resp.json()
tweets.sort(key=lambda t: t['id_str'])
for tweet in tweets:
yield tweet
ids = []
# hydrate any remaining ones
if len(ids) > 0:
log.info("hydrating %s", ids)
resp = self.post(url, data={
"id": ','.join(ids),
"include_ext_alt_text": 'true'
})
for tweet in resp.json():
yield tweet | [
"def",
"hydrate",
"(",
"self",
",",
"iterator",
")",
":",
"ids",
"=",
"[",
"]",
"url",
"=",
"\"https://api.twitter.com/1.1/statuses/lookup.json\"",
"# lookup 100 tweets at a time",
"for",
"tweet_id",
"in",
"iterator",
":",
"tweet_id",
"=",
"str",
"(",
"tweet_id",
... | Pass in an iterator of tweet ids and get back an iterator for the
decoded JSON for each corresponding tweet. | [
"Pass",
"in",
"an",
"iterator",
"of",
"tweet",
"ids",
"and",
"get",
"back",
"an",
"iterator",
"for",
"the",
"decoded",
"JSON",
"for",
"each",
"corresponding",
"tweet",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L449-L482 |
243,517 | DocNow/twarc | twarc/client.py | Twarc.retweets | 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(url, params={"count": 100})
for tweet in resp.json():
yield tweet | python | def retweets(self, tweet_id):
log.info("retrieving retweets of %s", tweet_id)
url = "https://api.twitter.com/1.1/statuses/retweets/""{}.json".format(
tweet_id)
resp = self.get(url, params={"count": 100})
for tweet in resp.json():
yield tweet | [
"def",
"retweets",
"(",
"self",
",",
"tweet_id",
")",
":",
"log",
".",
"info",
"(",
"\"retrieving retweets of %s\"",
",",
"tweet_id",
")",
"url",
"=",
"\"https://api.twitter.com/1.1/statuses/retweets/\"",
"\"{}.json\"",
".",
"format",
"(",
"tweet_id",
")",
"resp",
... | Retrieves up to the last 100 retweets for the provided
tweet. | [
"Retrieves",
"up",
"to",
"the",
"last",
"100",
"retweets",
"for",
"the",
"provided",
"tweet",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L490-L501 |
243,518 | DocNow/twarc | twarc/client.py | Twarc.trends_available | 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 resp.json() | python | def trends_available(self):
url = 'https://api.twitter.com/1.1/trends/available.json'
try:
resp = self.get(url)
except requests.exceptions.HTTPError as e:
raise e
return resp.json() | [
"def",
"trends_available",
"(",
"self",
")",
":",
"url",
"=",
"'https://api.twitter.com/1.1/trends/available.json'",
"try",
":",
"resp",
"=",
"self",
".",
"get",
"(",
"url",
")",
"except",
"requests",
".",
"exceptions",
".",
"HTTPError",
"as",
"e",
":",
"raise... | Returns a list of regions for which Twitter tracks trends. | [
"Returns",
"a",
"list",
"of",
"regions",
"for",
"which",
"Twitter",
"tracks",
"trends",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L503-L512 |
243,519 | DocNow/twarc | twarc/client.py | Twarc.trends_place | 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}
if exclude:
params['exclude'] = exclude
try:
resp = self.get(url, params=params, allow_404=True)
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
log.info("no region matching WOEID %s", woeid)
raise e
return resp.json() | python | def trends_place(self, woeid, exclude=None):
url = 'https://api.twitter.com/1.1/trends/place.json'
params = {'id': woeid}
if exclude:
params['exclude'] = exclude
try:
resp = self.get(url, params=params, allow_404=True)
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
log.info("no region matching WOEID %s", woeid)
raise e
return resp.json() | [
"def",
"trends_place",
"(",
"self",
",",
"woeid",
",",
"exclude",
"=",
"None",
")",
":",
"url",
"=",
"'https://api.twitter.com/1.1/trends/place.json'",
"params",
"=",
"{",
"'id'",
":",
"woeid",
"}",
"if",
"exclude",
":",
"params",
"[",
"'exclude'",
"]",
"=",... | Returns recent Twitter trends for the specified WOEID. If
exclude == 'hashtags', Twitter will remove hashtag trends from the
response. | [
"Returns",
"recent",
"Twitter",
"trends",
"for",
"the",
"specified",
"WOEID",
".",
"If",
"exclude",
"==",
"hashtags",
"Twitter",
"will",
"remove",
"hashtag",
"trends",
"from",
"the",
"response",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L514-L530 |
243,520 | DocNow/twarc | twarc/client.py | Twarc.replies | 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 of the replies. It also walk up the reply chain if you
supply a tweet that is itself a reply to another tweet. You can
optionally supply a tuple of tweet ids to ignore during this traversal
using the prune parameter.
"""
yield tweet
# get replies to the tweet
screen_name = tweet['user']['screen_name']
tweet_id = tweet['id_str']
log.info("looking for replies to: %s", tweet_id)
for reply in self.search("to:%s" % screen_name, since_id=tweet_id):
if reply['in_reply_to_status_id_str'] != tweet_id:
continue
if reply['id_str'] in prune:
log.info("ignoring pruned tweet id %s", reply['id_str'])
continue
log.info("found reply: %s", reply["id_str"])
if recursive:
if reply['id_str'] not in prune:
prune = prune + (tweet_id,)
for r in self.replies(reply, recursive, prune):
yield r
else:
yield reply
# if this tweet is itself a reply to another tweet get it and
# get other potential replies to it
reply_to_id = tweet.get('in_reply_to_status_id_str')
log.info("prune=%s", prune)
if recursive and reply_to_id and reply_to_id not in prune:
t = self.tweet(reply_to_id)
if t:
log.info("found reply-to: %s", t['id_str'])
prune = prune + (tweet['id_str'],)
for r in self.replies(t, recursive=True, prune=prune):
yield r
# if this tweet is a quote go get that too whatever tweets it
# may be in reply to
quote_id = tweet.get('quotes_status_id_str')
if recursive and quote_id and quote_id not in prune:
t = self.tweet(quote_id)
if t:
log.info("found quote: %s", t['id_str'])
prune = prune + (tweet['id_str'],)
for r in self.replies(t, recursive=True, prune=prune):
yield r | python | def replies(self, tweet, recursive=False, prune=()):
yield tweet
# get replies to the tweet
screen_name = tweet['user']['screen_name']
tweet_id = tweet['id_str']
log.info("looking for replies to: %s", tweet_id)
for reply in self.search("to:%s" % screen_name, since_id=tweet_id):
if reply['in_reply_to_status_id_str'] != tweet_id:
continue
if reply['id_str'] in prune:
log.info("ignoring pruned tweet id %s", reply['id_str'])
continue
log.info("found reply: %s", reply["id_str"])
if recursive:
if reply['id_str'] not in prune:
prune = prune + (tweet_id,)
for r in self.replies(reply, recursive, prune):
yield r
else:
yield reply
# if this tweet is itself a reply to another tweet get it and
# get other potential replies to it
reply_to_id = tweet.get('in_reply_to_status_id_str')
log.info("prune=%s", prune)
if recursive and reply_to_id and reply_to_id not in prune:
t = self.tweet(reply_to_id)
if t:
log.info("found reply-to: %s", t['id_str'])
prune = prune + (tweet['id_str'],)
for r in self.replies(t, recursive=True, prune=prune):
yield r
# if this tweet is a quote go get that too whatever tweets it
# may be in reply to
quote_id = tweet.get('quotes_status_id_str')
if recursive and quote_id and quote_id not in prune:
t = self.tweet(quote_id)
if t:
log.info("found quote: %s", t['id_str'])
prune = prune + (tweet['id_str'],)
for r in self.replies(t, recursive=True, prune=prune):
yield r | [
"def",
"replies",
"(",
"self",
",",
"tweet",
",",
"recursive",
"=",
"False",
",",
"prune",
"=",
"(",
")",
")",
":",
"yield",
"tweet",
"# get replies to the tweet",
"screen_name",
"=",
"tweet",
"[",
"'user'",
"]",
"[",
"'screen_name'",
"]",
"tweet_id",
"=",... | 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 of the replies. It also walk up the reply chain if you
supply a tweet that is itself a reply to another tweet. You can
optionally supply a tuple of tweet ids to ignore during this traversal
using the prune parameter. | [
"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",
... | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L544-L603 |
243,521 | DocNow/twarc | twarc/client.py | Twarc.list_members | 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://api.twitter.com/1.1/lists/members.json'
params = {'cursor': -1}
if list_id:
params['list_id'] = list_id
else:
params['slug'] = slug
if owner_screen_name:
params['owner_screen_name'] = owner_screen_name
else:
params['owner_id'] = owner_id
while params['cursor'] != 0:
try:
resp = self.get(url, params=params, allow_404=True)
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
log.error("no matching list")
raise e
users = resp.json()
for user in users['users']:
yield user
params['cursor'] = users['next_cursor'] | python | def list_members(self, list_id=None, slug=None, owner_screen_name=None, owner_id=None):
assert list_id or (slug and (owner_screen_name or owner_id))
url = 'https://api.twitter.com/1.1/lists/members.json'
params = {'cursor': -1}
if list_id:
params['list_id'] = list_id
else:
params['slug'] = slug
if owner_screen_name:
params['owner_screen_name'] = owner_screen_name
else:
params['owner_id'] = owner_id
while params['cursor'] != 0:
try:
resp = self.get(url, params=params, allow_404=True)
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
log.error("no matching list")
raise e
users = resp.json()
for user in users['users']:
yield user
params['cursor'] = users['next_cursor'] | [
"def",
"list_members",
"(",
"self",
",",
"list_id",
"=",
"None",
",",
"slug",
"=",
"None",
",",
"owner_screen_name",
"=",
"None",
",",
"owner_id",
"=",
"None",
")",
":",
"assert",
"list_id",
"or",
"(",
"slug",
"and",
"(",
"owner_screen_name",
"or",
"owne... | Returns the members of a list.
List id or (slug and (owner_screen_name or owner_id)) are required | [
"Returns",
"the",
"members",
"of",
"a",
"list",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L605-L634 |
243,522 | DocNow/twarc | twarc/client.py | Twarc.connect | 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("MissingKeys")
if self.client:
log.info("closing existing http session")
self.client.close()
if self.last_response:
log.info("closing last response")
self.last_response.close()
log.info("creating http session")
self.client = OAuth1Session(
client_key=self.consumer_key,
client_secret=self.consumer_secret,
resource_owner_key=self.access_token,
resource_owner_secret=self.access_token_secret
) | python | def connect(self):
if not (self.consumer_key and self.consumer_secret and self.access_token
and self.access_token_secret):
raise RuntimeError("MissingKeys")
if self.client:
log.info("closing existing http session")
self.client.close()
if self.last_response:
log.info("closing last response")
self.last_response.close()
log.info("creating http session")
self.client = OAuth1Session(
client_key=self.consumer_key,
client_secret=self.consumer_secret,
resource_owner_key=self.access_token,
resource_owner_secret=self.access_token_secret
) | [
"def",
"connect",
"(",
"self",
")",
":",
"if",
"not",
"(",
"self",
".",
"consumer_key",
"and",
"self",
".",
"consumer_secret",
"and",
"self",
".",
"access_token",
"and",
"self",
".",
"access_token_secret",
")",
":",
"raise",
"RuntimeError",
"(",
"\"MissingKe... | Sets up the HTTP session to talk to Twitter. If one is active it is
closed and another one is opened. | [
"Sets",
"up",
"the",
"HTTP",
"session",
"to",
"talk",
"to",
"Twitter",
".",
"If",
"one",
"is",
"active",
"it",
"is",
"closed",
"and",
"another",
"one",
"is",
"opened",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L707-L729 |
243,523 | DocNow/twarc | twarc/client.py | Twarc.get_keys | 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('CONSUMER_KEY')
if not self.consumer_secret:
self.consumer_secret = env('CONSUMER_SECRET')
if not self.access_token:
self.access_token = env('ACCESS_TOKEN')
if not self.access_token_secret:
self.access_token_secret = env('ACCESS_TOKEN_SECRET')
if self.config and not (self.consumer_key and
self.consumer_secret and
self.access_token and
self.access_token_secret):
self.load_config() | python | def get_keys(self):
env = os.environ.get
if not self.consumer_key:
self.consumer_key = env('CONSUMER_KEY')
if not self.consumer_secret:
self.consumer_secret = env('CONSUMER_SECRET')
if not self.access_token:
self.access_token = env('ACCESS_TOKEN')
if not self.access_token_secret:
self.access_token_secret = env('ACCESS_TOKEN_SECRET')
if self.config and not (self.consumer_key and
self.consumer_secret and
self.access_token and
self.access_token_secret):
self.load_config() | [
"def",
"get_keys",
"(",
"self",
")",
":",
"env",
"=",
"os",
".",
"environ",
".",
"get",
"if",
"not",
"self",
".",
"consumer_key",
":",
"self",
".",
"consumer_key",
"=",
"env",
"(",
"'CONSUMER_KEY'",
")",
"if",
"not",
"self",
".",
"consumer_secret",
":"... | 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. | [
"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",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L731-L751 |
243,524 | DocNow/twarc | twarc/client.py | Twarc.validate_keys | 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_token_secret
if keys_present:
try:
# Need to explicitly reconnect to confirm the current creds
# are used in the session object.
self.connect()
self.get(url)
except requests.HTTPError as e:
if e.response.status_code == 401:
raise RuntimeError('Invalid credentials provided.')
else:
raise e
else:
raise RuntimeError('Incomplete credentials provided.') | python | def validate_keys(self):
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_token_secret
if keys_present:
try:
# Need to explicitly reconnect to confirm the current creds
# are used in the session object.
self.connect()
self.get(url)
except requests.HTTPError as e:
if e.response.status_code == 401:
raise RuntimeError('Invalid credentials provided.')
else:
raise e
else:
raise RuntimeError('Incomplete credentials provided.') | [
"def",
"validate_keys",
"(",
"self",
")",
":",
"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",
".",... | Validate the keys provided are authentic credentials. | [
"Validate",
"the",
"keys",
"provided",
"are",
"authentic",
"credentials",
"."
] | 47dd87d0c00592a4d583412c9d660ba574fc6f26 | https://github.com/DocNow/twarc/blob/47dd87d0c00592a4d583412c9d660ba574fc6f26/twarc/client.py#L753-L774 |
243,525 | rochacbruno/dynaconf | dynaconf/contrib/flask_dynaconf.py | FlaskDynaconf.init_app | 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 | def init_app(self, app, **kwargs):
self.kwargs.update(kwargs)
self.settings = self.dynaconf_instance or LazySettings(**self.kwargs)
app.config = self.make_config(app)
app.dynaconf = self.settings | [
"def",
"init_app",
"(",
"self",
",",
"app",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"kwargs",
".",
"update",
"(",
"kwargs",
")",
"self",
".",
"settings",
"=",
"self",
".",
"dynaconf_instance",
"or",
"LazySettings",
"(",
"*",
"*",
"self",
".",... | kwargs holds initial dynaconf configuration | [
"kwargs",
"holds",
"initial",
"dynaconf",
"configuration"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/contrib/flask_dynaconf.py#L102-L107 |
243,526 | rochacbruno/dynaconf | dynaconf/contrib/flask_dynaconf.py | DynaconfConfig.get | 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 | def get(self, key, default=None):
return self._settings.get(key, Config.get(self, key, default)) | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"return",
"self",
".",
"_settings",
".",
"get",
"(",
"key",
",",
"Config",
".",
"get",
"(",
"self",
",",
"key",
",",
"default",
")",
")"
] | Gets config from dynaconf variables
if variables does not exists in dynaconf try getting from
`app.config` to support runtime settings. | [
"Gets",
"config",
"from",
"dynaconf",
"variables",
"if",
"variables",
"does",
"not",
"exists",
"in",
"dynaconf",
"try",
"getting",
"from",
"app",
".",
"config",
"to",
"support",
"runtime",
"settings",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/contrib/flask_dynaconf.py#L130-L134 |
243,527 | rochacbruno/dynaconf | dynaconf/utils/__init__.py | object_merge | 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 unique and item in new:
continue
new.insert(0, item)
if isinstance(old, dict) and isinstance(new, dict):
for key, value in old.items():
if key not in new:
new[key] = value
else:
object_merge(value, new[key]) | python | def object_merge(old, new, unique=False):
if isinstance(old, list) and isinstance(new, list):
if old == new:
return
for item in old[::-1]:
if unique and item in new:
continue
new.insert(0, item)
if isinstance(old, dict) and isinstance(new, dict):
for key, value in old.items():
if key not in new:
new[key] = value
else:
object_merge(value, new[key]) | [
"def",
"object_merge",
"(",
"old",
",",
"new",
",",
"unique",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"old",
",",
"list",
")",
"and",
"isinstance",
"(",
"new",
",",
"list",
")",
":",
"if",
"old",
"==",
"new",
":",
"return",
"for",
"item",
... | Recursively merge two data structures.
:param unique: When set to True existing list items are not set. | [
"Recursively",
"merge",
"two",
"data",
"structures",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/utils/__init__.py#L20-L38 |
243,528 | rochacbruno/dynaconf | dynaconf/utils/__init__.py | compat_kwargs | 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():
if c_new == new:
kwargs[c_old] = kwargs[new] | python | def compat_kwargs(kwargs):
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():
if c_new == new:
kwargs[c_old] = kwargs[new] | [
"def",
"compat_kwargs",
"(",
"kwargs",
")",
":",
"warn_deprecations",
"(",
"kwargs",
")",
"for",
"old",
",",
"new",
"in",
"RENAMED_VARS",
".",
"items",
"(",
")",
":",
"if",
"old",
"in",
"kwargs",
":",
"kwargs",
"[",
"new",
"]",
"=",
"kwargs",
"[",
"o... | To keep backwards compat change the kwargs to new names | [
"To",
"keep",
"backwards",
"compat",
"change",
"the",
"kwargs",
"to",
"new",
"names"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/utils/__init__.py#L107-L116 |
243,529 | rochacbruno/dynaconf | dynaconf/utils/__init__.py | deduplicate | 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 | def deduplicate(list_object):
new = []
for item in list_object:
if item not in new:
new.append(item)
return new | [
"def",
"deduplicate",
"(",
"list_object",
")",
":",
"new",
"=",
"[",
"]",
"for",
"item",
"in",
"list_object",
":",
"if",
"item",
"not",
"in",
"new",
":",
"new",
".",
"append",
"(",
"item",
")",
"return",
"new"
] | Rebuild `list_object` removing duplicated and keeping order | [
"Rebuild",
"list_object",
"removing",
"duplicated",
"and",
"keeping",
"order"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/utils/__init__.py#L148-L154 |
243,530 | rochacbruno/dynaconf | dynaconf/utils/__init__.py | trimmed_split | 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 | def trimmed_split(s, 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] | [
"def",
"trimmed_split",
"(",
"s",
",",
"seps",
"=",
"(",
"\";\"",
",",
"\",\"",
")",
")",
":",
"for",
"sep",
"in",
"seps",
":",
"if",
"sep",
"not",
"in",
"s",
":",
"continue",
"data",
"=",
"[",
"item",
".",
"strip",
"(",
")",
"for",
"item",
"in... | Given a string s, split is by one of one of the seps. | [
"Given",
"a",
"string",
"s",
"split",
"is",
"by",
"one",
"of",
"one",
"of",
"the",
"seps",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/utils/__init__.py#L175-L182 |
243,531 | rochacbruno/dynaconf | dynaconf/utils/__init__.py | ensure_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] | python | def ensure_a_list(data):
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] | [
"def",
"ensure_a_list",
"(",
"data",
")",
":",
"if",
"not",
"data",
":",
"return",
"[",
"]",
"if",
"isinstance",
"(",
"data",
",",
"(",
"list",
",",
"tuple",
",",
"set",
")",
")",
":",
"return",
"list",
"(",
"data",
")",
"if",
"isinstance",
"(",
... | Ensure data is a list or wrap it in a list | [
"Ensure",
"data",
"is",
"a",
"list",
"or",
"wrap",
"it",
"in",
"a",
"list"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/utils/__init__.py#L185-L194 |
243,532 | rochacbruno/dynaconf | dynaconf/loaders/redis_loader.py | load | 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
:return: None
"""
redis = StrictRedis(**obj.get("REDIS_FOR_DYNACONF"))
holder = obj.get("ENVVAR_PREFIX_FOR_DYNACONF")
try:
if key:
value = redis.hget(holder.upper(), key)
if value:
obj.logger.debug(
"redis_loader: loading by key: %s:%s (%s:%s)",
key,
value,
IDENTIFIER,
holder,
)
if value:
parsed_value = parse_conf_data(value, tomlfy=True)
if parsed_value:
obj.set(key, parsed_value)
else:
data = {
key: parse_conf_data(value, tomlfy=True)
for key, value in redis.hgetall(holder.upper()).items()
}
if data:
obj.logger.debug(
"redis_loader: loading: %s (%s:%s)",
data,
IDENTIFIER,
holder,
)
obj.update(data, loader_identifier=IDENTIFIER)
except Exception as e:
if silent:
if hasattr(obj, "logger"):
obj.logger.error(str(e))
return False
raise | python | def load(obj, env=None, silent=True, key=None):
redis = StrictRedis(**obj.get("REDIS_FOR_DYNACONF"))
holder = obj.get("ENVVAR_PREFIX_FOR_DYNACONF")
try:
if key:
value = redis.hget(holder.upper(), key)
if value:
obj.logger.debug(
"redis_loader: loading by key: %s:%s (%s:%s)",
key,
value,
IDENTIFIER,
holder,
)
if value:
parsed_value = parse_conf_data(value, tomlfy=True)
if parsed_value:
obj.set(key, parsed_value)
else:
data = {
key: parse_conf_data(value, tomlfy=True)
for key, value in redis.hgetall(holder.upper()).items()
}
if data:
obj.logger.debug(
"redis_loader: loading: %s (%s:%s)",
data,
IDENTIFIER,
holder,
)
obj.update(data, loader_identifier=IDENTIFIER)
except Exception as e:
if silent:
if hasattr(obj, "logger"):
obj.logger.error(str(e))
return False
raise | [
"def",
"load",
"(",
"obj",
",",
"env",
"=",
"None",
",",
"silent",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"redis",
"=",
"StrictRedis",
"(",
"*",
"*",
"obj",
".",
"get",
"(",
"\"REDIS_FOR_DYNACONF\"",
")",
")",
"holder",
"=",
"obj",
".",
... | 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 | [
"Reads",
"and",
"loads",
"in",
"to",
"settings",
"a",
"single",
"key",
"or",
"all",
"keys",
"from",
"redis"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/loaders/redis_loader.py#L16-L60 |
243,533 | rochacbruno/dynaconf | dynaconf/loaders/py_loader.py | load | 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: %s (Ignoring, Not Found)", settings_module
)
return
for setting in dir(mod):
if setting.isupper():
if key is None or key == setting:
setting_value = getattr(mod, setting)
obj.logger.debug(
"py_loader: loading %s: %s (%s)",
setting,
"*****" if "secret" in settings_module else setting_value,
identifier,
)
obj.set(setting, setting_value, loader_identifier=identifier)
obj._loaded_files.append(mod.__file__) | python | def load(obj, settings_module, identifier="py", silent=False, key=None):
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: %s (Ignoring, Not Found)", settings_module
)
return
for setting in dir(mod):
if setting.isupper():
if key is None or key == setting:
setting_value = getattr(mod, setting)
obj.logger.debug(
"py_loader: loading %s: %s (%s)",
setting,
"*****" if "secret" in settings_module else setting_value,
identifier,
)
obj.set(setting, setting_value, loader_identifier=identifier)
obj._loaded_files.append(mod.__file__) | [
"def",
"load",
"(",
"obj",
",",
"settings_module",
",",
"identifier",
"=",
"\"py\"",
",",
"silent",
"=",
"False",
",",
"key",
"=",
"None",
")",
":",
"mod",
",",
"loaded_from",
"=",
"get_module",
"(",
"obj",
",",
"settings_module",
",",
"silent",
")",
"... | Tries to import a python module | [
"Tries",
"to",
"import",
"a",
"python",
"module"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/loaders/py_loader.py#L15-L39 |
243,534 | rochacbruno/dynaconf | dynaconf/loaders/py_loader.py | import_from_filename | 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 then it is trying "
"to load itself entering in a circular reference "
"problem. To solve it you have to "
"invoke your program from another root folder "
"or rename your program file.".format(filename)
)
_find_file = getattr(obj, "find_file", find_file)
if not filename.endswith(".py"):
filename = "{0}.py".format(filename)
if filename in default_settings.SETTINGS_FILE_FOR_DYNACONF:
silent = True
mod = types.ModuleType(filename.rstrip(".py"))
mod.__file__ = filename
mod._is_error = False
try:
with io.open(
_find_file(filename),
encoding=default_settings.ENCODING_FOR_DYNACONF,
) as config_file:
exec(compile(config_file.read(), filename, "exec"), mod.__dict__)
except IOError as e:
e.strerror = ("py_loader: error loading file (%s %s)\n") % (
e.strerror,
filename,
)
if silent and e.errno in (errno.ENOENT, errno.EISDIR):
return
raw_logger().debug(e.strerror)
mod._is_error = True
return mod | python | def import_from_filename(obj, filename, silent=False): # pragma: no cover
if filename in [item.filename for item in inspect.stack()]:
raise ImportError(
"Looks like you are loading dynaconf "
"from inside the {} file and then it is trying "
"to load itself entering in a circular reference "
"problem. To solve it you have to "
"invoke your program from another root folder "
"or rename your program file.".format(filename)
)
_find_file = getattr(obj, "find_file", find_file)
if not filename.endswith(".py"):
filename = "{0}.py".format(filename)
if filename in default_settings.SETTINGS_FILE_FOR_DYNACONF:
silent = True
mod = types.ModuleType(filename.rstrip(".py"))
mod.__file__ = filename
mod._is_error = False
try:
with io.open(
_find_file(filename),
encoding=default_settings.ENCODING_FOR_DYNACONF,
) as config_file:
exec(compile(config_file.read(), filename, "exec"), mod.__dict__)
except IOError as e:
e.strerror = ("py_loader: error loading file (%s %s)\n") % (
e.strerror,
filename,
)
if silent and e.errno in (errno.ENOENT, errno.EISDIR):
return
raw_logger().debug(e.strerror)
mod._is_error = True
return mod | [
"def",
"import_from_filename",
"(",
"obj",
",",
"filename",
",",
"silent",
"=",
"False",
")",
":",
"# pragma: no cover",
"if",
"filename",
"in",
"[",
"item",
".",
"filename",
"for",
"item",
"in",
"inspect",
".",
"stack",
"(",
")",
"]",
":",
"raise",
"Imp... | If settings_module is a filename path import it. | [
"If",
"settings_module",
"is",
"a",
"filename",
"path",
"import",
"it",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/loaders/py_loader.py#L58-L94 |
243,535 | rochacbruno/dynaconf | dynaconf/loaders/vault_loader.py | _get_env_list | 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 with older versions that still uses [dynaconf] as
# [default] env
global_env = obj.get("ENVVAR_PREFIX_FOR_DYNACONF") or "DYNACONF"
if global_env not in env_list:
env_list.append(global_env)
# add the current env
if obj.current_env and obj.current_env not in env_list:
env_list.append(obj.current_env)
# add a manually set env
if env and env not in env_list:
env_list.append(env)
# add the [global] env
env_list.append("GLOBAL")
return [env.lower() for env in env_list] | python | def _get_env_list(obj, env):
# add the [default] env
env_list = [obj.get("DEFAULT_ENV_FOR_DYNACONF")]
# compatibility with older versions that still uses [dynaconf] as
# [default] env
global_env = obj.get("ENVVAR_PREFIX_FOR_DYNACONF") or "DYNACONF"
if global_env not in env_list:
env_list.append(global_env)
# add the current env
if obj.current_env and obj.current_env not in env_list:
env_list.append(obj.current_env)
# add a manually set env
if env and env not in env_list:
env_list.append(env)
# add the [global] env
env_list.append("GLOBAL")
return [env.lower() for env in env_list] | [
"def",
"_get_env_list",
"(",
"obj",
",",
"env",
")",
":",
"# add the [default] env",
"env_list",
"=",
"[",
"obj",
".",
"get",
"(",
"\"DEFAULT_ENV_FOR_DYNACONF\"",
")",
"]",
"# compatibility with older versions that still uses [dynaconf] as",
"# [default] env",
"global_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 | [
"Creates",
"the",
"list",
"of",
"environments",
"to",
"read"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/loaders/vault_loader.py#L18-L40 |
243,536 | rochacbruno/dynaconf | dynaconf/loaders/vault_loader.py | load | 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
:return: None
"""
client = get_client(obj)
env_list = _get_env_list(obj, env)
for env in env_list:
path = "/".join([obj.VAULT_PATH_FOR_DYNACONF, env]).replace("//", "/")
data = client.read(path)
if data:
# There seems to be a data dict within a data dict,
# extract the inner data
data = data.get("data", {}).get("data", {})
try:
if data and key:
value = parse_conf_data(data.get(key), tomlfy=True)
if value:
obj.logger.debug(
"vault_loader: loading by key: %s:%s (%s:%s)",
key,
"****",
IDENTIFIER,
path,
)
obj.set(key, value)
elif data:
obj.logger.debug(
"vault_loader: loading: %s (%s:%s)",
list(data.keys()),
IDENTIFIER,
path,
)
obj.update(data, loader_identifier=IDENTIFIER, tomlfy=True)
except Exception as e:
if silent:
if hasattr(obj, "logger"):
obj.logger.error(str(e))
return False
raise | python | def load(obj, env=None, silent=None, key=None):
client = get_client(obj)
env_list = _get_env_list(obj, env)
for env in env_list:
path = "/".join([obj.VAULT_PATH_FOR_DYNACONF, env]).replace("//", "/")
data = client.read(path)
if data:
# There seems to be a data dict within a data dict,
# extract the inner data
data = data.get("data", {}).get("data", {})
try:
if data and key:
value = parse_conf_data(data.get(key), tomlfy=True)
if value:
obj.logger.debug(
"vault_loader: loading by key: %s:%s (%s:%s)",
key,
"****",
IDENTIFIER,
path,
)
obj.set(key, value)
elif data:
obj.logger.debug(
"vault_loader: loading: %s (%s:%s)",
list(data.keys()),
IDENTIFIER,
path,
)
obj.update(data, loader_identifier=IDENTIFIER, tomlfy=True)
except Exception as e:
if silent:
if hasattr(obj, "logger"):
obj.logger.error(str(e))
return False
raise | [
"def",
"load",
"(",
"obj",
",",
"env",
"=",
"None",
",",
"silent",
"=",
"None",
",",
"key",
"=",
"None",
")",
":",
"client",
"=",
"get_client",
"(",
"obj",
")",
"env_list",
"=",
"_get_env_list",
"(",
"obj",
",",
"env",
")",
"for",
"env",
"in",
"e... | 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 | [
"Reads",
"and",
"loads",
"in",
"to",
"settings",
"a",
"single",
"key",
"or",
"all",
"keys",
"from",
"vault"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/loaders/vault_loader.py#L53-L97 |
243,537 | rochacbruno/dynaconf | dynaconf/cli.py | set_settings | 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_DYNACONF"])
elif "FLASK_APP" in os.environ: # pragma: no cover
with suppress(ImportError, click.UsageError):
from flask.cli import ScriptInfo
flask_app = ScriptInfo().load_app()
settings = flask_app.config
click.echo(
click.style(
"Flask app detected", fg="white", bg="bright_black"
)
)
elif "DJANGO_SETTINGS_MODULE" in os.environ: # pragma: no cover
sys.path.insert(0, os.path.abspath(os.getcwd()))
try:
# Django extension v2
from django.conf import settings
settings.DYNACONF.configure()
except (ImportError, AttributeError):
# Backwards compatible with old django extension (pre 2.0.0)
import dynaconf.contrib.django_dynaconf # noqa
from django.conf import settings as django_settings
django_settings.configure()
settings = django_settings
if settings is not None:
click.echo(
click.style(
"Django app detected", fg="white", bg="bright_black"
)
)
if settings is None:
settings = LazySettings() | python | def set_settings(instance=None):
global settings
settings = None
if instance:
settings = import_settings(instance)
elif "INSTANCE_FOR_DYNACONF" in os.environ:
settings = import_settings(os.environ["INSTANCE_FOR_DYNACONF"])
elif "FLASK_APP" in os.environ: # pragma: no cover
with suppress(ImportError, click.UsageError):
from flask.cli import ScriptInfo
flask_app = ScriptInfo().load_app()
settings = flask_app.config
click.echo(
click.style(
"Flask app detected", fg="white", bg="bright_black"
)
)
elif "DJANGO_SETTINGS_MODULE" in os.environ: # pragma: no cover
sys.path.insert(0, os.path.abspath(os.getcwd()))
try:
# Django extension v2
from django.conf import settings
settings.DYNACONF.configure()
except (ImportError, AttributeError):
# Backwards compatible with old django extension (pre 2.0.0)
import dynaconf.contrib.django_dynaconf # noqa
from django.conf import settings as django_settings
django_settings.configure()
settings = django_settings
if settings is not None:
click.echo(
click.style(
"Django app detected", fg="white", bg="bright_black"
)
)
if settings is None:
settings = LazySettings() | [
"def",
"set_settings",
"(",
"instance",
"=",
"None",
")",
":",
"global",
"settings",
"settings",
"=",
"None",
"if",
"instance",
":",
"settings",
"=",
"import_settings",
"(",
"instance",
")",
"elif",
"\"INSTANCE_FOR_DYNACONF\"",
"in",
"os",
".",
"environ",
":",... | Pick correct settings instance and set it to a global variable. | [
"Pick",
"correct",
"settings",
"instance",
"and",
"set",
"it",
"to",
"a",
"global",
"variable",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/cli.py#L33-L81 |
243,538 | rochacbruno/dynaconf | dynaconf/cli.py | import_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.UsageError(
"invalid path to settings instance: {}".format(dotted_path)
)
try:
module = importlib.import_module(module)
except ImportError as e:
raise click.UsageError(e)
try:
return getattr(module, name)
except AttributeError as e:
raise click.UsageError(e) | python | def import_settings(dotted_path):
if "." in dotted_path:
module, name = dotted_path.rsplit(".", 1)
else:
raise click.UsageError(
"invalid path to settings instance: {}".format(dotted_path)
)
try:
module = importlib.import_module(module)
except ImportError as e:
raise click.UsageError(e)
try:
return getattr(module, name)
except AttributeError as e:
raise click.UsageError(e) | [
"def",
"import_settings",
"(",
"dotted_path",
")",
":",
"if",
"\".\"",
"in",
"dotted_path",
":",
"module",
",",
"name",
"=",
"dotted_path",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"else",
":",
"raise",
"click",
".",
"UsageError",
"(",
"\"invalid path t... | Import settings instance from python dotted path.
Last item in dotted path must be settings instace.
Example: import_settings('path.to.settings') | [
"Import",
"settings",
"instance",
"from",
"python",
"dotted",
"path",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/cli.py#L84-L104 |
243,539 | rochacbruno/dynaconf | dynaconf/cli.py | read_file_in_root_directory | 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 | def read_file_in_root_directory(*names, **kwargs):
return read_file(
os.path.join(os.path.dirname(__file__), *names),
encoding=kwargs.get("encoding", "utf-8"),
) | [
"def",
"read_file_in_root_directory",
"(",
"*",
"names",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"read_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"*",
"names",
")",
",",
"encodi... | Read a file on root dir. | [
"Read",
"a",
"file",
"on",
"root",
"dir",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/cli.py#L119-L124 |
243,540 | rochacbruno/dynaconf | dynaconf/cli.py | show_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() | python | def show_banner(ctx, param, value):
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() | [
"def",
"show_banner",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"if",
"not",
"value",
"or",
"ctx",
".",
"resilient_parsing",
":",
"return",
"set_settings",
"(",
")",
"click",
".",
"echo",
"(",
"settings",
".",
"dynaconf_banner",
")",
"click",
"."... | Shows dynaconf awesome banner | [
"Shows",
"dynaconf",
"awesome",
"banner"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/cli.py#L143-L150 |
243,541 | rochacbruno/dynaconf | dynaconf/cli.py | write | 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 str(path).endswith(constants.ALL_EXTENSIONS + ("py",)):
settings_path = path
secrets_path = path.parent / ".secrets.{}".format(to)
else:
if to == "env":
if str(path) in (".env", "./.env"): # pragma: no cover
settings_path = path
elif str(path).endswith("/.env"):
settings_path = path
elif str(path).endswith(".env"):
settings_path = path.parent / ".env"
else:
settings_path = path / ".env"
Path.touch(settings_path)
secrets_path = None
_vars.update(_secrets)
else:
settings_path = path / "settings.{}".format(to)
secrets_path = path / ".secrets.{}".format(to)
if (
_vars and not y and settings_path and settings_path.exists()
): # pragma: no cover # noqa
click.confirm(
"{} exists do you want to overwrite it?".format(settings_path),
abort=True,
)
if (
_secrets and not y and secrets_path and secrets_path.exists()
): # pragma: no cover # noqa
click.confirm(
"{} exists do you want to overwrite it?".format(secrets_path),
abort=True,
)
if to not in ["py", "env"]:
if _vars:
_vars = {env: _vars}
if _secrets:
_secrets = {env: _secrets}
if _vars and settings_path:
loader.write(settings_path, _vars, merge=True)
click.echo("Data successful written to {}".format(settings_path))
if _secrets and secrets_path:
loader.write(secrets_path, _secrets, merge=True)
click.echo("Data successful written to {}".format(secrets_path))
else: # pragma: no cover
# lets write to external source
with settings.using_env(env):
# make sure we're in the correct environment
loader.write(settings, _vars, **_secrets)
click.echo("Data successful written to {}".format(to)) | python | def write(to, _vars, _secrets, path, env, y):
_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 str(path).endswith(constants.ALL_EXTENSIONS + ("py",)):
settings_path = path
secrets_path = path.parent / ".secrets.{}".format(to)
else:
if to == "env":
if str(path) in (".env", "./.env"): # pragma: no cover
settings_path = path
elif str(path).endswith("/.env"):
settings_path = path
elif str(path).endswith(".env"):
settings_path = path.parent / ".env"
else:
settings_path = path / ".env"
Path.touch(settings_path)
secrets_path = None
_vars.update(_secrets)
else:
settings_path = path / "settings.{}".format(to)
secrets_path = path / ".secrets.{}".format(to)
if (
_vars and not y and settings_path and settings_path.exists()
): # pragma: no cover # noqa
click.confirm(
"{} exists do you want to overwrite it?".format(settings_path),
abort=True,
)
if (
_secrets and not y and secrets_path and secrets_path.exists()
): # pragma: no cover # noqa
click.confirm(
"{} exists do you want to overwrite it?".format(secrets_path),
abort=True,
)
if to not in ["py", "env"]:
if _vars:
_vars = {env: _vars}
if _secrets:
_secrets = {env: _secrets}
if _vars and settings_path:
loader.write(settings_path, _vars, merge=True)
click.echo("Data successful written to {}".format(settings_path))
if _secrets and secrets_path:
loader.write(secrets_path, _secrets, merge=True)
click.echo("Data successful written to {}".format(secrets_path))
else: # pragma: no cover
# lets write to external source
with settings.using_env(env):
# make sure we're in the correct environment
loader.write(settings, _vars, **_secrets)
click.echo("Data successful written to {}".format(to)) | [
"def",
"write",
"(",
"to",
",",
"_vars",
",",
"_secrets",
",",
"path",
",",
"env",
",",
"y",
")",
":",
"_vars",
"=",
"split_vars",
"(",
"_vars",
")",
"_secrets",
"=",
"split_vars",
"(",
"_secrets",
")",
"loader",
"=",
"importlib",
".",
"import_module",... | Writes data to specific source | [
"Writes",
"data",
"to",
"specific",
"source"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/cli.py#L496-L562 |
243,542 | rochacbruno/dynaconf | dynaconf/cli.py | validate | 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).endswith(".toml"):
path = path / "dynaconf_validators.toml"
if not path.exists(): # pragma: no cover # noqa
click.echo(
click.style("{} not found".format(path), fg="white", bg="red")
)
sys.exit(1)
validation_data = toml.load(open(str(path)))
success = True
for env, name_data in validation_data.items():
for name, data in name_data.items():
if not isinstance(data, dict): # pragma: no cover
click.echo(
click.style(
"Invalid rule for parameter '{}'".format(name),
fg="white",
bg="yellow",
)
)
else:
data.setdefault("env", env)
click.echo(
click.style(
"Validating '{}' with '{}'".format(name, data),
fg="white",
bg="blue",
)
)
try:
Validator(name, **data).validate(settings)
except ValidationError as e:
click.echo(
click.style(
"Error: {}".format(e), fg="white", bg="red"
)
)
success = False
if success:
click.echo(click.style("Validation success!", fg="white", bg="green")) | python | def validate(path): # pragma: no cover
# 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).endswith(".toml"):
path = path / "dynaconf_validators.toml"
if not path.exists(): # pragma: no cover # noqa
click.echo(
click.style("{} not found".format(path), fg="white", bg="red")
)
sys.exit(1)
validation_data = toml.load(open(str(path)))
success = True
for env, name_data in validation_data.items():
for name, data in name_data.items():
if not isinstance(data, dict): # pragma: no cover
click.echo(
click.style(
"Invalid rule for parameter '{}'".format(name),
fg="white",
bg="yellow",
)
)
else:
data.setdefault("env", env)
click.echo(
click.style(
"Validating '{}' with '{}'".format(name, data),
fg="white",
bg="blue",
)
)
try:
Validator(name, **data).validate(settings)
except ValidationError as e:
click.echo(
click.style(
"Error: {}".format(e), fg="white", bg="red"
)
)
success = False
if success:
click.echo(click.style("Validation success!", fg="white", bg="green")) | [
"def",
"validate",
"(",
"path",
")",
":",
"# pragma: no cover",
"# 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",
")",
... | Validates Dynaconf settings based on rules defined in
dynaconf_validators.toml | [
"Validates",
"Dynaconf",
"settings",
"based",
"on",
"rules",
"defined",
"in",
"dynaconf_validators",
".",
"toml"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/cli.py#L569-L620 |
243,543 | rochacbruno/dynaconf | example/common/program.py | connect | 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))
print("-" * 79) | python | def connect(server, port, username, password):
print("-" * 79)
print("Connecting to: {}".format(server))
print("At port: {}".format(port))
print("Using username: {}".format(username))
print("Using password: {}".format(password))
print("-" * 79) | [
"def",
"connect",
"(",
"server",
",",
"port",
",",
"username",
",",
"password",
")",
":",
"print",
"(",
"\"-\"",
"*",
"79",
")",
"print",
"(",
"\"Connecting to: {}\"",
".",
"format",
"(",
"server",
")",
")",
"print",
"(",
"\"At port: {}\"",
".",
"format"... | This function might be something coming from your ORM | [
"This",
"function",
"might",
"be",
"something",
"coming",
"from",
"your",
"ORM"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/example/common/program.py#L4-L11 |
243,544 | rochacbruno/dynaconf | dynaconf/loaders/env_loader.py | write | 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 | def write(settings_path, settings_data, **kwargs):
for key, value in settings_data.items():
dotenv_cli.set_key(str(settings_path), key.upper(), str(value)) | [
"def",
"write",
"(",
"settings_path",
",",
"settings_data",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"key",
",",
"value",
"in",
"settings_data",
".",
"items",
"(",
")",
":",
"dotenv_cli",
".",
"set_key",
"(",
"str",
"(",
"settings_path",
")",
",",
"ke... | Write data to .env file | [
"Write",
"data",
"to",
".",
"env",
"file"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/loaders/env_loader.py#L60-L63 |
243,545 | rochacbruno/dynaconf | dynaconf/utils/parse_conf.py | parse_with_toml | 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 | def parse_with_toml(data):
try:
return toml.loads("key={}".format(data), DynaBox).key
except toml.TomlDecodeError:
return data | [
"def",
"parse_with_toml",
"(",
"data",
")",
":",
"try",
":",
"return",
"toml",
".",
"loads",
"(",
"\"key={}\"",
".",
"format",
"(",
"data",
")",
",",
"DynaBox",
")",
".",
"key",
"except",
"toml",
".",
"TomlDecodeError",
":",
"return",
"data"
] | Uses TOML syntax to parse data | [
"Uses",
"TOML",
"syntax",
"to",
"parse",
"data"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/utils/parse_conf.py#L28-L33 |
243,546 | rochacbruno/dynaconf | dynaconf/loaders/base.py | BaseLoader.load | 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
"""
filename = filename or self.obj.get(self.identifier.upper())
if not filename:
return
if not isinstance(filename, (list, tuple)):
split_files = ensure_a_list(filename)
if all([f.endswith(self.extensions) for f in split_files]): # noqa
files = split_files # it is a ['file.ext', ...]
else: # it is a single config as string
files = [filename]
else: # it is already a list/tuple
files = filename
self.obj._loaded_files.extend(files)
# add the [default] env
env_list = [self.obj.get("DEFAULT_ENV_FOR_DYNACONF")]
# compatibility with older versions that still uses [dynaconf] as
# [default] env
global_env = self.obj.get("ENVVAR_PREFIX_FOR_DYNACONF") or "DYNACONF"
if global_env not in env_list:
env_list.append(global_env)
# add the current [env]
if self.env not in env_list:
env_list.append(self.env)
# add the [global] env
env_list.append("GLOBAL")
# load all envs
self._read(files, env_list, silent, key) | python | def load(self, filename=None, key=None, silent=True):
filename = filename or self.obj.get(self.identifier.upper())
if not filename:
return
if not isinstance(filename, (list, tuple)):
split_files = ensure_a_list(filename)
if all([f.endswith(self.extensions) for f in split_files]): # noqa
files = split_files # it is a ['file.ext', ...]
else: # it is a single config as string
files = [filename]
else: # it is already a list/tuple
files = filename
self.obj._loaded_files.extend(files)
# add the [default] env
env_list = [self.obj.get("DEFAULT_ENV_FOR_DYNACONF")]
# compatibility with older versions that still uses [dynaconf] as
# [default] env
global_env = self.obj.get("ENVVAR_PREFIX_FOR_DYNACONF") or "DYNACONF"
if global_env not in env_list:
env_list.append(global_env)
# add the current [env]
if self.env not in env_list:
env_list.append(self.env)
# add the [global] env
env_list.append("GLOBAL")
# load all envs
self._read(files, env_list, silent, key) | [
"def",
"load",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"key",
"=",
"None",
",",
"silent",
"=",
"True",
")",
":",
"filename",
"=",
"filename",
"or",
"self",
".",
"obj",
".",
"get",
"(",
"self",
".",
"identifier",
".",
"upper",
"(",
")",
")... | 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 | [
"Reads",
"and",
"loads",
"in",
"to",
"self",
".",
"obj",
"a",
"single",
"key",
"or",
"all",
"keys",
"from",
"source"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/loaders/base.py#L44-L84 |
243,547 | rochacbruno/dynaconf | dynaconf/base.py | LazySettings._setup | 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(
settings_module=settings_module, **self._kwargs
)
self.logger.debug("Lazy Settings _setup ...") | python | def _setup(self):
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(
settings_module=settings_module, **self._kwargs
)
self.logger.debug("Lazy Settings _setup ...") | [
"def",
"_setup",
"(",
"self",
")",
":",
"default_settings",
".",
"reload",
"(",
")",
"environment_variable",
"=",
"self",
".",
"_kwargs",
".",
"get",
"(",
"\"ENVVAR_FOR_DYNACONF\"",
",",
"default_settings",
".",
"ENVVAR_FOR_DYNACONF",
")",
"settings_module",
"=",
... | Initial setup, run once. | [
"Initial",
"setup",
"run",
"once",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L115-L125 |
243,548 | rochacbruno/dynaconf | dynaconf/base.py | LazySettings.configure | 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.reload()
environment_var = self._kwargs.get(
"ENVVAR_FOR_DYNACONF", default_settings.ENVVAR_FOR_DYNACONF
)
settings_module = settings_module or os.environ.get(environment_var)
compat_kwargs(kwargs)
kwargs.update(self._kwargs)
self._wrapped = Settings(settings_module=settings_module, **kwargs)
self.logger.debug("Lazy Settings configured ...") | python | def configure(self, settings_module=None, **kwargs):
default_settings.reload()
environment_var = self._kwargs.get(
"ENVVAR_FOR_DYNACONF", default_settings.ENVVAR_FOR_DYNACONF
)
settings_module = settings_module or os.environ.get(environment_var)
compat_kwargs(kwargs)
kwargs.update(self._kwargs)
self._wrapped = Settings(settings_module=settings_module, **kwargs)
self.logger.debug("Lazy Settings configured ...") | [
"def",
"configure",
"(",
"self",
",",
"settings_module",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"default_settings",
".",
"reload",
"(",
")",
"environment_var",
"=",
"self",
".",
"_kwargs",
".",
"get",
"(",
"\"ENVVAR_FOR_DYNACONF\"",
",",
"default_se... | 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 | [
"Allows",
"user",
"to",
"reconfigure",
"settings",
"object",
"passing",
"a",
"new",
"settings",
"module",
"or",
"separated",
"kwargs"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L127-L143 |
243,549 | rochacbruno/dynaconf | dynaconf/base.py | Settings.as_dict | 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_env(env)
with ctx_mgr:
data = self.store.copy()
# if not internal remove internal settings
if not internal:
for name in dir(default_settings):
data.pop(name, None)
return data | python | def as_dict(self, env=None, internal=False):
ctx_mgr = suppress() if env is None else self.using_env(env)
with ctx_mgr:
data = self.store.copy()
# if not internal remove internal settings
if not internal:
for name in dir(default_settings):
data.pop(name, None)
return data | [
"def",
"as_dict",
"(",
"self",
",",
"env",
"=",
"None",
",",
"internal",
"=",
"False",
")",
":",
"ctx_mgr",
"=",
"suppress",
"(",
")",
"if",
"env",
"is",
"None",
"else",
"self",
".",
"using_env",
"(",
"env",
")",
"with",
"ctx_mgr",
":",
"data",
"="... | 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? | [
"Returns",
"a",
"dictionary",
"with",
"set",
"key",
"and",
"values",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L237-L250 |
243,550 | rochacbruno/dynaconf | dynaconf/base.py | Settings._dotted_get | 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._memoized = result
# If we've reached the end, then return result and clear the
# memoized data.
if not keys or result is default:
self._memoized = None
return result
# If we've still got key elements to traverse, let's do that.
return self._dotted_get(".".join(keys), default=default, **kwargs) | python | def _dotted_get(self, dotted_key, default=None, **kwargs):
split_key = dotted_key.split(".")
name, keys = split_key[0], split_key[1:]
result = self.get(name, default=default, **kwargs)
self._memoized = result
# If we've reached the end, then return result and clear the
# memoized data.
if not keys or result is default:
self._memoized = None
return result
# If we've still got key elements to traverse, let's do that.
return self._dotted_get(".".join(keys), default=default, **kwargs) | [
"def",
"_dotted_get",
"(",
"self",
",",
"dotted_key",
",",
"default",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"split_key",
"=",
"dotted_key",
".",
"split",
"(",
"\".\"",
")",
"name",
",",
"keys",
"=",
"split_key",
"[",
"0",
"]",
",",
"split_k... | Perform dotted key lookups and keep track of where we are. | [
"Perform",
"dotted",
"key",
"lookups",
"and",
"keep",
"track",
"of",
"where",
"we",
"are",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L252-L268 |
243,551 | rochacbruno/dynaconf | dynaconf/base.py | Settings.exists | 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 self.get(key, fresh=fresh, default=missing) is not missing | python | def exists(self, key, fresh=False):
key = key.upper()
if key in self._deleted:
return False
return self.get(key, fresh=fresh, default=missing) is not missing | [
"def",
"exists",
"(",
"self",
",",
"key",
",",
"fresh",
"=",
"False",
")",
":",
"key",
"=",
"key",
".",
"upper",
"(",
")",
"if",
"key",
"in",
"self",
".",
"_deleted",
":",
"return",
"False",
"return",
"self",
".",
"get",
"(",
"key",
",",
"fresh",... | Check if key exists
:param key: the name of setting variable
:param fresh: if key should be taken from source direclty
:return: Boolean | [
"Check",
"if",
"key",
"exists"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L310-L320 |
243,552 | rochacbruno/dynaconf | dynaconf/base.py | Settings.get_environ | 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, @bool or @json ?
or cast must be true to use cast inference
:return: The value if found, default or None
"""
key = key.upper()
data = self.environ.get(key, default)
if data:
if cast in converters:
data = converters.get(cast)(data)
if cast is True:
data = parse_conf_data(data, tomlfy=True)
return data | python | def get_environ(self, key, default=None, cast=None):
key = key.upper()
data = self.environ.get(key, default)
if data:
if cast in converters:
data = converters.get(cast)(data)
if cast is True:
data = parse_conf_data(data, tomlfy=True)
return data | [
"def",
"get_environ",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
",",
"cast",
"=",
"None",
")",
":",
"key",
"=",
"key",
".",
"upper",
"(",
")",
"data",
"=",
"self",
".",
"environ",
".",
"get",
"(",
"key",
",",
"default",
")",
"if",
"... | 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 inference
:return: The value if found, default or None | [
"Get",
"value",
"from",
"environment",
"variable",
"using",
"os",
".",
"environ",
".",
"get"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L333-L349 |
243,553 | rochacbruno/dynaconf | dynaconf/base.py | Settings.settings_module | 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_MODULE", None):
self.set("SETTINGS_MODULE", settings_module)
return self.SETTINGS_MODULE | python | def settings_module(self):
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_MODULE", None):
self.set("SETTINGS_MODULE", settings_module)
return self.SETTINGS_MODULE | [
"def",
"settings_module",
"(",
"self",
")",
":",
"settings_module",
"=",
"parse_conf_data",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"self",
".",
"ENVVAR_FOR_DYNACONF",
",",
"self",
".",
"SETTINGS_FILE_FOR_DYNACONF",
")",
",",
"tomlfy",
"=",
"True",
",",
... | Gets SETTINGS_MODULE variable | [
"Gets",
"SETTINGS_MODULE",
"variable"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L472-L482 |
243,554 | rochacbruno/dynaconf | dynaconf/base.py | Settings.clean | 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 | def clean(self, *args, **kwargs):
for key in list(self.store.keys()):
self.unset(key) | [
"def",
"clean",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"key",
"in",
"list",
"(",
"self",
".",
"store",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"unset",
"(",
"key",
")"
] | Clean all loaded values to reload when switching envs | [
"Clean",
"all",
"loaded",
"values",
"to",
"reload",
"when",
"switching",
"envs"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L534-L537 |
243,555 | rochacbruno/dynaconf | dynaconf/base.py | Settings.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.pop(key, None) | python | def unset(self, key):
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.pop(key, None) | [
"def",
"unset",
"(",
"self",
",",
"key",
")",
":",
"key",
"=",
"key",
".",
"strip",
"(",
")",
".",
"upper",
"(",
")",
"if",
"key",
"not",
"in",
"dir",
"(",
"default_settings",
")",
"and",
"key",
"not",
"in",
"self",
".",
"_defaults",
":",
"self",... | Unset on all references
:param key: The key to be unset | [
"Unset",
"on",
"all",
"references"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L539-L548 |
243,556 | rochacbruno/dynaconf | dynaconf/base.py | Settings.set | 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 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 secret values is hidden on logs.
"""
if "." in key and dotted_lookup is True:
return self._dotted_set(
key, value, loader_identifier=loader_identifier, tomlfy=tomlfy
)
value = parse_conf_data(value, tomlfy=tomlfy)
key = key.strip().upper()
existing = getattr(self, key, None)
if existing is not None and existing != value:
value = self._merge_before_set(key, existing, value, is_secret)
if isinstance(value, dict):
value = DynaBox(value, box_it_up=True)
setattr(self, key, value)
self.store[key] = value
self._deleted.discard(key)
# set loader identifiers so cleaners know which keys to clean
if loader_identifier and loader_identifier in self.loaded_by_loaders:
self.loaded_by_loaders[loader_identifier][key] = value
elif loader_identifier:
self.loaded_by_loaders[loader_identifier] = {key: value}
elif loader_identifier is None:
# if .set is called without loader identifier it becomes
# a default value and goes away only when explicitly unset
self._defaults[key] = value | python | def set(
self,
key,
value,
loader_identifier=None,
tomlfy=False,
dotted_lookup=True,
is_secret=False,
):
if "." in key and dotted_lookup is True:
return self._dotted_set(
key, value, loader_identifier=loader_identifier, tomlfy=tomlfy
)
value = parse_conf_data(value, tomlfy=tomlfy)
key = key.strip().upper()
existing = getattr(self, key, None)
if existing is not None and existing != value:
value = self._merge_before_set(key, existing, value, is_secret)
if isinstance(value, dict):
value = DynaBox(value, box_it_up=True)
setattr(self, key, value)
self.store[key] = value
self._deleted.discard(key)
# set loader identifiers so cleaners know which keys to clean
if loader_identifier and loader_identifier in self.loaded_by_loaders:
self.loaded_by_loaders[loader_identifier][key] = value
elif loader_identifier:
self.loaded_by_loaders[loader_identifier] = {key: value}
elif loader_identifier is None:
# if .set is called without loader identifier it becomes
# a default value and goes away only when explicitly unset
self._defaults[key] = value | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
",",
"loader_identifier",
"=",
"None",
",",
"tomlfy",
"=",
"False",
",",
"dotted_lookup",
"=",
"True",
",",
"is_secret",
"=",
"False",
",",
")",
":",
"if",
"\".\"",
"in",
"key",
"and",
"dotted_lookup... | 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 secret values is hidden on logs. | [
"Set",
"a",
"value",
"storing",
"references",
"for",
"the",
"loader"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L572-L616 |
243,557 | rochacbruno/dynaconf | dynaconf/base.py | Settings._merge_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 _log_after_merge(_value):
self.logger.debug("%s merged to %s", key, _value)
global_merge = getattr(self, "MERGE_ENABLED_FOR_DYNACONF", False)
if isinstance(value, dict):
local_merge = value.pop(
"dynaconf_merge", value.pop("dynaconf_merge_unique", None)
)
if global_merge or local_merge:
safe_value = {k: "***" for k in value} if is_secret else value
_log_before_merging(safe_value)
object_merge(existing, value)
safe_value = (
{
k: ("***" if k in safe_value else v)
for k, v in value.items()
}
if is_secret
else value
)
_log_after_merge(safe_value)
if isinstance(value, (list, tuple)):
local_merge = (
"dynaconf_merge" in value or "dynaconf_merge_unique" in value
)
if global_merge or local_merge:
value = list(value)
unique = False
if local_merge:
try:
value.remove("dynaconf_merge")
except ValueError: # EAFP
value.remove("dynaconf_merge_unique")
unique = True
original = set(value)
_log_before_merging(
["***" for item in value] if is_secret else value
)
object_merge(existing, value, unique=unique)
safe_value = (
["***" if item in original else item for item in value]
if is_secret
else value
)
_log_after_merge(safe_value)
return value | python | def _merge_before_set(self, key, existing, value, is_secret):
def _log_before_merging(_value):
self.logger.debug(
"Merging existing %s: %s with new: %s", key, existing, _value
)
def _log_after_merge(_value):
self.logger.debug("%s merged to %s", key, _value)
global_merge = getattr(self, "MERGE_ENABLED_FOR_DYNACONF", False)
if isinstance(value, dict):
local_merge = value.pop(
"dynaconf_merge", value.pop("dynaconf_merge_unique", None)
)
if global_merge or local_merge:
safe_value = {k: "***" for k in value} if is_secret else value
_log_before_merging(safe_value)
object_merge(existing, value)
safe_value = (
{
k: ("***" if k in safe_value else v)
for k, v in value.items()
}
if is_secret
else value
)
_log_after_merge(safe_value)
if isinstance(value, (list, tuple)):
local_merge = (
"dynaconf_merge" in value or "dynaconf_merge_unique" in value
)
if global_merge or local_merge:
value = list(value)
unique = False
if local_merge:
try:
value.remove("dynaconf_merge")
except ValueError: # EAFP
value.remove("dynaconf_merge_unique")
unique = True
original = set(value)
_log_before_merging(
["***" for item in value] if is_secret else value
)
object_merge(existing, value, unique=unique)
safe_value = (
["***" if item in original else item for item in value]
if is_secret
else value
)
_log_after_merge(safe_value)
return value | [
"def",
"_merge_before_set",
"(",
"self",
",",
"key",
",",
"existing",
",",
"value",
",",
"is_secret",
")",
":",
"def",
"_log_before_merging",
"(",
"_value",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Merging existing %s: %s with new: %s\"",
",",
"k... | Merge the new value being set with the existing value before set | [
"Merge",
"the",
"new",
"value",
"being",
"set",
"with",
"the",
"existing",
"value",
"before",
"set"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L655-L713 |
243,558 | rochacbruno/dynaconf | dynaconf/base.py | Settings.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:
loader = importlib.import_module(loader_module_name)
self._loaders.append(loader)
return self._loaders | python | def loaders(self): # pragma: no cover
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:
loader = importlib.import_module(loader_module_name)
self._loaders.append(loader)
return self._loaders | [
"def",
"loaders",
"(",
"self",
")",
":",
"# pragma: no cover",
"if",
"self",
".",
"LOADERS_FOR_DYNACONF",
"in",
"(",
"None",
",",
"0",
",",
"\"0\"",
",",
"\"false\"",
",",
"False",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"No loader defined\"",... | Return available loaders | [
"Return",
"available",
"loaders"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L716-L727 |
243,559 | rochacbruno/dynaconf | dynaconf/base.py | Settings.reload | def reload(self, env=None, silent=None): # pragma: no cover
"""Clean end Execute all loaders"""
self.clean()
self.execute_loaders(env, silent) | python | def reload(self, env=None, silent=None): # pragma: no cover
self.clean()
self.execute_loaders(env, silent) | [
"def",
"reload",
"(",
"self",
",",
"env",
"=",
"None",
",",
"silent",
"=",
"None",
")",
":",
"# pragma: no cover",
"self",
".",
"clean",
"(",
")",
"self",
".",
"execute_loaders",
"(",
"env",
",",
"silent",
")"
] | Clean end Execute all loaders | [
"Clean",
"end",
"Execute",
"all",
"loaders"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L729-L732 |
243,560 | rochacbruno/dynaconf | dynaconf/base.py | Settings.execute_loaders | 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 filename to load
"""
if key is None:
default_loader(self, self._defaults)
env = (env or self.current_env).upper()
silent = silent or self.SILENT_ERRORS_FOR_DYNACONF
settings_loader(
self, env=env, silent=silent, key=key, filename=filename
)
self.load_extra_yaml(env, silent, key) # DEPRECATED
enable_external_loaders(self)
for loader in self.loaders:
self.logger.debug("Dynaconf executing: %s", loader.__name__)
loader.load(self, env, silent=silent, key=key)
self.load_includes(env, silent=silent, key=key)
self.logger.debug("Loaded Files: %s", deduplicate(self._loaded_files)) | python | def execute_loaders(self, env=None, silent=None, key=None, filename=None):
if key is None:
default_loader(self, self._defaults)
env = (env or self.current_env).upper()
silent = silent or self.SILENT_ERRORS_FOR_DYNACONF
settings_loader(
self, env=env, silent=silent, key=key, filename=filename
)
self.load_extra_yaml(env, silent, key) # DEPRECATED
enable_external_loaders(self)
for loader in self.loaders:
self.logger.debug("Dynaconf executing: %s", loader.__name__)
loader.load(self, env, silent=silent, key=key)
self.load_includes(env, silent=silent, key=key)
self.logger.debug("Loaded Files: %s", deduplicate(self._loaded_files)) | [
"def",
"execute_loaders",
"(",
"self",
",",
"env",
"=",
"None",
",",
"silent",
"=",
"None",
",",
"key",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
":",
"default_loader",
"(",
"self",
",",
"self",
".",
"_defaults",... | 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 | [
"Execute",
"all",
"internal",
"and",
"registered",
"loaders"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L734-L755 |
243,561 | rochacbruno/dynaconf | dynaconf/base.py | Settings.load_includes | 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)
self.load_file(path=includes, env=env, silent=silent, key=key) | python | def load_includes(self, env, silent, key):
includes = self.get("DYNACONF_INCLUDE", [])
includes.extend(ensure_a_list(self.get("INCLUDES_FOR_DYNACONF")))
if includes:
self.logger.debug("Processing includes %s", includes)
self.load_file(path=includes, env=env, silent=silent, key=key) | [
"def",
"load_includes",
"(",
"self",
",",
"env",
",",
"silent",
",",
"key",
")",
":",
"includes",
"=",
"self",
".",
"get",
"(",
"\"DYNACONF_INCLUDE\"",
",",
"[",
"]",
")",
"includes",
".",
"extend",
"(",
"ensure_a_list",
"(",
"self",
".",
"get",
"(",
... | Do we have any nested includes we need to process? | [
"Do",
"we",
"have",
"any",
"nested",
"includes",
"we",
"need",
"to",
"process?"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L757-L763 |
243,562 | rochacbruno/dynaconf | dynaconf/base.py | Settings.load_file | 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 single key?
"""
env = (env or self.current_env).upper()
files = ensure_a_list(path)
if files:
self.logger.debug("Got %s files to process", files)
already_loaded = set()
for _filename in files:
self.logger.debug("Processing file %s", _filename)
filepath = os.path.join(self._root_path, _filename)
self.logger.debug("File path is %s", filepath)
# Handle possible *.globs sorted alphanumeric
for path in sorted(glob.glob(filepath)):
self.logger.debug("Loading %s", path)
if path in already_loaded: # pragma: no cover
self.logger.debug("Skipping %s, already loaded", path)
continue
settings_loader(
obj=self,
env=env,
silent=silent,
key=key,
filename=path,
)
already_loaded.add(path)
if not already_loaded:
self.logger.warning(
"Not able to locate the files %s to load", files
) | python | def load_file(self, path=None, env=None, silent=True, key=None):
env = (env or self.current_env).upper()
files = ensure_a_list(path)
if files:
self.logger.debug("Got %s files to process", files)
already_loaded = set()
for _filename in files:
self.logger.debug("Processing file %s", _filename)
filepath = os.path.join(self._root_path, _filename)
self.logger.debug("File path is %s", filepath)
# Handle possible *.globs sorted alphanumeric
for path in sorted(glob.glob(filepath)):
self.logger.debug("Loading %s", path)
if path in already_loaded: # pragma: no cover
self.logger.debug("Skipping %s, already loaded", path)
continue
settings_loader(
obj=self,
env=env,
silent=silent,
key=key,
filename=path,
)
already_loaded.add(path)
if not already_loaded:
self.logger.warning(
"Not able to locate the files %s to load", files
) | [
"def",
"load_file",
"(",
"self",
",",
"path",
"=",
"None",
",",
"env",
"=",
"None",
",",
"silent",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"env",
"=",
"(",
"env",
"or",
"self",
".",
"current_env",
")",
".",
"upper",
"(",
")",
"files",
"... | 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? | [
"Programmatically",
"load",
"files",
"from",
"path",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L765-L799 |
243,563 | rochacbruno/dynaconf | dynaconf/base.py | Settings._root_path | 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])
self.set("ROOT_PATH_FOR_DYNACONF", root_path)
return root_path | python | 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])
self.set("ROOT_PATH_FOR_DYNACONF", root_path)
return root_path | [
"def",
"_root_path",
"(",
"self",
")",
":",
"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",... | ROOT_PATH_FOR_DYNACONF or the path of first loaded file or '. | [
"ROOT_PATH_FOR_DYNACONF",
"or",
"the",
"path",
"of",
"first",
"loaded",
"file",
"or",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L802-L809 |
243,564 | rochacbruno/dynaconf | dynaconf/base.py | Settings.load_extra_yaml | 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 is deprecated, please define multiple "
"filepaths instead: "
"e.g: SETTINGS_FILE_FOR_DYNACONF = "
"'settings.py,settings.yaml,settings.toml' or "
"INCLUDES_FOR_DYNACONF=['path.toml', 'folder/*']"
)
yaml_loader.load(
self,
env=env,
filename=self.find_file(self.get("YAML")),
silent=silent,
key=key,
) | python | def load_extra_yaml(self, env, silent, key):
if self.get("YAML") is not None:
self.logger.warning(
"The use of YAML var is deprecated, please define multiple "
"filepaths instead: "
"e.g: SETTINGS_FILE_FOR_DYNACONF = "
"'settings.py,settings.yaml,settings.toml' or "
"INCLUDES_FOR_DYNACONF=['path.toml', 'folder/*']"
)
yaml_loader.load(
self,
env=env,
filename=self.find_file(self.get("YAML")),
silent=silent,
key=key,
) | [
"def",
"load_extra_yaml",
"(",
"self",
",",
"env",
",",
"silent",
",",
"key",
")",
":",
"if",
"self",
".",
"get",
"(",
"\"YAML\"",
")",
"is",
"not",
"None",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"The use of YAML var is deprecated, please define ... | This is deprecated, kept for compat
.. deprecated:: 1.0.0
Use multiple settings or INCLUDES_FOR_DYNACONF files instead. | [
"This",
"is",
"deprecated",
"kept",
"for",
"compat"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L811-L831 |
243,565 | rochacbruno/dynaconf | dynaconf/base.py | Settings.path_for | 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 | def path_for(self, *args):
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) | [
"def",
"path_for",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"args",
"and",
"args",
"[",
"0",
"]",
".",
"startswith",
"(",
"os",
".",
"path",
".",
"sep",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"*",
"args",
")",
"return",
... | Path containing _root_path | [
"Path",
"containing",
"_root_path"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L833-L837 |
243,566 | rochacbruno/dynaconf | dynaconf/base.py | Settings.validators | def validators(self):
"""Gets or creates validator wrapper"""
if not hasattr(self, "_validators"):
self._validators = ValidatorList(self)
return self._validators | python | def validators(self):
if not hasattr(self, "_validators"):
self._validators = ValidatorList(self)
return self._validators | [
"def",
"validators",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_validators\"",
")",
":",
"self",
".",
"_validators",
"=",
"ValidatorList",
"(",
"self",
")",
"return",
"self",
".",
"_validators"
] | Gets or creates validator wrapper | [
"Gets",
"or",
"creates",
"validator",
"wrapper"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L847-L851 |
243,567 | rochacbruno/dynaconf | dynaconf/base.py | Settings.populate_obj | 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 | def populate_obj(self, obj, keys=None):
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) | [
"def",
"populate_obj",
"(",
"self",
",",
"obj",
",",
"keys",
"=",
"None",
")",
":",
"keys",
"=",
"keys",
"or",
"self",
".",
"keys",
"(",
")",
"for",
"key",
"in",
"keys",
":",
"key",
"=",
"key",
".",
"upper",
"(",
")",
"value",
"=",
"self",
".",... | Given the `obj` populate it using self.store items. | [
"Given",
"the",
"obj",
"populate",
"it",
"using",
"self",
".",
"store",
"items",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/base.py#L878-L885 |
243,568 | rochacbruno/dynaconf | dynaconf/loaders/__init__.py | default_loader | 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()
}
all_keys = deduplicate(
list(defaults.keys()) + list(default_settings_values.keys())
)
for key in all_keys:
if not obj.exists(key):
value = defaults.get(key, default_settings_values.get(key))
obj.logger.debug("loading: %s:%s", key, value)
obj.set(key, value)
# start dotenv to get default env vars from there
# check overrides in env vars
default_settings.start_dotenv(obj)
# Deal with cases where a custom ENV_SWITCHER_IS_PROVIDED
# Example: Flask and Django Extensions
env_switcher = defaults.get(
"ENV_SWITCHER_FOR_DYNACONF", "ENV_FOR_DYNACONF"
)
for key in all_keys:
if key not in default_settings_values.keys():
continue
env_value = obj.get_environ(
env_switcher if key == "ENV_FOR_DYNACONF" else key,
default="_not_found",
)
if env_value != "_not_found":
obj.logger.debug("overriding from envvar: %s:%s", key, env_value)
obj.set(key, env_value, tomlfy=True) | python | def default_loader(obj, defaults=None):
defaults = defaults or {}
default_settings_values = {
key: value
for key, value in default_settings.__dict__.items() # noqa
if key.isupper()
}
all_keys = deduplicate(
list(defaults.keys()) + list(default_settings_values.keys())
)
for key in all_keys:
if not obj.exists(key):
value = defaults.get(key, default_settings_values.get(key))
obj.logger.debug("loading: %s:%s", key, value)
obj.set(key, value)
# start dotenv to get default env vars from there
# check overrides in env vars
default_settings.start_dotenv(obj)
# Deal with cases where a custom ENV_SWITCHER_IS_PROVIDED
# Example: Flask and Django Extensions
env_switcher = defaults.get(
"ENV_SWITCHER_FOR_DYNACONF", "ENV_FOR_DYNACONF"
)
for key in all_keys:
if key not in default_settings_values.keys():
continue
env_value = obj.get_environ(
env_switcher if key == "ENV_FOR_DYNACONF" else key,
default="_not_found",
)
if env_value != "_not_found":
obj.logger.debug("overriding from envvar: %s:%s", key, env_value)
obj.set(key, env_value, tomlfy=True) | [
"def",
"default_loader",
"(",
"obj",
",",
"defaults",
"=",
"None",
")",
":",
"defaults",
"=",
"defaults",
"or",
"{",
"}",
"default_settings_values",
"=",
"{",
"key",
":",
"value",
"for",
"key",
",",
"value",
"in",
"default_settings",
".",
"__dict__",
".",
... | Loads default settings and check if there are overridings
exported as environment variables | [
"Loads",
"default",
"settings",
"and",
"check",
"if",
"there",
"are",
"overridings",
"exported",
"as",
"environment",
"variables"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/loaders/__init__.py#L15-L56 |
243,569 | rochacbruno/dynaconf | dynaconf/loaders/__init__.py | settings_loader | 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
:param silent: Boolean to raise loading errors
:param key: Load a single key if provided
:param filename: optional filename to override the settings_module
"""
if filename is None:
settings_module = settings_module or obj.settings_module
if not settings_module: # pragma: no cover
return
files = ensure_a_list(settings_module)
else:
files = ensure_a_list(filename)
files.extend(ensure_a_list(obj.get("SECRETS_FOR_DYNACONF", None)))
found_files = []
modules_names = []
for item in files:
if item.endswith(ct.ALL_EXTENSIONS + (".py",)):
p_root = obj._root_path or (
os.path.dirname(found_files[0]) if found_files else None
)
found = obj.find_file(item, project_root=p_root)
if found:
found_files.append(found)
else:
# a bare python module name w/o extension
modules_names.append(item)
enabled_core_loaders = obj.get("CORE_LOADERS_FOR_DYNACONF")
for mod_file in modules_names + found_files:
# can be set to multiple files settings.py,settings.yaml,...
# Cascade all loaders
loaders = [
{"ext": ct.YAML_EXTENSIONS, "name": "YAML", "loader": yaml_loader},
{"ext": ct.TOML_EXTENSIONS, "name": "TOML", "loader": toml_loader},
{"ext": ct.INI_EXTENSIONS, "name": "INI", "loader": ini_loader},
{"ext": ct.JSON_EXTENSIONS, "name": "JSON", "loader": json_loader},
]
for loader in loaders:
if loader["name"] not in enabled_core_loaders:
continue
if mod_file.endswith(loader["ext"]):
loader["loader"].load(
obj, filename=mod_file, env=env, silent=silent, key=key
)
continue
if mod_file.endswith(ct.ALL_EXTENSIONS):
continue
if "PY" not in enabled_core_loaders:
# pyloader is disabled
continue
# must be Python file or module
# load from default defined module settings.py or .secrets.py if exists
py_loader.load(obj, mod_file, key=key)
# load from the current env e.g: development_settings.py
env = env or obj.current_env
if mod_file.endswith(".py"):
if ".secrets.py" == mod_file:
tmpl = ".{0}_{1}{2}"
mod_file = "secrets.py"
else:
tmpl = "{0}_{1}{2}"
dirname = os.path.dirname(mod_file)
filename, extension = os.path.splitext(os.path.basename(mod_file))
new_filename = tmpl.format(env.lower(), filename, extension)
env_mod_file = os.path.join(dirname, new_filename)
global_filename = tmpl.format("global", filename, extension)
global_mod_file = os.path.join(dirname, global_filename)
else:
env_mod_file = "{0}_{1}".format(env.lower(), mod_file)
global_mod_file = "{0}_{1}".format("global", mod_file)
py_loader.load(
obj,
env_mod_file,
identifier="py_{0}".format(env.upper()),
silent=True,
key=key,
)
# load from global_settings.py
py_loader.load(
obj, global_mod_file, identifier="py_global", silent=True, key=key
) | python | def settings_loader(
obj, settings_module=None, env=None, silent=True, key=None, filename=None
):
if filename is None:
settings_module = settings_module or obj.settings_module
if not settings_module: # pragma: no cover
return
files = ensure_a_list(settings_module)
else:
files = ensure_a_list(filename)
files.extend(ensure_a_list(obj.get("SECRETS_FOR_DYNACONF", None)))
found_files = []
modules_names = []
for item in files:
if item.endswith(ct.ALL_EXTENSIONS + (".py",)):
p_root = obj._root_path or (
os.path.dirname(found_files[0]) if found_files else None
)
found = obj.find_file(item, project_root=p_root)
if found:
found_files.append(found)
else:
# a bare python module name w/o extension
modules_names.append(item)
enabled_core_loaders = obj.get("CORE_LOADERS_FOR_DYNACONF")
for mod_file in modules_names + found_files:
# can be set to multiple files settings.py,settings.yaml,...
# Cascade all loaders
loaders = [
{"ext": ct.YAML_EXTENSIONS, "name": "YAML", "loader": yaml_loader},
{"ext": ct.TOML_EXTENSIONS, "name": "TOML", "loader": toml_loader},
{"ext": ct.INI_EXTENSIONS, "name": "INI", "loader": ini_loader},
{"ext": ct.JSON_EXTENSIONS, "name": "JSON", "loader": json_loader},
]
for loader in loaders:
if loader["name"] not in enabled_core_loaders:
continue
if mod_file.endswith(loader["ext"]):
loader["loader"].load(
obj, filename=mod_file, env=env, silent=silent, key=key
)
continue
if mod_file.endswith(ct.ALL_EXTENSIONS):
continue
if "PY" not in enabled_core_loaders:
# pyloader is disabled
continue
# must be Python file or module
# load from default defined module settings.py or .secrets.py if exists
py_loader.load(obj, mod_file, key=key)
# load from the current env e.g: development_settings.py
env = env or obj.current_env
if mod_file.endswith(".py"):
if ".secrets.py" == mod_file:
tmpl = ".{0}_{1}{2}"
mod_file = "secrets.py"
else:
tmpl = "{0}_{1}{2}"
dirname = os.path.dirname(mod_file)
filename, extension = os.path.splitext(os.path.basename(mod_file))
new_filename = tmpl.format(env.lower(), filename, extension)
env_mod_file = os.path.join(dirname, new_filename)
global_filename = tmpl.format("global", filename, extension)
global_mod_file = os.path.join(dirname, global_filename)
else:
env_mod_file = "{0}_{1}".format(env.lower(), mod_file)
global_mod_file = "{0}_{1}".format("global", mod_file)
py_loader.load(
obj,
env_mod_file,
identifier="py_{0}".format(env.upper()),
silent=True,
key=key,
)
# load from global_settings.py
py_loader.load(
obj, global_mod_file, identifier="py_global", silent=True, key=key
) | [
"def",
"settings_loader",
"(",
"obj",
",",
"settings_module",
"=",
"None",
",",
"env",
"=",
"None",
",",
"silent",
"=",
"True",
",",
"key",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"None",
":",
"settings_module",
"="... | 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: optional filename to override the settings_module | [
"Loads",
"from",
"defined",
"settings",
"module"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/loaders/__init__.py#L59-L159 |
243,570 | rochacbruno/dynaconf | dynaconf/loaders/__init__.py | enable_external_loaders | 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
)
if (
enabled
and enabled not in false_values
and loader not in obj.LOADERS_FOR_DYNACONF
): # noqa
obj.logger.debug("loaders: Enabling %s", loader)
obj.LOADERS_FOR_DYNACONF.insert(0, loader) | python | def enable_external_loaders(obj):
for name, loader in ct.EXTERNAL_LOADERS.items():
enabled = getattr(
obj, "{}_ENABLED_FOR_DYNACONF".format(name.upper()), False
)
if (
enabled
and enabled not in false_values
and loader not in obj.LOADERS_FOR_DYNACONF
): # noqa
obj.logger.debug("loaders: Enabling %s", loader)
obj.LOADERS_FOR_DYNACONF.insert(0, loader) | [
"def",
"enable_external_loaders",
"(",
"obj",
")",
":",
"for",
"name",
",",
"loader",
"in",
"ct",
".",
"EXTERNAL_LOADERS",
".",
"items",
"(",
")",
":",
"enabled",
"=",
"getattr",
"(",
"obj",
",",
"\"{}_ENABLED_FOR_DYNACONF\"",
".",
"format",
"(",
"name",
"... | Enable external service loaders like `VAULT_` and `REDIS_`
looks forenv variables like `REDIS_ENABLED_FOR_DYNACONF` | [
"Enable",
"external",
"service",
"loaders",
"like",
"VAULT_",
"and",
"REDIS_",
"looks",
"forenv",
"variables",
"like",
"REDIS_ENABLED_FOR_DYNACONF"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/loaders/__init__.py#L162-L176 |
243,571 | rochacbruno/dynaconf | dynaconf/utils/files.py | _walk_to_root | 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)
last_dir = None
current_dir = os.path.abspath(path)
paths = []
while last_dir != current_dir:
paths.append(current_dir)
paths.append(os.path.join(current_dir, "config"))
if break_at and current_dir == os.path.abspath(break_at): # noqa
logger.debug("Reached the %s directory, breaking.", break_at)
break
parent_dir = os.path.abspath(os.path.join(current_dir, os.path.pardir))
last_dir, current_dir = current_dir, parent_dir
return paths | python | def _walk_to_root(path, break_at=None):
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)
last_dir = None
current_dir = os.path.abspath(path)
paths = []
while last_dir != current_dir:
paths.append(current_dir)
paths.append(os.path.join(current_dir, "config"))
if break_at and current_dir == os.path.abspath(break_at): # noqa
logger.debug("Reached the %s directory, breaking.", break_at)
break
parent_dir = os.path.abspath(os.path.join(current_dir, os.path.pardir))
last_dir, current_dir = current_dir, parent_dir
return paths | [
"def",
"_walk_to_root",
"(",
"path",
",",
"break_at",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"# pragma: no cover",
"raise",
"IOError",
"(",
"\"Starting path not found\"",
")",
"if",
"os",
".",
"path",
... | Directories starting from the given directory up to the root or break_at | [
"Directories",
"starting",
"from",
"the",
"given",
"directory",
"up",
"to",
"the",
"root",
"or",
"break_at"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/utils/files.py#L12-L33 |
243,572 | rochacbruno/dynaconf | dynaconf/utils/files.py | find_file | 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 location and its parents until root
- Current working directory
For each path in the `search_tree` it will also look for an
aditional `./config` folder.
"""
search_tree = []
work_dir = os.getcwd()
skip_files = skip_files or []
if project_root is None:
logger.debug("No root_path for %s", filename)
else:
logger.debug("Got root_path %s for %s", project_root, filename)
search_tree.extend(_walk_to_root(project_root, break_at=work_dir))
script_dir = os.path.dirname(os.path.abspath(inspect.stack()[-1].filename))
# Path to invoked script and recursively to root with its ./config dirs
search_tree.extend(_walk_to_root(script_dir))
# Path to where Python interpreter was invoked and recursively to root
search_tree.extend(_walk_to_root(work_dir))
# Don't look the same place twice
search_tree = deduplicate(search_tree)
global SEARCHTREE
SEARCHTREE != search_tree and logger.debug("Search Tree: %s", search_tree)
SEARCHTREE = search_tree
logger.debug("Searching for %s", filename)
for dirname in search_tree:
check_path = os.path.join(dirname, filename)
if check_path in skip_files:
continue
if os.path.exists(check_path):
logger.debug("Found: %s", os.path.abspath(check_path))
return check_path # First found will return
# return empty string if not found so it can still be joined in os.path
return "" | python | def find_file(filename=".env", project_root=None, skip_files=None, **kwargs):
search_tree = []
work_dir = os.getcwd()
skip_files = skip_files or []
if project_root is None:
logger.debug("No root_path for %s", filename)
else:
logger.debug("Got root_path %s for %s", project_root, filename)
search_tree.extend(_walk_to_root(project_root, break_at=work_dir))
script_dir = os.path.dirname(os.path.abspath(inspect.stack()[-1].filename))
# Path to invoked script and recursively to root with its ./config dirs
search_tree.extend(_walk_to_root(script_dir))
# Path to where Python interpreter was invoked and recursively to root
search_tree.extend(_walk_to_root(work_dir))
# Don't look the same place twice
search_tree = deduplicate(search_tree)
global SEARCHTREE
SEARCHTREE != search_tree and logger.debug("Search Tree: %s", search_tree)
SEARCHTREE = search_tree
logger.debug("Searching for %s", filename)
for dirname in search_tree:
check_path = os.path.join(dirname, filename)
if check_path in skip_files:
continue
if os.path.exists(check_path):
logger.debug("Found: %s", os.path.abspath(check_path))
return check_path # First found will return
# return empty string if not found so it can still be joined in os.path
return "" | [
"def",
"find_file",
"(",
"filename",
"=",
"\".env\"",
",",
"project_root",
"=",
"None",
",",
"skip_files",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"search_tree",
"=",
"[",
"]",
"work_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"skip_files",
"=",
... | 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 path in the `search_tree` it will also look for an
aditional `./config` folder. | [
"Search",
"in",
"increasingly",
"higher",
"folders",
"for",
"the",
"given",
"file",
"Returns",
"path",
"to",
"the",
"file",
"if",
"found",
"or",
"an",
"empty",
"string",
"otherwise",
"."
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/utils/files.py#L39-L88 |
243,573 | rochacbruno/dynaconf | dynaconf/validator.py | Validator.validate | 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.when.envs = self.envs
self.when.validate(settings)
except ValidationError:
# if when is invalid, return canceling validation flow
return
# If only using current_env, skip using_env decoration (reload)
if (
len(self.envs) == 1
and self.envs[0].upper() == settings.current_env.upper()
):
self._validate_items(settings, settings.current_env)
return
for env in self.envs:
with settings.using_env(env):
self._validate_items(settings, env) | python | def validate(self, settings):
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.when.envs = self.envs
self.when.validate(settings)
except ValidationError:
# if when is invalid, return canceling validation flow
return
# If only using current_env, skip using_env decoration (reload)
if (
len(self.envs) == 1
and self.envs[0].upper() == settings.current_env.upper()
):
self._validate_items(settings, settings.current_env)
return
for env in self.envs:
with settings.using_env(env):
self._validate_items(settings, env) | [
"def",
"validate",
"(",
"self",
",",
"settings",
")",
":",
"if",
"self",
".",
"envs",
"is",
"None",
":",
"self",
".",
"envs",
"=",
"[",
"settings",
".",
"current_env",
"]",
"if",
"self",
".",
"when",
"is",
"not",
"None",
":",
"try",
":",
"# inherit... | Raise ValidationError if invalid | [
"Raise",
"ValidationError",
"if",
"invalid"
] | 5a7cc8f8252251cbdf4f4112965801f9dfe2831d | https://github.com/rochacbruno/dynaconf/blob/5a7cc8f8252251cbdf4f4112965801f9dfe2831d/dynaconf/validator.py#L86-L113 |
243,574 | django-json-api/django-rest-framework-json-api | rest_framework_json_api/serializers.py | ModelSerializer.to_representation | 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:
try:
field_representation = self._get_field_representation(field, instance)
ret[field.field_name] = field_representation
except SkipField:
continue
return ret | python | def to_representation(self, instance):
ret = OrderedDict()
readable_fields = [
field for field in self.fields.values()
if not field.write_only
]
for field in readable_fields:
try:
field_representation = self._get_field_representation(field, instance)
ret[field.field_name] = field_representation
except SkipField:
continue
return ret | [
"def",
"to_representation",
"(",
"self",
",",
"instance",
")",
":",
"ret",
"=",
"OrderedDict",
"(",
")",
"readable_fields",
"=",
"[",
"field",
"for",
"field",
"in",
"self",
".",
"fields",
".",
"values",
"(",
")",
"if",
"not",
"field",
".",
"write_only",
... | Object instance -> Dict of primitive datatypes. | [
"Object",
"instance",
"-",
">",
"Dict",
"of",
"primitive",
"datatypes",
"."
] | de7021f9e011615ce8b65d0cb38227c6c12721b6 | https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/serializers.py#L175-L192 |
243,575 | django-json-api/django-rest-framework-json-api | rest_framework_json_api/renderers.py | JSONRenderer.extract_attributes | 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
if field_name == 'id':
continue
# don't output a key for write only fields
if fields[field_name].write_only:
continue
# Skip fields with relations
if isinstance(
field, (relations.RelatedField, relations.ManyRelatedField, BaseSerializer)
):
continue
# Skip read_only attribute fields when `resource` is an empty
# serializer. Prevents the "Raw Data" form of the browsable API
# from rendering `"foo": null` for read only fields
try:
resource[field_name]
except KeyError:
if fields[field_name].read_only:
continue
data.update({
field_name: resource.get(field_name)
})
return utils._format_object(data) | python | def extract_attributes(cls, fields, resource):
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
if field_name == 'id':
continue
# don't output a key for write only fields
if fields[field_name].write_only:
continue
# Skip fields with relations
if isinstance(
field, (relations.RelatedField, relations.ManyRelatedField, BaseSerializer)
):
continue
# Skip read_only attribute fields when `resource` is an empty
# serializer. Prevents the "Raw Data" form of the browsable API
# from rendering `"foo": null` for read only fields
try:
resource[field_name]
except KeyError:
if fields[field_name].read_only:
continue
data.update({
field_name: resource.get(field_name)
})
return utils._format_object(data) | [
"def",
"extract_attributes",
"(",
"cls",
",",
"fields",
",",
"resource",
")",
":",
"data",
"=",
"OrderedDict",
"(",
")",
"for",
"field_name",
",",
"field",
"in",
"six",
".",
"iteritems",
"(",
"fields",
")",
":",
"# ID is always provided in the root of JSON API s... | Builds the `attributes` object of the JSON API resource object. | [
"Builds",
"the",
"attributes",
"object",
"of",
"the",
"JSON",
"API",
"resource",
"object",
"."
] | de7021f9e011615ce8b65d0cb38227c6c12721b6 | https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/renderers.py#L50-L81 |
243,576 | django-json-api/django-rest-framework-json-api | rest_framework_json_api/renderers.py | JSONRenderer.extract_relation_instance | 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 name of field's source.
"""
relation_instance = None
try:
relation_instance = getattr(resource_instance, field_name)
except AttributeError:
try:
# For ManyRelatedFields if `related_name` is not set
# we need to access `foo_set` from `source`
relation_instance = getattr(resource_instance, field.child_relation.source)
except AttributeError:
if hasattr(serializer, field.source):
serializer_method = getattr(serializer, field.source)
relation_instance = serializer_method(resource_instance)
else:
# case when source is a simple remap on resource_instance
try:
relation_instance = getattr(resource_instance, field.source)
except AttributeError:
pass
return relation_instance | python | def extract_relation_instance(cls, field_name, field, resource_instance, serializer):
relation_instance = None
try:
relation_instance = getattr(resource_instance, field_name)
except AttributeError:
try:
# For ManyRelatedFields if `related_name` is not set
# we need to access `foo_set` from `source`
relation_instance = getattr(resource_instance, field.child_relation.source)
except AttributeError:
if hasattr(serializer, field.source):
serializer_method = getattr(serializer, field.source)
relation_instance = serializer_method(resource_instance)
else:
# case when source is a simple remap on resource_instance
try:
relation_instance = getattr(resource_instance, field.source)
except AttributeError:
pass
return relation_instance | [
"def",
"extract_relation_instance",
"(",
"cls",
",",
"field_name",
",",
"field",
",",
"resource_instance",
",",
"serializer",
")",
":",
"relation_instance",
"=",
"None",
"try",
":",
"relation_instance",
"=",
"getattr",
"(",
"resource_instance",
",",
"field_name",
... | 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. | [
"Determines",
"what",
"instance",
"represents",
"given",
"relation",
"and",
"extracts",
"it",
"."
] | de7021f9e011615ce8b65d0cb38227c6c12721b6 | https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/renderers.py#L299-L326 |
243,577 | django-json-api/django-rest-framework-json-api | rest_framework_json_api/renderers.py | JSONRenderer.extract_meta | 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 = getattr(serializer, 'Meta', None)
meta_fields = getattr(meta, 'meta_fields', [])
data = OrderedDict()
for field_name in meta_fields:
data.update({
field_name: resource.get(field_name)
})
return data | python | def extract_meta(cls, serializer, resource):
if hasattr(serializer, 'child'):
meta = getattr(serializer.child, 'Meta', None)
else:
meta = getattr(serializer, 'Meta', None)
meta_fields = getattr(meta, 'meta_fields', [])
data = OrderedDict()
for field_name in meta_fields:
data.update({
field_name: resource.get(field_name)
})
return data | [
"def",
"extract_meta",
"(",
"cls",
",",
"serializer",
",",
"resource",
")",
":",
"if",
"hasattr",
"(",
"serializer",
",",
"'child'",
")",
":",
"meta",
"=",
"getattr",
"(",
"serializer",
".",
"child",
",",
"'Meta'",
",",
"None",
")",
"else",
":",
"meta"... | Gathers the data from serializer fields specified in meta_fields and adds it to
the meta object. | [
"Gathers",
"the",
"data",
"from",
"serializer",
"fields",
"specified",
"in",
"meta_fields",
"and",
"adds",
"it",
"to",
"the",
"meta",
"object",
"."
] | de7021f9e011615ce8b65d0cb38227c6c12721b6 | https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/renderers.py#L458-L473 |
243,578 | django-json-api/django-rest-framework-json-api | rest_framework_json_api/renderers.py | JSONRenderer.extract_root_meta | 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(serializer, 'get_root_meta', None):
json_api_meta = serializer.get_root_meta(resource, many)
assert isinstance(json_api_meta, dict), 'get_root_meta must return a dict'
data.update(json_api_meta)
return data | python | def extract_root_meta(cls, serializer, resource):
many = False
if hasattr(serializer, 'child'):
many = True
serializer = serializer.child
data = {}
if getattr(serializer, 'get_root_meta', None):
json_api_meta = serializer.get_root_meta(resource, many)
assert isinstance(json_api_meta, dict), 'get_root_meta must return a dict'
data.update(json_api_meta)
return data | [
"def",
"extract_root_meta",
"(",
"cls",
",",
"serializer",
",",
"resource",
")",
":",
"many",
"=",
"False",
"if",
"hasattr",
"(",
"serializer",
",",
"'child'",
")",
":",
"many",
"=",
"True",
"serializer",
"=",
"serializer",
".",
"child",
"data",
"=",
"{"... | Calls a `get_root_meta` function on a serializer, if it exists. | [
"Calls",
"a",
"get_root_meta",
"function",
"on",
"a",
"serializer",
"if",
"it",
"exists",
"."
] | de7021f9e011615ce8b65d0cb38227c6c12721b6 | https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/renderers.py#L476-L490 |
243,579 | django-json-api/django-rest-framework-json-api | rest_framework_json_api/views.py | PrefetchForIncludesHelperMixin.get_queryset | 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 called with ?include=author it will prefetch author and authorbio
class MyViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
prefetch_for_includes = {
'__all__': [],
'author': ['author', 'author__authorbio'],
'category.section': ['category']
}
"""
qs = super(PrefetchForIncludesHelperMixin, self).get_queryset()
if not hasattr(self, 'prefetch_for_includes'):
return qs
includes = self.request.GET.get('include', '').split(',')
for inc in includes + ['__all__']:
prefetches = self.prefetch_for_includes.get(inc)
if prefetches:
qs = qs.prefetch_related(*prefetches)
return qs | python | def get_queryset(self):
qs = super(PrefetchForIncludesHelperMixin, self).get_queryset()
if not hasattr(self, 'prefetch_for_includes'):
return qs
includes = self.request.GET.get('include', '').split(',')
for inc in includes + ['__all__']:
prefetches = self.prefetch_for_includes.get(inc)
if prefetches:
qs = qs.prefetch_related(*prefetches)
return qs | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"qs",
"=",
"super",
"(",
"PrefetchForIncludesHelperMixin",
",",
"self",
")",
".",
"get_queryset",
"(",
")",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'prefetch_for_includes'",
")",
":",
"return",
"qs",
"includes... | 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 author and authorbio
class MyViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
prefetch_for_includes = {
'__all__': [],
'author': ['author', 'author__authorbio'],
'category.section': ['category']
} | [
"This",
"viewset",
"provides",
"a",
"helper",
"attribute",
"to",
"prefetch",
"related",
"models",
"based",
"on",
"the",
"include",
"specified",
"in",
"the",
"URL",
"."
] | de7021f9e011615ce8b65d0cb38227c6c12721b6 | https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/views.py#L34-L62 |
243,580 | django-json-api/django-rest-framework-json-api | rest_framework_json_api/views.py | AutoPrefetchMixin.get_queryset | 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:
included_model = None
levels = included.split('.')
level_model = qs.model
for level in levels:
if not hasattr(level_model, level):
break
field = getattr(level_model, level)
field_class = field.__class__
is_forward_relation = (
issubclass(field_class, ForwardManyToOneDescriptor) or
issubclass(field_class, ManyToManyDescriptor)
)
is_reverse_relation = (
issubclass(field_class, ReverseManyToOneDescriptor) or
issubclass(field_class, ReverseOneToOneDescriptor)
)
if not (is_forward_relation or is_reverse_relation):
break
if level == levels[-1]:
included_model = field
else:
if issubclass(field_class, ReverseOneToOneDescriptor):
model_field = field.related.field
else:
model_field = field.field
if is_forward_relation:
level_model = model_field.related_model
else:
level_model = model_field.model
if included_model is not None:
qs = qs.prefetch_related(included.replace('.', '__'))
return qs | python | def get_queryset(self, *args, **kwargs):
qs = super(AutoPrefetchMixin, self).get_queryset(*args, **kwargs)
included_resources = get_included_resources(self.request)
for included in included_resources:
included_model = None
levels = included.split('.')
level_model = qs.model
for level in levels:
if not hasattr(level_model, level):
break
field = getattr(level_model, level)
field_class = field.__class__
is_forward_relation = (
issubclass(field_class, ForwardManyToOneDescriptor) or
issubclass(field_class, ManyToManyDescriptor)
)
is_reverse_relation = (
issubclass(field_class, ReverseManyToOneDescriptor) or
issubclass(field_class, ReverseOneToOneDescriptor)
)
if not (is_forward_relation or is_reverse_relation):
break
if level == levels[-1]:
included_model = field
else:
if issubclass(field_class, ReverseOneToOneDescriptor):
model_field = field.related.field
else:
model_field = field.field
if is_forward_relation:
level_model = model_field.related_model
else:
level_model = model_field.model
if included_model is not None:
qs = qs.prefetch_related(included.replace('.', '__'))
return qs | [
"def",
"get_queryset",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"qs",
"=",
"super",
"(",
"AutoPrefetchMixin",
",",
"self",
")",
".",
"get_queryset",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"included_resources",
"=",
"... | This mixin adds automatic prefetching for OneToOne and ManyToMany fields. | [
"This",
"mixin",
"adds",
"automatic",
"prefetching",
"for",
"OneToOne",
"and",
"ManyToMany",
"fields",
"."
] | de7021f9e011615ce8b65d0cb38227c6c12721b6 | https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/views.py#L66-L109 |
243,581 | django-json-api/django-rest-framework-json-api | rest_framework_json_api/views.py | RelationshipView.get_url | 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.
"""
# Return None if the view name is not supplied
if not view_name:
return None
# Return the hyperlink, or error if incorrectly configured.
try:
url = self.reverse(view_name, kwargs=kwargs, request=request)
except NoReverseMatch:
msg = (
'Could not resolve URL for hyperlinked relationship using '
'view name "%s". You may have failed to include the related '
'model in your API, or incorrectly configured the '
'`lookup_field` attribute on this field.'
)
raise ImproperlyConfigured(msg % view_name)
if url is None:
return None
return Hyperlink(url, name) | python | def get_url(self, name, view_name, kwargs, request):
# Return None if the view name is not supplied
if not view_name:
return None
# Return the hyperlink, or error if incorrectly configured.
try:
url = self.reverse(view_name, kwargs=kwargs, request=request)
except NoReverseMatch:
msg = (
'Could not resolve URL for hyperlinked relationship using '
'view name "%s". You may have failed to include the related '
'model in your API, or incorrectly configured the '
'`lookup_field` attribute on this field.'
)
raise ImproperlyConfigured(msg % view_name)
if url is None:
return None
return Hyperlink(url, name) | [
"def",
"get_url",
"(",
"self",
",",
"name",
",",
"view_name",
",",
"kwargs",
",",
"request",
")",
":",
"# Return None if the view name is not supplied",
"if",
"not",
"view_name",
":",
"return",
"None",
"# Return the hyperlink, or error if incorrectly configured.",
"try",
... | 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. | [
"Given",
"a",
"name",
"view",
"name",
"and",
"kwargs",
"return",
"the",
"URL",
"that",
"hyperlinks",
"to",
"the",
"object",
"."
] | de7021f9e011615ce8b65d0cb38227c6c12721b6 | https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/views.py#L221-L248 |
243,582 | django-json-api/django-rest-framework-json-api | rest_framework_json_api/utils.py | get_resource_name | 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
# Check to see if there is a status code and return early
# with the resource_name value of `errors`.
try:
code = str(view.response.status_code)
except (AttributeError, ValueError):
pass
else:
if code.startswith('4') or code.startswith('5'):
return 'errors'
try:
resource_name = getattr(view, 'resource_name')
except AttributeError:
try:
serializer = view.get_serializer_class()
if expand_polymorphic_types and issubclass(serializer, PolymorphicModelSerializer):
return serializer.get_polymorphic_types()
else:
return get_resource_type_from_serializer(serializer)
except AttributeError:
try:
resource_name = get_resource_type_from_model(view.model)
except AttributeError:
resource_name = view.__class__.__name__
if not isinstance(resource_name, six.string_types):
# The resource name is not a string - return as is
return resource_name
# the name was calculated automatically from the view > pluralize and format
resource_name = format_resource_type(resource_name)
return resource_name | python | def get_resource_name(context, expand_polymorphic_types=False):
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
# Check to see if there is a status code and return early
# with the resource_name value of `errors`.
try:
code = str(view.response.status_code)
except (AttributeError, ValueError):
pass
else:
if code.startswith('4') or code.startswith('5'):
return 'errors'
try:
resource_name = getattr(view, 'resource_name')
except AttributeError:
try:
serializer = view.get_serializer_class()
if expand_polymorphic_types and issubclass(serializer, PolymorphicModelSerializer):
return serializer.get_polymorphic_types()
else:
return get_resource_type_from_serializer(serializer)
except AttributeError:
try:
resource_name = get_resource_type_from_model(view.model)
except AttributeError:
resource_name = view.__class__.__name__
if not isinstance(resource_name, six.string_types):
# The resource name is not a string - return as is
return resource_name
# the name was calculated automatically from the view > pluralize and format
resource_name = format_resource_type(resource_name)
return resource_name | [
"def",
"get_resource_name",
"(",
"context",
",",
"expand_polymorphic_types",
"=",
"False",
")",
":",
"from",
"rest_framework_json_api",
".",
"serializers",
"import",
"PolymorphicModelSerializer",
"view",
"=",
"context",
".",
"get",
"(",
"'view'",
")",
"# Sanity check ... | Return the name of a resource. | [
"Return",
"the",
"name",
"of",
"a",
"resource",
"."
] | de7021f9e011615ce8b65d0cb38227c6c12721b6 | https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/utils.py#L36-L79 |
243,583 | django-json-api/django-rest-framework-json-api | rest_framework_json_api/utils.py | format_field_names | 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_settings.FORMAT_FIELD_NAMES
if isinstance(obj, dict):
formatted = OrderedDict()
for key, value in obj.items():
key = format_value(key, format_type)
formatted[key] = value
return formatted
return obj | python | def format_field_names(obj, format_type=None):
if format_type is None:
format_type = json_api_settings.FORMAT_FIELD_NAMES
if isinstance(obj, dict):
formatted = OrderedDict()
for key, value in obj.items():
key = format_value(key, format_type)
formatted[key] = value
return formatted
return obj | [
"def",
"format_field_names",
"(",
"obj",
",",
"format_type",
"=",
"None",
")",
":",
"if",
"format_type",
"is",
"None",
":",
"format_type",
"=",
"json_api_settings",
".",
"FORMAT_FIELD_NAMES",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"formatted",
... | 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' | [
"Takes",
"a",
"dict",
"and",
"returns",
"it",
"with",
"formatted",
"keys",
"as",
"set",
"in",
"format_type",
"or",
"JSON_API_FORMAT_FIELD_NAMES"
] | de7021f9e011615ce8b65d0cb38227c6c12721b6 | https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/utils.py#L101-L118 |
243,584 | django-json-api/django-rest-framework-json-api | rest_framework_json_api/utils.py | _format_object | 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) | python | def _format_object(obj, format_type=None):
if json_api_settings.FORMAT_KEYS is not None:
return format_keys(obj, format_type)
return format_field_names(obj, format_type) | [
"def",
"_format_object",
"(",
"obj",
",",
"format_type",
"=",
"None",
")",
":",
"if",
"json_api_settings",
".",
"FORMAT_KEYS",
"is",
"not",
"None",
":",
"return",
"format_keys",
"(",
"obj",
",",
"format_type",
")",
"return",
"format_field_names",
"(",
"obj",
... | Depending on settings calls either `format_keys` or `format_field_names` | [
"Depending",
"on",
"settings",
"calls",
"either",
"format_keys",
"or",
"format_field_names"
] | de7021f9e011615ce8b65d0cb38227c6c12721b6 | https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/utils.py#L121-L127 |
243,585 | django-json-api/django-rest-framework-json-api | rest_framework_json_api/utils.py | get_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_resources_from_serializer(serializer) | python | def get_included_resources(request, serializer=None):
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_resources_from_serializer(serializer) | [
"def",
"get_included_resources",
"(",
"request",
",",
"serializer",
"=",
"None",
")",
":",
"include_resources_param",
"=",
"request",
".",
"query_params",
".",
"get",
"(",
"'include'",
")",
"if",
"request",
"else",
"None",
"if",
"include_resources_param",
":",
"... | Build a list of included resources. | [
"Build",
"a",
"list",
"of",
"included",
"resources",
"."
] | de7021f9e011615ce8b65d0cb38227c6c12721b6 | https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/utils.py#L327-L333 |
243,586 | django-json-api/django-rest-framework-json-api | rest_framework_json_api/parsers.py | JSONParser.parse | 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 isinstance(result, dict) or 'data' not in result:
raise ParseError('Received document does not contain primary data')
data = result.get('data')
view = parser_context['view']
from rest_framework_json_api.views import RelationshipView
if isinstance(view, RelationshipView):
# We skip parsing the object as JSONAPI Resource Identifier Object and not a regular
# Resource Object
if isinstance(data, list):
for resource_identifier_object in data:
if not (
resource_identifier_object.get('id') and
resource_identifier_object.get('type')
):
raise ParseError(
'Received data contains one or more malformed JSONAPI '
'Resource Identifier Object(s)'
)
elif not (data.get('id') and data.get('type')):
raise ParseError('Received data is not a valid JSONAPI Resource Identifier Object')
return data
request = parser_context.get('request')
# Check for inconsistencies
if request.method in ('PUT', 'POST', 'PATCH'):
resource_name = utils.get_resource_name(
parser_context, expand_polymorphic_types=True)
if isinstance(resource_name, six.string_types):
if data.get('type') != resource_name:
raise exceptions.Conflict(
"The resource object's type ({data_type}) is not the type that "
"constitute the collection represented by the endpoint "
"({resource_type}).".format(
data_type=data.get('type'),
resource_type=resource_name))
else:
if data.get('type') not in resource_name:
raise exceptions.Conflict(
"The resource object's type ({data_type}) is not the type that "
"constitute the collection represented by the endpoint "
"(one of [{resource_types}]).".format(
data_type=data.get('type'),
resource_types=", ".join(resource_name)))
if not data.get('id') and request.method in ('PATCH', 'PUT'):
raise ParseError("The resource identifier object must contain an 'id' member")
# Construct the return data
serializer_class = getattr(view, 'serializer_class', None)
parsed_data = {'id': data.get('id')} if 'id' in data else {}
# `type` field needs to be allowed in none polymorphic serializers
if serializer_class is not None:
if issubclass(serializer_class, serializers.PolymorphicModelSerializer):
parsed_data['type'] = data.get('type')
parsed_data.update(self.parse_attributes(data))
parsed_data.update(self.parse_relationships(data))
parsed_data.update(self.parse_metadata(result))
return parsed_data | python | def parse(self, stream, media_type=None, parser_context=None):
result = super(JSONParser, self).parse(
stream, media_type=media_type, parser_context=parser_context
)
if not isinstance(result, dict) or 'data' not in result:
raise ParseError('Received document does not contain primary data')
data = result.get('data')
view = parser_context['view']
from rest_framework_json_api.views import RelationshipView
if isinstance(view, RelationshipView):
# We skip parsing the object as JSONAPI Resource Identifier Object and not a regular
# Resource Object
if isinstance(data, list):
for resource_identifier_object in data:
if not (
resource_identifier_object.get('id') and
resource_identifier_object.get('type')
):
raise ParseError(
'Received data contains one or more malformed JSONAPI '
'Resource Identifier Object(s)'
)
elif not (data.get('id') and data.get('type')):
raise ParseError('Received data is not a valid JSONAPI Resource Identifier Object')
return data
request = parser_context.get('request')
# Check for inconsistencies
if request.method in ('PUT', 'POST', 'PATCH'):
resource_name = utils.get_resource_name(
parser_context, expand_polymorphic_types=True)
if isinstance(resource_name, six.string_types):
if data.get('type') != resource_name:
raise exceptions.Conflict(
"The resource object's type ({data_type}) is not the type that "
"constitute the collection represented by the endpoint "
"({resource_type}).".format(
data_type=data.get('type'),
resource_type=resource_name))
else:
if data.get('type') not in resource_name:
raise exceptions.Conflict(
"The resource object's type ({data_type}) is not the type that "
"constitute the collection represented by the endpoint "
"(one of [{resource_types}]).".format(
data_type=data.get('type'),
resource_types=", ".join(resource_name)))
if not data.get('id') and request.method in ('PATCH', 'PUT'):
raise ParseError("The resource identifier object must contain an 'id' member")
# Construct the return data
serializer_class = getattr(view, 'serializer_class', None)
parsed_data = {'id': data.get('id')} if 'id' in data else {}
# `type` field needs to be allowed in none polymorphic serializers
if serializer_class is not None:
if issubclass(serializer_class, serializers.PolymorphicModelSerializer):
parsed_data['type'] = data.get('type')
parsed_data.update(self.parse_attributes(data))
parsed_data.update(self.parse_relationships(data))
parsed_data.update(self.parse_metadata(result))
return parsed_data | [
"def",
"parse",
"(",
"self",
",",
"stream",
",",
"media_type",
"=",
"None",
",",
"parser_context",
"=",
"None",
")",
":",
"result",
"=",
"super",
"(",
"JSONParser",
",",
"self",
")",
".",
"parse",
"(",
"stream",
",",
"media_type",
"=",
"media_type",
",... | Parses the incoming bytestream as JSON and returns the resulting data | [
"Parses",
"the",
"incoming",
"bytestream",
"as",
"JSON",
"and",
"returns",
"the",
"resulting",
"data"
] | de7021f9e011615ce8b65d0cb38227c6c12721b6 | https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/parsers.py#L85-L153 |
243,587 | django-json-api/django-rest-framework-json-api | rest_framework_json_api/relations.py | ResourceRelatedField.get_resource_type_from_included_serializer | def get_resource_type_from_included_serializer(self):
"""
Check to see it this resource has a different resource_name when
included and return that name, or None
"""
field_name = self.field_name or self.parent.field_name
parent = self.get_parent_serializer()
if parent is not None:
# accept both singular and plural versions of field_name
field_names = [
inflection.singularize(field_name),
inflection.pluralize(field_name)
]
includes = get_included_serializers(parent)
for field in field_names:
if field in includes.keys():
return get_resource_type_from_serializer(includes[field])
return None | python | def get_resource_type_from_included_serializer(self):
field_name = self.field_name or self.parent.field_name
parent = self.get_parent_serializer()
if parent is not None:
# accept both singular and plural versions of field_name
field_names = [
inflection.singularize(field_name),
inflection.pluralize(field_name)
]
includes = get_included_serializers(parent)
for field in field_names:
if field in includes.keys():
return get_resource_type_from_serializer(includes[field])
return None | [
"def",
"get_resource_type_from_included_serializer",
"(",
"self",
")",
":",
"field_name",
"=",
"self",
".",
"field_name",
"or",
"self",
".",
"parent",
".",
"field_name",
"parent",
"=",
"self",
".",
"get_parent_serializer",
"(",
")",
"if",
"parent",
"is",
"not",
... | Check to see it this resource has a different resource_name when
included and return that name, or None | [
"Check",
"to",
"see",
"it",
"this",
"resource",
"has",
"a",
"different",
"resource_name",
"when",
"included",
"and",
"return",
"that",
"name",
"or",
"None"
] | de7021f9e011615ce8b65d0cb38227c6c12721b6 | https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/relations.py#L255-L274 |
243,588 | oauthlib/oauthlib | oauthlib/oauth1/rfc5849/signature.py | sign_plaintext | def sign_plaintext(client_secret, resource_owner_secret):
"""Sign a request using plaintext.
Per `section 3.4.4`_ of the spec.
The "PLAINTEXT" method does not employ a signature algorithm. It
MUST be used with a transport-layer mechanism such as TLS or SSL (or
sent over a secure channel with equivalent protections). It does not
utilize the signature base string or the "oauth_timestamp" and
"oauth_nonce" parameters.
.. _`section 3.4.4`: https://tools.ietf.org/html/rfc5849#section-3.4.4
"""
# The "oauth_signature" protocol parameter is set to the concatenated
# value of:
# 1. The client shared-secret, after being encoded (`Section 3.6`_).
#
# .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6
signature = utils.escape(client_secret or '')
# 2. An "&" character (ASCII code 38), which MUST be included even
# when either secret is empty.
signature += '&'
# 3. The token shared-secret, after being encoded (`Section 3.6`_).
#
# .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6
signature += utils.escape(resource_owner_secret or '')
return signature | python | def sign_plaintext(client_secret, resource_owner_secret):
# The "oauth_signature" protocol parameter is set to the concatenated
# value of:
# 1. The client shared-secret, after being encoded (`Section 3.6`_).
#
# .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6
signature = utils.escape(client_secret or '')
# 2. An "&" character (ASCII code 38), which MUST be included even
# when either secret is empty.
signature += '&'
# 3. The token shared-secret, after being encoded (`Section 3.6`_).
#
# .. _`Section 3.6`: https://tools.ietf.org/html/rfc5849#section-3.6
signature += utils.escape(resource_owner_secret or '')
return signature | [
"def",
"sign_plaintext",
"(",
"client_secret",
",",
"resource_owner_secret",
")",
":",
"# The \"oauth_signature\" protocol parameter is set to the concatenated",
"# value of:",
"# 1. The client shared-secret, after being encoded (`Section 3.6`_).",
"#",
"# .. _`Section 3.6`: https://tools.i... | Sign a request using plaintext.
Per `section 3.4.4`_ of the spec.
The "PLAINTEXT" method does not employ a signature algorithm. It
MUST be used with a transport-layer mechanism such as TLS or SSL (or
sent over a secure channel with equivalent protections). It does not
utilize the signature base string or the "oauth_timestamp" and
"oauth_nonce" parameters.
.. _`section 3.4.4`: https://tools.ietf.org/html/rfc5849#section-3.4.4 | [
"Sign",
"a",
"request",
"using",
"plaintext",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/signature.py#L595-L627 |
243,589 | oauthlib/oauthlib | oauthlib/oauth1/rfc5849/signature.py | verify_hmac_sha1 | def verify_hmac_sha1(request, client_secret=None,
resource_owner_secret=None):
"""Verify a HMAC-SHA1 signature.
Per `section 3.4`_ of the spec.
.. _`section 3.4`: https://tools.ietf.org/html/rfc5849#section-3.4
To satisfy `RFC2616 section 5.2`_ item 1, the request argument's uri
attribute MUST be an absolute URI whose netloc part identifies the
origin server or gateway on which the resource resides. Any Host
item of the request argument's headers dict attribute will be
ignored.
.. _`RFC2616 section 5.2`: https://tools.ietf.org/html/rfc2616#section-5.2
"""
norm_params = normalize_parameters(request.params)
bs_uri = base_string_uri(request.uri)
sig_base_str = signature_base_string(request.http_method, bs_uri,
norm_params)
signature = sign_hmac_sha1(sig_base_str, client_secret,
resource_owner_secret)
match = safe_string_equals(signature, request.signature)
if not match:
log.debug('Verify HMAC-SHA1 failed: signature base string: %s',
sig_base_str)
return match | python | def verify_hmac_sha1(request, client_secret=None,
resource_owner_secret=None):
norm_params = normalize_parameters(request.params)
bs_uri = base_string_uri(request.uri)
sig_base_str = signature_base_string(request.http_method, bs_uri,
norm_params)
signature = sign_hmac_sha1(sig_base_str, client_secret,
resource_owner_secret)
match = safe_string_equals(signature, request.signature)
if not match:
log.debug('Verify HMAC-SHA1 failed: signature base string: %s',
sig_base_str)
return match | [
"def",
"verify_hmac_sha1",
"(",
"request",
",",
"client_secret",
"=",
"None",
",",
"resource_owner_secret",
"=",
"None",
")",
":",
"norm_params",
"=",
"normalize_parameters",
"(",
"request",
".",
"params",
")",
"bs_uri",
"=",
"base_string_uri",
"(",
"request",
"... | Verify a HMAC-SHA1 signature.
Per `section 3.4`_ of the spec.
.. _`section 3.4`: https://tools.ietf.org/html/rfc5849#section-3.4
To satisfy `RFC2616 section 5.2`_ item 1, the request argument's uri
attribute MUST be an absolute URI whose netloc part identifies the
origin server or gateway on which the resource resides. Any Host
item of the request argument's headers dict attribute will be
ignored.
.. _`RFC2616 section 5.2`: https://tools.ietf.org/html/rfc2616#section-5.2 | [
"Verify",
"a",
"HMAC",
"-",
"SHA1",
"signature",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/signature.py#L634-L661 |
243,590 | oauthlib/oauthlib | oauthlib/oauth1/rfc5849/signature.py | verify_plaintext | def verify_plaintext(request, client_secret=None, resource_owner_secret=None):
"""Verify a PLAINTEXT signature.
Per `section 3.4`_ of the spec.
.. _`section 3.4`: https://tools.ietf.org/html/rfc5849#section-3.4
"""
signature = sign_plaintext(client_secret, resource_owner_secret)
match = safe_string_equals(signature, request.signature)
if not match:
log.debug('Verify PLAINTEXT failed')
return match | python | def verify_plaintext(request, client_secret=None, resource_owner_secret=None):
signature = sign_plaintext(client_secret, resource_owner_secret)
match = safe_string_equals(signature, request.signature)
if not match:
log.debug('Verify PLAINTEXT failed')
return match | [
"def",
"verify_plaintext",
"(",
"request",
",",
"client_secret",
"=",
"None",
",",
"resource_owner_secret",
"=",
"None",
")",
":",
"signature",
"=",
"sign_plaintext",
"(",
"client_secret",
",",
"resource_owner_secret",
")",
"match",
"=",
"safe_string_equals",
"(",
... | Verify a PLAINTEXT signature.
Per `section 3.4`_ of the spec.
.. _`section 3.4`: https://tools.ietf.org/html/rfc5849#section-3.4 | [
"Verify",
"a",
"PLAINTEXT",
"signature",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/signature.py#L702-L713 |
243,591 | oauthlib/oauthlib | oauthlib/oauth1/rfc5849/endpoints/authorization.py | AuthorizationEndpoint.create_authorization_response | def create_authorization_response(self, uri, http_method='GET', body=None,
headers=None, realms=None, credentials=None):
"""Create an authorization response, with a new request token if valid.
:param uri: The full URI of the token request.
:param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc.
:param body: The request body as a string.
:param headers: The request headers as a dict.
:param credentials: A list of credentials to include in the verifier.
:returns: A tuple of 3 elements.
1. A dict of headers to set on the response.
2. The response body as a string.
3. The response status code as an integer.
If the callback URI tied to the current token is "oob", a response with
a 200 status code will be returned. In this case, it may be desirable to
modify the response to better display the verifier to the client.
An example of an authorization request::
>>> from your_validator import your_validator
>>> from oauthlib.oauth1 import AuthorizationEndpoint
>>> endpoint = AuthorizationEndpoint(your_validator)
>>> h, b, s = endpoint.create_authorization_response(
... 'https://your.provider/authorize?oauth_token=...',
... credentials={
... 'extra': 'argument',
... })
>>> h
{'Location': 'https://the.client/callback?oauth_verifier=...&extra=argument'}
>>> b
None
>>> s
302
An example of a request with an "oob" callback::
>>> from your_validator import your_validator
>>> from oauthlib.oauth1 import AuthorizationEndpoint
>>> endpoint = AuthorizationEndpoint(your_validator)
>>> h, b, s = endpoint.create_authorization_response(
... 'https://your.provider/authorize?foo=bar',
... credentials={
... 'extra': 'argument',
... })
>>> h
{'Content-Type': 'application/x-www-form-urlencoded'}
>>> b
'oauth_verifier=...&extra=argument'
>>> s
200
"""
request = self._create_request(uri, http_method=http_method, body=body,
headers=headers)
if not request.resource_owner_key:
raise errors.InvalidRequestError(
'Missing mandatory parameter oauth_token.')
if not self.request_validator.verify_request_token(
request.resource_owner_key, request):
raise errors.InvalidClientError()
request.realms = realms
if (request.realms and not self.request_validator.verify_realms(
request.resource_owner_key, request.realms, request)):
raise errors.InvalidRequestError(
description=('User granted access to realms outside of '
'what the client may request.'))
verifier = self.create_verifier(request, credentials or {})
redirect_uri = self.request_validator.get_redirect_uri(
request.resource_owner_key, request)
if redirect_uri == 'oob':
response_headers = {
'Content-Type': 'application/x-www-form-urlencoded'}
response_body = urlencode(verifier)
return response_headers, response_body, 200
else:
populated_redirect = add_params_to_uri(
redirect_uri, verifier.items())
return {'Location': populated_redirect}, None, 302 | python | def create_authorization_response(self, uri, http_method='GET', body=None,
headers=None, realms=None, credentials=None):
request = self._create_request(uri, http_method=http_method, body=body,
headers=headers)
if not request.resource_owner_key:
raise errors.InvalidRequestError(
'Missing mandatory parameter oauth_token.')
if not self.request_validator.verify_request_token(
request.resource_owner_key, request):
raise errors.InvalidClientError()
request.realms = realms
if (request.realms and not self.request_validator.verify_realms(
request.resource_owner_key, request.realms, request)):
raise errors.InvalidRequestError(
description=('User granted access to realms outside of '
'what the client may request.'))
verifier = self.create_verifier(request, credentials or {})
redirect_uri = self.request_validator.get_redirect_uri(
request.resource_owner_key, request)
if redirect_uri == 'oob':
response_headers = {
'Content-Type': 'application/x-www-form-urlencoded'}
response_body = urlencode(verifier)
return response_headers, response_body, 200
else:
populated_redirect = add_params_to_uri(
redirect_uri, verifier.items())
return {'Location': populated_redirect}, None, 302 | [
"def",
"create_authorization_response",
"(",
"self",
",",
"uri",
",",
"http_method",
"=",
"'GET'",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"realms",
"=",
"None",
",",
"credentials",
"=",
"None",
")",
":",
"request",
"=",
"self",
".",
... | Create an authorization response, with a new request token if valid.
:param uri: The full URI of the token request.
:param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc.
:param body: The request body as a string.
:param headers: The request headers as a dict.
:param credentials: A list of credentials to include in the verifier.
:returns: A tuple of 3 elements.
1. A dict of headers to set on the response.
2. The response body as a string.
3. The response status code as an integer.
If the callback URI tied to the current token is "oob", a response with
a 200 status code will be returned. In this case, it may be desirable to
modify the response to better display the verifier to the client.
An example of an authorization request::
>>> from your_validator import your_validator
>>> from oauthlib.oauth1 import AuthorizationEndpoint
>>> endpoint = AuthorizationEndpoint(your_validator)
>>> h, b, s = endpoint.create_authorization_response(
... 'https://your.provider/authorize?oauth_token=...',
... credentials={
... 'extra': 'argument',
... })
>>> h
{'Location': 'https://the.client/callback?oauth_verifier=...&extra=argument'}
>>> b
None
>>> s
302
An example of a request with an "oob" callback::
>>> from your_validator import your_validator
>>> from oauthlib.oauth1 import AuthorizationEndpoint
>>> endpoint = AuthorizationEndpoint(your_validator)
>>> h, b, s = endpoint.create_authorization_response(
... 'https://your.provider/authorize?foo=bar',
... credentials={
... 'extra': 'argument',
... })
>>> h
{'Content-Type': 'application/x-www-form-urlencoded'}
>>> b
'oauth_verifier=...&extra=argument'
>>> s
200 | [
"Create",
"an",
"authorization",
"response",
"with",
"a",
"new",
"request",
"token",
"if",
"valid",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/endpoints/authorization.py#L59-L139 |
243,592 | oauthlib/oauthlib | oauthlib/oauth1/rfc5849/endpoints/authorization.py | AuthorizationEndpoint.get_realms_and_credentials | def get_realms_and_credentials(self, uri, http_method='GET', body=None,
headers=None):
"""Fetch realms and credentials for the presented request token.
:param uri: The full URI of the token request.
:param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc.
:param body: The request body as a string.
:param headers: The request headers as a dict.
:returns: A tuple of 2 elements.
1. A list of request realms.
2. A dict of credentials which may be useful in creating the
authorization form.
"""
request = self._create_request(uri, http_method=http_method, body=body,
headers=headers)
if not self.request_validator.verify_request_token(
request.resource_owner_key, request):
raise errors.InvalidClientError()
realms = self.request_validator.get_realms(
request.resource_owner_key, request)
return realms, {'resource_owner_key': request.resource_owner_key} | python | def get_realms_and_credentials(self, uri, http_method='GET', body=None,
headers=None):
request = self._create_request(uri, http_method=http_method, body=body,
headers=headers)
if not self.request_validator.verify_request_token(
request.resource_owner_key, request):
raise errors.InvalidClientError()
realms = self.request_validator.get_realms(
request.resource_owner_key, request)
return realms, {'resource_owner_key': request.resource_owner_key} | [
"def",
"get_realms_and_credentials",
"(",
"self",
",",
"uri",
",",
"http_method",
"=",
"'GET'",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"request",
"=",
"self",
".",
"_create_request",
"(",
"uri",
",",
"http_method",
"=",
"http_meth... | Fetch realms and credentials for the presented request token.
:param uri: The full URI of the token request.
:param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc.
:param body: The request body as a string.
:param headers: The request headers as a dict.
:returns: A tuple of 2 elements.
1. A list of request realms.
2. A dict of credentials which may be useful in creating the
authorization form. | [
"Fetch",
"realms",
"and",
"credentials",
"for",
"the",
"presented",
"request",
"token",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/endpoints/authorization.py#L141-L163 |
243,593 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/endpoints/introspect.py | IntrospectEndpoint.create_introspect_response | def create_introspect_response(self, uri, http_method='POST', body=None,
headers=None):
"""Create introspect valid or invalid response
If the authorization server is unable to determine the state
of the token without additional information, it SHOULD return
an introspection response indicating the token is not active
as described in Section 2.2.
"""
resp_headers = {
'Content-Type': 'application/json',
'Cache-Control': 'no-store',
'Pragma': 'no-cache',
}
request = Request(uri, http_method, body, headers)
try:
self.validate_introspect_request(request)
log.debug('Token introspect valid for %r.', request)
except OAuth2Error as e:
log.debug('Client error during validation of %r. %r.', request, e)
resp_headers.update(e.headers)
return resp_headers, e.json, e.status_code
claims = self.request_validator.introspect_token(
request.token,
request.token_type_hint,
request
)
if claims is None:
return resp_headers, json.dumps(dict(active=False)), 200
if "active" in claims:
claims.pop("active")
return resp_headers, json.dumps(dict(active=True, **claims)), 200 | python | def create_introspect_response(self, uri, http_method='POST', body=None,
headers=None):
resp_headers = {
'Content-Type': 'application/json',
'Cache-Control': 'no-store',
'Pragma': 'no-cache',
}
request = Request(uri, http_method, body, headers)
try:
self.validate_introspect_request(request)
log.debug('Token introspect valid for %r.', request)
except OAuth2Error as e:
log.debug('Client error during validation of %r. %r.', request, e)
resp_headers.update(e.headers)
return resp_headers, e.json, e.status_code
claims = self.request_validator.introspect_token(
request.token,
request.token_type_hint,
request
)
if claims is None:
return resp_headers, json.dumps(dict(active=False)), 200
if "active" in claims:
claims.pop("active")
return resp_headers, json.dumps(dict(active=True, **claims)), 200 | [
"def",
"create_introspect_response",
"(",
"self",
",",
"uri",
",",
"http_method",
"=",
"'POST'",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"resp_headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
",",
"'Cache-Control'",
":"... | Create introspect valid or invalid response
If the authorization server is unable to determine the state
of the token without additional information, it SHOULD return
an introspection response indicating the token is not active
as described in Section 2.2. | [
"Create",
"introspect",
"valid",
"or",
"invalid",
"response"
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/endpoints/introspect.py#L50-L82 |
243,594 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/clients/service_application.py | ServiceApplicationClient.prepare_request_body | def prepare_request_body(self,
private_key=None,
subject=None,
issuer=None,
audience=None,
expires_at=None,
issued_at=None,
extra_claims=None,
body='',
scope=None,
include_client_id=False,
**kwargs):
"""Create and add a JWT assertion to the request body.
:param private_key: Private key used for signing and encrypting.
Must be given as a string.
:param subject: (sub) The principal that is the subject of the JWT,
i.e. which user is the token requested on behalf of.
For example, ``foo@example.com.
:param issuer: (iss) The JWT MUST contain an "iss" (issuer) claim that
contains a unique identifier for the entity that issued
the JWT. For example, ``your-client@provider.com``.
:param audience: (aud) A value identifying the authorization server as an
intended audience, e.g.
``https://provider.com/oauth2/token``.
:param expires_at: A unix expiration timestamp for the JWT. Defaults
to an hour from now, i.e. ``time.time() + 3600``.
:param issued_at: A unix timestamp of when the JWT was created.
Defaults to now, i.e. ``time.time()``.
:param extra_claims: A dict of additional claims to include in the JWT.
:param body: Existing request body (URL encoded string) to embed parameters
into. This may contain extra paramters. Default ''.
:param scope: The scope of the access request.
:param include_client_id: `True` to send the `client_id` in the
body of the upstream request. This is required
if the client is not authenticating with the
authorization server as described in
`Section 3.2.1`_. False otherwise (default).
:type include_client_id: Boolean
:param not_before: A unix timestamp after which the JWT may be used.
Not included unless provided. *
:param jwt_id: A unique JWT token identifier. Not included unless
provided. *
:param kwargs: Extra credentials to include in the token request.
Parameters marked with a `*` above are not explicit arguments in the
function signature, but are specially documented arguments for items
appearing in the generic `**kwargs` keyworded input.
The "scope" parameter may be used, as defined in the Assertion
Framework for OAuth 2.0 Client Authentication and Authorization Grants
[I-D.ietf-oauth-assertions] specification, to indicate the requested
scope.
Authentication of the client is optional, as described in
`Section 3.2.1`_ of OAuth 2.0 [RFC6749] and consequently, the
"client_id" is only needed when a form of client authentication that
relies on the parameter is used.
The following non-normative example demonstrates an Access Token
Request with a JWT as an authorization grant (with extra line breaks
for display purposes only):
.. code-block: http
POST /token.oauth2 HTTP/1.1
Host: as.example.com
Content-Type: application/x-www-form-urlencoded
grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer
&assertion=eyJhbGciOiJFUzI1NiJ9.
eyJpc3Mi[...omitted for brevity...].
J9l-ZhwP[...omitted for brevity...]
.. _`Section 3.2.1`: https://tools.ietf.org/html/rfc6749#section-3.2.1
"""
import jwt
key = private_key or self.private_key
if not key:
raise ValueError('An encryption key must be supplied to make JWT'
' token requests.')
claim = {
'iss': issuer or self.issuer,
'aud': audience or self.audience,
'sub': subject or self.subject,
'exp': int(expires_at or time.time() + 3600),
'iat': int(issued_at or time.time()),
}
for attr in ('iss', 'aud', 'sub'):
if claim[attr] is None:
raise ValueError(
'Claim must include %s but none was given.' % attr)
if 'not_before' in kwargs:
claim['nbf'] = kwargs.pop('not_before')
if 'jwt_id' in kwargs:
claim['jti'] = kwargs.pop('jwt_id')
claim.update(extra_claims or {})
assertion = jwt.encode(claim, key, 'RS256')
assertion = to_unicode(assertion)
kwargs['client_id'] = self.client_id
kwargs['include_client_id'] = include_client_id
return prepare_token_request(self.grant_type,
body=body,
assertion=assertion,
scope=scope,
**kwargs) | python | def prepare_request_body(self,
private_key=None,
subject=None,
issuer=None,
audience=None,
expires_at=None,
issued_at=None,
extra_claims=None,
body='',
scope=None,
include_client_id=False,
**kwargs):
import jwt
key = private_key or self.private_key
if not key:
raise ValueError('An encryption key must be supplied to make JWT'
' token requests.')
claim = {
'iss': issuer or self.issuer,
'aud': audience or self.audience,
'sub': subject or self.subject,
'exp': int(expires_at or time.time() + 3600),
'iat': int(issued_at or time.time()),
}
for attr in ('iss', 'aud', 'sub'):
if claim[attr] is None:
raise ValueError(
'Claim must include %s but none was given.' % attr)
if 'not_before' in kwargs:
claim['nbf'] = kwargs.pop('not_before')
if 'jwt_id' in kwargs:
claim['jti'] = kwargs.pop('jwt_id')
claim.update(extra_claims or {})
assertion = jwt.encode(claim, key, 'RS256')
assertion = to_unicode(assertion)
kwargs['client_id'] = self.client_id
kwargs['include_client_id'] = include_client_id
return prepare_token_request(self.grant_type,
body=body,
assertion=assertion,
scope=scope,
**kwargs) | [
"def",
"prepare_request_body",
"(",
"self",
",",
"private_key",
"=",
"None",
",",
"subject",
"=",
"None",
",",
"issuer",
"=",
"None",
",",
"audience",
"=",
"None",
",",
"expires_at",
"=",
"None",
",",
"issued_at",
"=",
"None",
",",
"extra_claims",
"=",
"... | Create and add a JWT assertion to the request body.
:param private_key: Private key used for signing and encrypting.
Must be given as a string.
:param subject: (sub) The principal that is the subject of the JWT,
i.e. which user is the token requested on behalf of.
For example, ``foo@example.com.
:param issuer: (iss) The JWT MUST contain an "iss" (issuer) claim that
contains a unique identifier for the entity that issued
the JWT. For example, ``your-client@provider.com``.
:param audience: (aud) A value identifying the authorization server as an
intended audience, e.g.
``https://provider.com/oauth2/token``.
:param expires_at: A unix expiration timestamp for the JWT. Defaults
to an hour from now, i.e. ``time.time() + 3600``.
:param issued_at: A unix timestamp of when the JWT was created.
Defaults to now, i.e. ``time.time()``.
:param extra_claims: A dict of additional claims to include in the JWT.
:param body: Existing request body (URL encoded string) to embed parameters
into. This may contain extra paramters. Default ''.
:param scope: The scope of the access request.
:param include_client_id: `True` to send the `client_id` in the
body of the upstream request. This is required
if the client is not authenticating with the
authorization server as described in
`Section 3.2.1`_. False otherwise (default).
:type include_client_id: Boolean
:param not_before: A unix timestamp after which the JWT may be used.
Not included unless provided. *
:param jwt_id: A unique JWT token identifier. Not included unless
provided. *
:param kwargs: Extra credentials to include in the token request.
Parameters marked with a `*` above are not explicit arguments in the
function signature, but are specially documented arguments for items
appearing in the generic `**kwargs` keyworded input.
The "scope" parameter may be used, as defined in the Assertion
Framework for OAuth 2.0 Client Authentication and Authorization Grants
[I-D.ietf-oauth-assertions] specification, to indicate the requested
scope.
Authentication of the client is optional, as described in
`Section 3.2.1`_ of OAuth 2.0 [RFC6749] and consequently, the
"client_id" is only needed when a form of client authentication that
relies on the parameter is used.
The following non-normative example demonstrates an Access Token
Request with a JWT as an authorization grant (with extra line breaks
for display purposes only):
.. code-block: http
POST /token.oauth2 HTTP/1.1
Host: as.example.com
Content-Type: application/x-www-form-urlencoded
grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer
&assertion=eyJhbGciOiJFUzI1NiJ9.
eyJpc3Mi[...omitted for brevity...].
J9l-ZhwP[...omitted for brevity...]
.. _`Section 3.2.1`: https://tools.ietf.org/html/rfc6749#section-3.2.1 | [
"Create",
"and",
"add",
"a",
"JWT",
"assertion",
"to",
"the",
"request",
"body",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/clients/service_application.py#L66-L190 |
243,595 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/grant_types/authorization_code.py | AuthorizationCodeGrant.create_authorization_code | def create_authorization_code(self, request):
"""
Generates an authorization grant represented as a dictionary.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
"""
grant = {'code': common.generate_token()}
if hasattr(request, 'state') and request.state:
grant['state'] = request.state
log.debug('Created authorization code grant %r for request %r.',
grant, request)
return grant | python | def create_authorization_code(self, request):
grant = {'code': common.generate_token()}
if hasattr(request, 'state') and request.state:
grant['state'] = request.state
log.debug('Created authorization code grant %r for request %r.',
grant, request)
return grant | [
"def",
"create_authorization_code",
"(",
"self",
",",
"request",
")",
":",
"grant",
"=",
"{",
"'code'",
":",
"common",
".",
"generate_token",
"(",
")",
"}",
"if",
"hasattr",
"(",
"request",
",",
"'state'",
")",
"and",
"request",
".",
"state",
":",
"grant... | Generates an authorization grant represented as a dictionary.
:param request: OAuthlib request.
:type request: oauthlib.common.Request | [
"Generates",
"an",
"authorization",
"grant",
"represented",
"as",
"a",
"dictionary",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py#L163-L175 |
243,596 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/grant_types/authorization_code.py | AuthorizationCodeGrant.create_token_response | def create_token_response(self, request, token_handler):
"""Validate the authorization code.
The client MUST NOT use the authorization code more than once. If an
authorization code is used more than once, the authorization server
MUST deny the request and SHOULD revoke (when possible) all tokens
previously issued based on that authorization code. The authorization
code is bound to the client identifier and redirection URI.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:param token_handler: A token handler instance, for example of type
oauthlib.oauth2.BearerToken.
"""
headers = self._get_default_headers()
try:
self.validate_token_request(request)
log.debug('Token request validation ok for %r.', request)
except errors.OAuth2Error as e:
log.debug('Client error during validation of %r. %r.', request, e)
headers.update(e.headers)
return headers, e.json, e.status_code
token = token_handler.create_token(request, refresh_token=self.refresh_token)
for modifier in self._token_modifiers:
token = modifier(token, token_handler, request)
self.request_validator.save_token(token, request)
self.request_validator.invalidate_authorization_code(
request.client_id, request.code, request)
return headers, json.dumps(token), 200 | python | def create_token_response(self, request, token_handler):
headers = self._get_default_headers()
try:
self.validate_token_request(request)
log.debug('Token request validation ok for %r.', request)
except errors.OAuth2Error as e:
log.debug('Client error during validation of %r. %r.', request, e)
headers.update(e.headers)
return headers, e.json, e.status_code
token = token_handler.create_token(request, refresh_token=self.refresh_token)
for modifier in self._token_modifiers:
token = modifier(token, token_handler, request)
self.request_validator.save_token(token, request)
self.request_validator.invalidate_authorization_code(
request.client_id, request.code, request)
return headers, json.dumps(token), 200 | [
"def",
"create_token_response",
"(",
"self",
",",
"request",
",",
"token_handler",
")",
":",
"headers",
"=",
"self",
".",
"_get_default_headers",
"(",
")",
"try",
":",
"self",
".",
"validate_token_request",
"(",
"request",
")",
"log",
".",
"debug",
"(",
"'To... | Validate the authorization code.
The client MUST NOT use the authorization code more than once. If an
authorization code is used more than once, the authorization server
MUST deny the request and SHOULD revoke (when possible) all tokens
previously issued based on that authorization code. The authorization
code is bound to the client identifier and redirection URI.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:param token_handler: A token handler instance, for example of type
oauthlib.oauth2.BearerToken. | [
"Validate",
"the",
"authorization",
"code",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py#L284-L316 |
243,597 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/grant_types/authorization_code.py | AuthorizationCodeGrant.validate_authorization_request | def validate_authorization_request(self, request):
"""Check the authorization request for normal and fatal errors.
A normal error could be a missing response_type parameter or the client
attempting to access scope it is not allowed to ask authorization for.
Normal errors can safely be included in the redirection URI and
sent back to the client.
Fatal errors occur when the client_id or redirect_uri is invalid or
missing. These must be caught by the provider and handled, how this
is done is outside of the scope of OAuthLib but showing an error
page describing the issue is a good idea.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
"""
# First check for fatal errors
# If the request fails due to a missing, invalid, or mismatching
# redirection URI, or if the client identifier is missing or invalid,
# the authorization server SHOULD inform the resource owner of the
# error and MUST NOT automatically redirect the user-agent to the
# invalid redirection URI.
# First check duplicate parameters
for param in ('client_id', 'response_type', 'redirect_uri', 'scope', 'state'):
try:
duplicate_params = request.duplicate_params
except ValueError:
raise errors.InvalidRequestFatalError(description='Unable to parse query string', request=request)
if param in duplicate_params:
raise errors.InvalidRequestFatalError(description='Duplicate %s parameter.' % param, request=request)
# REQUIRED. The client identifier as described in Section 2.2.
# https://tools.ietf.org/html/rfc6749#section-2.2
if not request.client_id:
raise errors.MissingClientIdError(request=request)
if not self.request_validator.validate_client_id(request.client_id, request):
raise errors.InvalidClientIdError(request=request)
# OPTIONAL. As described in Section 3.1.2.
# https://tools.ietf.org/html/rfc6749#section-3.1.2
log.debug('Validating redirection uri %s for client %s.',
request.redirect_uri, request.client_id)
# OPTIONAL. As described in Section 3.1.2.
# https://tools.ietf.org/html/rfc6749#section-3.1.2
self._handle_redirects(request)
# Then check for normal errors.
# If the resource owner denies the access request or if the request
# fails for reasons other than a missing or invalid redirection URI,
# the authorization server informs the client by adding the following
# parameters to the query component of the redirection URI using the
# "application/x-www-form-urlencoded" format, per Appendix B.
# https://tools.ietf.org/html/rfc6749#appendix-B
# Note that the correct parameters to be added are automatically
# populated through the use of specific exceptions.
request_info = {}
for validator in self.custom_validators.pre_auth:
request_info.update(validator(request))
# REQUIRED.
if request.response_type is None:
raise errors.MissingResponseTypeError(request=request)
# Value MUST be set to "code" or one of the OpenID authorization code including
# response_types "code token", "code id_token", "code token id_token"
elif not 'code' in request.response_type and request.response_type != 'none':
raise errors.UnsupportedResponseTypeError(request=request)
if not self.request_validator.validate_response_type(request.client_id,
request.response_type,
request.client, request):
log.debug('Client %s is not authorized to use response_type %s.',
request.client_id, request.response_type)
raise errors.UnauthorizedClientError(request=request)
# OPTIONAL. Validate PKCE request or reply with "error"/"invalid_request"
# https://tools.ietf.org/html/rfc6749#section-4.4.1
if self.request_validator.is_pkce_required(request.client_id, request) is True:
if request.code_challenge is None:
raise errors.MissingCodeChallengeError(request=request)
if request.code_challenge is not None:
# OPTIONAL, defaults to "plain" if not present in the request.
if request.code_challenge_method is None:
request.code_challenge_method = "plain"
if request.code_challenge_method not in self._code_challenge_methods:
raise errors.UnsupportedCodeChallengeMethodError(request=request)
# OPTIONAL. The scope of the access request as described by Section 3.3
# https://tools.ietf.org/html/rfc6749#section-3.3
self.validate_scopes(request)
request_info.update({
'client_id': request.client_id,
'redirect_uri': request.redirect_uri,
'response_type': request.response_type,
'state': request.state,
'request': request
})
for validator in self.custom_validators.post_auth:
request_info.update(validator(request))
return request.scopes, request_info | python | def validate_authorization_request(self, request):
# First check for fatal errors
# If the request fails due to a missing, invalid, or mismatching
# redirection URI, or if the client identifier is missing or invalid,
# the authorization server SHOULD inform the resource owner of the
# error and MUST NOT automatically redirect the user-agent to the
# invalid redirection URI.
# First check duplicate parameters
for param in ('client_id', 'response_type', 'redirect_uri', 'scope', 'state'):
try:
duplicate_params = request.duplicate_params
except ValueError:
raise errors.InvalidRequestFatalError(description='Unable to parse query string', request=request)
if param in duplicate_params:
raise errors.InvalidRequestFatalError(description='Duplicate %s parameter.' % param, request=request)
# REQUIRED. The client identifier as described in Section 2.2.
# https://tools.ietf.org/html/rfc6749#section-2.2
if not request.client_id:
raise errors.MissingClientIdError(request=request)
if not self.request_validator.validate_client_id(request.client_id, request):
raise errors.InvalidClientIdError(request=request)
# OPTIONAL. As described in Section 3.1.2.
# https://tools.ietf.org/html/rfc6749#section-3.1.2
log.debug('Validating redirection uri %s for client %s.',
request.redirect_uri, request.client_id)
# OPTIONAL. As described in Section 3.1.2.
# https://tools.ietf.org/html/rfc6749#section-3.1.2
self._handle_redirects(request)
# Then check for normal errors.
# If the resource owner denies the access request or if the request
# fails for reasons other than a missing or invalid redirection URI,
# the authorization server informs the client by adding the following
# parameters to the query component of the redirection URI using the
# "application/x-www-form-urlencoded" format, per Appendix B.
# https://tools.ietf.org/html/rfc6749#appendix-B
# Note that the correct parameters to be added are automatically
# populated through the use of specific exceptions.
request_info = {}
for validator in self.custom_validators.pre_auth:
request_info.update(validator(request))
# REQUIRED.
if request.response_type is None:
raise errors.MissingResponseTypeError(request=request)
# Value MUST be set to "code" or one of the OpenID authorization code including
# response_types "code token", "code id_token", "code token id_token"
elif not 'code' in request.response_type and request.response_type != 'none':
raise errors.UnsupportedResponseTypeError(request=request)
if not self.request_validator.validate_response_type(request.client_id,
request.response_type,
request.client, request):
log.debug('Client %s is not authorized to use response_type %s.',
request.client_id, request.response_type)
raise errors.UnauthorizedClientError(request=request)
# OPTIONAL. Validate PKCE request or reply with "error"/"invalid_request"
# https://tools.ietf.org/html/rfc6749#section-4.4.1
if self.request_validator.is_pkce_required(request.client_id, request) is True:
if request.code_challenge is None:
raise errors.MissingCodeChallengeError(request=request)
if request.code_challenge is not None:
# OPTIONAL, defaults to "plain" if not present in the request.
if request.code_challenge_method is None:
request.code_challenge_method = "plain"
if request.code_challenge_method not in self._code_challenge_methods:
raise errors.UnsupportedCodeChallengeMethodError(request=request)
# OPTIONAL. The scope of the access request as described by Section 3.3
# https://tools.ietf.org/html/rfc6749#section-3.3
self.validate_scopes(request)
request_info.update({
'client_id': request.client_id,
'redirect_uri': request.redirect_uri,
'response_type': request.response_type,
'state': request.state,
'request': request
})
for validator in self.custom_validators.post_auth:
request_info.update(validator(request))
return request.scopes, request_info | [
"def",
"validate_authorization_request",
"(",
"self",
",",
"request",
")",
":",
"# First check for fatal errors",
"# If the request fails due to a missing, invalid, or mismatching",
"# redirection URI, or if the client identifier is missing or invalid,",
"# the authorization server SHOULD info... | Check the authorization request for normal and fatal errors.
A normal error could be a missing response_type parameter or the client
attempting to access scope it is not allowed to ask authorization for.
Normal errors can safely be included in the redirection URI and
sent back to the client.
Fatal errors occur when the client_id or redirect_uri is invalid or
missing. These must be caught by the provider and handled, how this
is done is outside of the scope of OAuthLib but showing an error
page describing the issue is a good idea.
:param request: OAuthlib request.
:type request: oauthlib.common.Request | [
"Check",
"the",
"authorization",
"request",
"for",
"normal",
"and",
"fatal",
"errors",
"."
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/grant_types/authorization_code.py#L318-L430 |
243,598 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/endpoints/metadata.py | MetadataEndpoint.create_metadata_response | def create_metadata_response(self, uri, http_method='GET', body=None,
headers=None):
"""Create metadata response
"""
headers = {
'Content-Type': 'application/json'
}
return headers, json.dumps(self.claims), 200 | python | def create_metadata_response(self, uri, http_method='GET', body=None,
headers=None):
headers = {
'Content-Type': 'application/json'
}
return headers, json.dumps(self.claims), 200 | [
"def",
"create_metadata_response",
"(",
"self",
",",
"uri",
",",
"http_method",
"=",
"'GET'",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
"return",
"headers",
",",
... | Create metadata response | [
"Create",
"metadata",
"response"
] | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/endpoints/metadata.py#L57-L64 |
243,599 | oauthlib/oauthlib | oauthlib/oauth2/rfc6749/endpoints/metadata.py | MetadataEndpoint.validate_metadata_token | def validate_metadata_token(self, claims, endpoint):
"""
If the token endpoint is used in the grant type, the value of this
parameter MUST be the same as the value of the "grant_type"
parameter passed to the token endpoint defined in the grant type
definition.
"""
self._grant_types.extend(endpoint._grant_types.keys())
claims.setdefault("token_endpoint_auth_methods_supported", ["client_secret_post", "client_secret_basic"])
self.validate_metadata(claims, "token_endpoint_auth_methods_supported", is_list=True)
self.validate_metadata(claims, "token_endpoint_auth_signing_alg_values_supported", is_list=True)
self.validate_metadata(claims, "token_endpoint", is_required=True, is_url=True) | python | def validate_metadata_token(self, claims, endpoint):
self._grant_types.extend(endpoint._grant_types.keys())
claims.setdefault("token_endpoint_auth_methods_supported", ["client_secret_post", "client_secret_basic"])
self.validate_metadata(claims, "token_endpoint_auth_methods_supported", is_list=True)
self.validate_metadata(claims, "token_endpoint_auth_signing_alg_values_supported", is_list=True)
self.validate_metadata(claims, "token_endpoint", is_required=True, is_url=True) | [
"def",
"validate_metadata_token",
"(",
"self",
",",
"claims",
",",
"endpoint",
")",
":",
"self",
".",
"_grant_types",
".",
"extend",
"(",
"endpoint",
".",
"_grant_types",
".",
"keys",
"(",
")",
")",
"claims",
".",
"setdefault",
"(",
"\"token_endpoint_auth_meth... | If the token endpoint is used in the grant type, the value of this
parameter MUST be the same as the value of the "grant_type"
parameter passed to the token endpoint defined in the grant type
definition. | [
"If",
"the",
"token",
"endpoint",
"is",
"used",
"in",
"the",
"grant",
"type",
"the",
"value",
"of",
"this",
"parameter",
"MUST",
"be",
"the",
"same",
"as",
"the",
"value",
"of",
"the",
"grant_type",
"parameter",
"passed",
"to",
"the",
"token",
"endpoint",
... | 30321dd3c0ca784d3508a1970cf90d9f76835c79 | https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth2/rfc6749/endpoints/metadata.py#L91-L103 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.