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
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
18,100
drdoctr/doctr
doctr/travis.py
sync_from_log
def sync_from_log(src, dst, log_file, exclude=()): """ Sync the files in ``src`` to ``dst``. The files that are synced are logged to ``log_file``. If ``log_file`` exists, the files in ``log_file`` are removed first. Returns ``(added, removed)``, where added is a list of all files synced from ``src`` (even if it already existed in ``dst``), and ``removed`` is every file from ``log_file`` that was removed from ``dst`` because it wasn't in ``src``. ``added`` also includes the log file. ``exclude`` may be a list of paths from ``src`` that should be ignored. Such paths are neither added nor removed, even if they are in the logfile. """ from os.path import join, exists, isdir exclude = [os.path.normpath(i) for i in exclude] added, removed = [], [] if not exists(log_file): # Assume this is the first run print("%s doesn't exist. Not removing any files." % log_file) else: with open(log_file) as f: files = f.read().strip().split('\n') for new_f in files: new_f = new_f.strip() if any(is_subdir(new_f, os.path.join(dst, i)) for i in exclude): pass elif exists(new_f): os.remove(new_f) removed.append(new_f) else: print("Warning: File %s doesn't exist." % new_f, file=sys.stderr) if os.path.isdir(src): if not src.endswith(os.sep): src += os.sep files = glob.iglob(join(src, '**'), recursive=True) else: files = [src] src = os.path.dirname(src) + os.sep if os.sep in src else '' os.makedirs(dst, exist_ok=True) # sorted makes this easier to test for f in sorted(files): if any(is_subdir(f, os.path.join(src, i)) for i in exclude): continue new_f = join(dst, f[len(src):]) if isdir(f) or f.endswith(os.sep): os.makedirs(new_f, exist_ok=True) else: shutil.copy2(f, new_f) added.append(new_f) if new_f in removed: removed.remove(new_f) with open(log_file, 'w') as f: f.write('\n'.join(added)) added.append(log_file) return added, removed
python
def sync_from_log(src, dst, log_file, exclude=()): """ Sync the files in ``src`` to ``dst``. The files that are synced are logged to ``log_file``. If ``log_file`` exists, the files in ``log_file`` are removed first. Returns ``(added, removed)``, where added is a list of all files synced from ``src`` (even if it already existed in ``dst``), and ``removed`` is every file from ``log_file`` that was removed from ``dst`` because it wasn't in ``src``. ``added`` also includes the log file. ``exclude`` may be a list of paths from ``src`` that should be ignored. Such paths are neither added nor removed, even if they are in the logfile. """ from os.path import join, exists, isdir exclude = [os.path.normpath(i) for i in exclude] added, removed = [], [] if not exists(log_file): # Assume this is the first run print("%s doesn't exist. Not removing any files." % log_file) else: with open(log_file) as f: files = f.read().strip().split('\n') for new_f in files: new_f = new_f.strip() if any(is_subdir(new_f, os.path.join(dst, i)) for i in exclude): pass elif exists(new_f): os.remove(new_f) removed.append(new_f) else: print("Warning: File %s doesn't exist." % new_f, file=sys.stderr) if os.path.isdir(src): if not src.endswith(os.sep): src += os.sep files = glob.iglob(join(src, '**'), recursive=True) else: files = [src] src = os.path.dirname(src) + os.sep if os.sep in src else '' os.makedirs(dst, exist_ok=True) # sorted makes this easier to test for f in sorted(files): if any(is_subdir(f, os.path.join(src, i)) for i in exclude): continue new_f = join(dst, f[len(src):]) if isdir(f) or f.endswith(os.sep): os.makedirs(new_f, exist_ok=True) else: shutil.copy2(f, new_f) added.append(new_f) if new_f in removed: removed.remove(new_f) with open(log_file, 'w') as f: f.write('\n'.join(added)) added.append(log_file) return added, removed
[ "def", "sync_from_log", "(", "src", ",", "dst", ",", "log_file", ",", "exclude", "=", "(", ")", ")", ":", "from", "os", ".", "path", "import", "join", ",", "exists", ",", "isdir", "exclude", "=", "[", "os", ".", "path", ".", "normpath", "(", "i", ")", "for", "i", "in", "exclude", "]", "added", ",", "removed", "=", "[", "]", ",", "[", "]", "if", "not", "exists", "(", "log_file", ")", ":", "# Assume this is the first run", "print", "(", "\"%s doesn't exist. Not removing any files.\"", "%", "log_file", ")", "else", ":", "with", "open", "(", "log_file", ")", "as", "f", ":", "files", "=", "f", ".", "read", "(", ")", ".", "strip", "(", ")", ".", "split", "(", "'\\n'", ")", "for", "new_f", "in", "files", ":", "new_f", "=", "new_f", ".", "strip", "(", ")", "if", "any", "(", "is_subdir", "(", "new_f", ",", "os", ".", "path", ".", "join", "(", "dst", ",", "i", ")", ")", "for", "i", "in", "exclude", ")", ":", "pass", "elif", "exists", "(", "new_f", ")", ":", "os", ".", "remove", "(", "new_f", ")", "removed", ".", "append", "(", "new_f", ")", "else", ":", "print", "(", "\"Warning: File %s doesn't exist.\"", "%", "new_f", ",", "file", "=", "sys", ".", "stderr", ")", "if", "os", ".", "path", ".", "isdir", "(", "src", ")", ":", "if", "not", "src", ".", "endswith", "(", "os", ".", "sep", ")", ":", "src", "+=", "os", ".", "sep", "files", "=", "glob", ".", "iglob", "(", "join", "(", "src", ",", "'**'", ")", ",", "recursive", "=", "True", ")", "else", ":", "files", "=", "[", "src", "]", "src", "=", "os", ".", "path", ".", "dirname", "(", "src", ")", "+", "os", ".", "sep", "if", "os", ".", "sep", "in", "src", "else", "''", "os", ".", "makedirs", "(", "dst", ",", "exist_ok", "=", "True", ")", "# sorted makes this easier to test", "for", "f", "in", "sorted", "(", "files", ")", ":", "if", "any", "(", "is_subdir", "(", "f", ",", "os", ".", "path", ".", "join", "(", "src", ",", "i", ")", ")", "for", "i", "in", "exclude", ")", ":", "continue", "new_f", "=", "join", "(", "dst", ",", "f", "[", "len", "(", "src", ")", ":", "]", ")", "if", "isdir", "(", "f", ")", "or", "f", ".", "endswith", "(", "os", ".", "sep", ")", ":", "os", ".", "makedirs", "(", "new_f", ",", "exist_ok", "=", "True", ")", "else", ":", "shutil", ".", "copy2", "(", "f", ",", "new_f", ")", "added", ".", "append", "(", "new_f", ")", "if", "new_f", "in", "removed", ":", "removed", ".", "remove", "(", "new_f", ")", "with", "open", "(", "log_file", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "'\\n'", ".", "join", "(", "added", ")", ")", "added", ".", "append", "(", "log_file", ")", "return", "added", ",", "removed" ]
Sync the files in ``src`` to ``dst``. The files that are synced are logged to ``log_file``. If ``log_file`` exists, the files in ``log_file`` are removed first. Returns ``(added, removed)``, where added is a list of all files synced from ``src`` (even if it already existed in ``dst``), and ``removed`` is every file from ``log_file`` that was removed from ``dst`` because it wasn't in ``src``. ``added`` also includes the log file. ``exclude`` may be a list of paths from ``src`` that should be ignored. Such paths are neither added nor removed, even if they are in the logfile.
[ "Sync", "the", "files", "in", "src", "to", "dst", "." ]
0f19ff78c8239efcc98d417f36b0a31d9be01ba5
https://github.com/drdoctr/doctr/blob/0f19ff78c8239efcc98d417f36b0a31d9be01ba5/doctr/travis.py#L410-L477
18,101
drdoctr/doctr
doctr/travis.py
push_docs
def push_docs(deploy_branch='gh-pages', retries=5): """ Push the changes to the branch named ``deploy_branch``. Assumes that :func:`setup_GitHub_push` has been run and returned True, and that :func:`commit_docs` has been run. Does not push anything if no changes were made. """ code = 1 while code and retries: print("Pulling") code = run(['git', 'pull', '-s', 'recursive', '-X', 'ours', 'doctr_remote', deploy_branch], exit=False) print("Pushing commit") code = run(['git', 'push', '-q', 'doctr_remote', '{}:{}'.format(DOCTR_WORKING_BRANCH, deploy_branch)], exit=False) if code: retries -= 1 print("Push failed, retrying") time.sleep(1) else: return sys.exit("Giving up...")
python
def push_docs(deploy_branch='gh-pages', retries=5): """ Push the changes to the branch named ``deploy_branch``. Assumes that :func:`setup_GitHub_push` has been run and returned True, and that :func:`commit_docs` has been run. Does not push anything if no changes were made. """ code = 1 while code and retries: print("Pulling") code = run(['git', 'pull', '-s', 'recursive', '-X', 'ours', 'doctr_remote', deploy_branch], exit=False) print("Pushing commit") code = run(['git', 'push', '-q', 'doctr_remote', '{}:{}'.format(DOCTR_WORKING_BRANCH, deploy_branch)], exit=False) if code: retries -= 1 print("Push failed, retrying") time.sleep(1) else: return sys.exit("Giving up...")
[ "def", "push_docs", "(", "deploy_branch", "=", "'gh-pages'", ",", "retries", "=", "5", ")", ":", "code", "=", "1", "while", "code", "and", "retries", ":", "print", "(", "\"Pulling\"", ")", "code", "=", "run", "(", "[", "'git'", ",", "'pull'", ",", "'-s'", ",", "'recursive'", ",", "'-X'", ",", "'ours'", ",", "'doctr_remote'", ",", "deploy_branch", "]", ",", "exit", "=", "False", ")", "print", "(", "\"Pushing commit\"", ")", "code", "=", "run", "(", "[", "'git'", ",", "'push'", ",", "'-q'", ",", "'doctr_remote'", ",", "'{}:{}'", ".", "format", "(", "DOCTR_WORKING_BRANCH", ",", "deploy_branch", ")", "]", ",", "exit", "=", "False", ")", "if", "code", ":", "retries", "-=", "1", "print", "(", "\"Push failed, retrying\"", ")", "time", ".", "sleep", "(", "1", ")", "else", ":", "return", "sys", ".", "exit", "(", "\"Giving up...\"", ")" ]
Push the changes to the branch named ``deploy_branch``. Assumes that :func:`setup_GitHub_push` has been run and returned True, and that :func:`commit_docs` has been run. Does not push anything if no changes were made.
[ "Push", "the", "changes", "to", "the", "branch", "named", "deploy_branch", "." ]
0f19ff78c8239efcc98d417f36b0a31d9be01ba5
https://github.com/drdoctr/doctr/blob/0f19ff78c8239efcc98d417f36b0a31d9be01ba5/doctr/travis.py#L536-L560
18,102
licenses/lice
lice/core.py
clean_path
def clean_path(p): """ Clean a path by expanding user and environment variables and ensuring absolute path. """ p = os.path.expanduser(p) p = os.path.expandvars(p) p = os.path.abspath(p) return p
python
def clean_path(p): """ Clean a path by expanding user and environment variables and ensuring absolute path. """ p = os.path.expanduser(p) p = os.path.expandvars(p) p = os.path.abspath(p) return p
[ "def", "clean_path", "(", "p", ")", ":", "p", "=", "os", ".", "path", ".", "expanduser", "(", "p", ")", "p", "=", "os", ".", "path", ".", "expandvars", "(", "p", ")", "p", "=", "os", ".", "path", ".", "abspath", "(", "p", ")", "return", "p" ]
Clean a path by expanding user and environment variables and ensuring absolute path.
[ "Clean", "a", "path", "by", "expanding", "user", "and", "environment", "variables", "and", "ensuring", "absolute", "path", "." ]
71635c2544d5edf9e93af4141467763916a86624
https://github.com/licenses/lice/blob/71635c2544d5edf9e93af4141467763916a86624/lice/core.py#L93-L100
18,103
licenses/lice
lice/core.py
load_file_template
def load_file_template(path): """ Load template from the specified filesystem path. """ template = StringIO() if not os.path.exists(path): raise ValueError("path does not exist: %s" % path) with open(clean_path(path), "rb") as infile: # opened as binary for line in infile: template.write(line.decode("utf-8")) # ensure utf-8 return template
python
def load_file_template(path): """ Load template from the specified filesystem path. """ template = StringIO() if not os.path.exists(path): raise ValueError("path does not exist: %s" % path) with open(clean_path(path), "rb") as infile: # opened as binary for line in infile: template.write(line.decode("utf-8")) # ensure utf-8 return template
[ "def", "load_file_template", "(", "path", ")", ":", "template", "=", "StringIO", "(", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "ValueError", "(", "\"path does not exist: %s\"", "%", "path", ")", "with", "open", "(", "clean_path", "(", "path", ")", ",", "\"rb\"", ")", "as", "infile", ":", "# opened as binary", "for", "line", "in", "infile", ":", "template", ".", "write", "(", "line", ".", "decode", "(", "\"utf-8\"", ")", ")", "# ensure utf-8", "return", "template" ]
Load template from the specified filesystem path.
[ "Load", "template", "from", "the", "specified", "filesystem", "path", "." ]
71635c2544d5edf9e93af4141467763916a86624
https://github.com/licenses/lice/blob/71635c2544d5edf9e93af4141467763916a86624/lice/core.py#L126-L135
18,104
licenses/lice
lice/core.py
load_package_template
def load_package_template(license, header=False): """ Load license template distributed with package. """ content = StringIO() filename = 'template-%s-header.txt' if header else 'template-%s.txt' with resource_stream(__name__, filename % license) as licfile: for line in licfile: content.write(line.decode("utf-8")) # write utf-8 string return content
python
def load_package_template(license, header=False): """ Load license template distributed with package. """ content = StringIO() filename = 'template-%s-header.txt' if header else 'template-%s.txt' with resource_stream(__name__, filename % license) as licfile: for line in licfile: content.write(line.decode("utf-8")) # write utf-8 string return content
[ "def", "load_package_template", "(", "license", ",", "header", "=", "False", ")", ":", "content", "=", "StringIO", "(", ")", "filename", "=", "'template-%s-header.txt'", "if", "header", "else", "'template-%s.txt'", "with", "resource_stream", "(", "__name__", ",", "filename", "%", "license", ")", "as", "licfile", ":", "for", "line", "in", "licfile", ":", "content", ".", "write", "(", "line", ".", "decode", "(", "\"utf-8\"", ")", ")", "# write utf-8 string", "return", "content" ]
Load license template distributed with package.
[ "Load", "license", "template", "distributed", "with", "package", "." ]
71635c2544d5edf9e93af4141467763916a86624
https://github.com/licenses/lice/blob/71635c2544d5edf9e93af4141467763916a86624/lice/core.py#L138-L146
18,105
licenses/lice
lice/core.py
extract_vars
def extract_vars(template): """ Extract variables from template. Variables are enclosed in double curly braces. """ keys = set() for match in re.finditer(r"\{\{ (?P<key>\w+) \}\}", template.getvalue()): keys.add(match.groups()[0]) return sorted(list(keys))
python
def extract_vars(template): """ Extract variables from template. Variables are enclosed in double curly braces. """ keys = set() for match in re.finditer(r"\{\{ (?P<key>\w+) \}\}", template.getvalue()): keys.add(match.groups()[0]) return sorted(list(keys))
[ "def", "extract_vars", "(", "template", ")", ":", "keys", "=", "set", "(", ")", "for", "match", "in", "re", ".", "finditer", "(", "r\"\\{\\{ (?P<key>\\w+) \\}\\}\"", ",", "template", ".", "getvalue", "(", ")", ")", ":", "keys", ".", "add", "(", "match", ".", "groups", "(", ")", "[", "0", "]", ")", "return", "sorted", "(", "list", "(", "keys", ")", ")" ]
Extract variables from template. Variables are enclosed in double curly braces.
[ "Extract", "variables", "from", "template", ".", "Variables", "are", "enclosed", "in", "double", "curly", "braces", "." ]
71635c2544d5edf9e93af4141467763916a86624
https://github.com/licenses/lice/blob/71635c2544d5edf9e93af4141467763916a86624/lice/core.py#L149-L156
18,106
licenses/lice
lice/core.py
generate_license
def generate_license(template, context): """ Generate a license by extracting variables from the template and replacing them with the corresponding values in the given context. """ out = StringIO() content = template.getvalue() for key in extract_vars(template): if key not in context: raise ValueError("%s is missing from the template context" % key) content = content.replace("{{ %s }}" % key, context[key]) template.close() # free template memory (when is garbage collected?) out.write(content) return out
python
def generate_license(template, context): """ Generate a license by extracting variables from the template and replacing them with the corresponding values in the given context. """ out = StringIO() content = template.getvalue() for key in extract_vars(template): if key not in context: raise ValueError("%s is missing from the template context" % key) content = content.replace("{{ %s }}" % key, context[key]) template.close() # free template memory (when is garbage collected?) out.write(content) return out
[ "def", "generate_license", "(", "template", ",", "context", ")", ":", "out", "=", "StringIO", "(", ")", "content", "=", "template", ".", "getvalue", "(", ")", "for", "key", "in", "extract_vars", "(", "template", ")", ":", "if", "key", "not", "in", "context", ":", "raise", "ValueError", "(", "\"%s is missing from the template context\"", "%", "key", ")", "content", "=", "content", ".", "replace", "(", "\"{{ %s }}\"", "%", "key", ",", "context", "[", "key", "]", ")", "template", ".", "close", "(", ")", "# free template memory (when is garbage collected?)", "out", ".", "write", "(", "content", ")", "return", "out" ]
Generate a license by extracting variables from the template and replacing them with the corresponding values in the given context.
[ "Generate", "a", "license", "by", "extracting", "variables", "from", "the", "template", "and", "replacing", "them", "with", "the", "corresponding", "values", "in", "the", "given", "context", "." ]
71635c2544d5edf9e93af4141467763916a86624
https://github.com/licenses/lice/blob/71635c2544d5edf9e93af4141467763916a86624/lice/core.py#L159-L171
18,107
licenses/lice
lice/core.py
get_suffix
def get_suffix(name): """Check if file name have valid suffix for formatting. if have suffix return it else return False. """ a = name.count(".") if a: ext = name.split(".")[-1] if ext in LANGS.keys(): return ext return False else: return False
python
def get_suffix(name): """Check if file name have valid suffix for formatting. if have suffix return it else return False. """ a = name.count(".") if a: ext = name.split(".")[-1] if ext in LANGS.keys(): return ext return False else: return False
[ "def", "get_suffix", "(", "name", ")", ":", "a", "=", "name", ".", "count", "(", "\".\"", ")", "if", "a", ":", "ext", "=", "name", ".", "split", "(", "\".\"", ")", "[", "-", "1", "]", "if", "ext", "in", "LANGS", ".", "keys", "(", ")", ":", "return", "ext", "return", "False", "else", ":", "return", "False" ]
Check if file name have valid suffix for formatting. if have suffix return it else return False.
[ "Check", "if", "file", "name", "have", "valid", "suffix", "for", "formatting", ".", "if", "have", "suffix", "return", "it", "else", "return", "False", "." ]
71635c2544d5edf9e93af4141467763916a86624
https://github.com/licenses/lice/blob/71635c2544d5edf9e93af4141467763916a86624/lice/core.py#L191-L202
18,108
crate/crate-python
src/crate/client/http.py
_raise_for_status
def _raise_for_status(response): """ make sure that only crate.exceptions are raised that are defined in the DB-API specification """ message = '' if 400 <= response.status < 500: message = '%s Client Error: %s' % (response.status, response.reason) elif 500 <= response.status < 600: message = '%s Server Error: %s' % (response.status, response.reason) else: return if response.status == 503: raise ConnectionError(message) if response.headers.get("content-type", "").startswith("application/json"): data = json.loads(response.data.decode('utf-8')) error = data.get('error', {}) error_trace = data.get('error_trace', None) if "results" in data: errors = [res["error_message"] for res in data["results"] if res.get("error_message")] if errors: raise ProgrammingError("\n".join(errors)) if isinstance(error, dict): raise ProgrammingError(error.get('message', ''), error_trace=error_trace) raise ProgrammingError(error, error_trace=error_trace) raise ProgrammingError(message)
python
def _raise_for_status(response): """ make sure that only crate.exceptions are raised that are defined in the DB-API specification """ message = '' if 400 <= response.status < 500: message = '%s Client Error: %s' % (response.status, response.reason) elif 500 <= response.status < 600: message = '%s Server Error: %s' % (response.status, response.reason) else: return if response.status == 503: raise ConnectionError(message) if response.headers.get("content-type", "").startswith("application/json"): data = json.loads(response.data.decode('utf-8')) error = data.get('error', {}) error_trace = data.get('error_trace', None) if "results" in data: errors = [res["error_message"] for res in data["results"] if res.get("error_message")] if errors: raise ProgrammingError("\n".join(errors)) if isinstance(error, dict): raise ProgrammingError(error.get('message', ''), error_trace=error_trace) raise ProgrammingError(error, error_trace=error_trace) raise ProgrammingError(message)
[ "def", "_raise_for_status", "(", "response", ")", ":", "message", "=", "''", "if", "400", "<=", "response", ".", "status", "<", "500", ":", "message", "=", "'%s Client Error: %s'", "%", "(", "response", ".", "status", ",", "response", ".", "reason", ")", "elif", "500", "<=", "response", ".", "status", "<", "600", ":", "message", "=", "'%s Server Error: %s'", "%", "(", "response", ".", "status", ",", "response", ".", "reason", ")", "else", ":", "return", "if", "response", ".", "status", "==", "503", ":", "raise", "ConnectionError", "(", "message", ")", "if", "response", ".", "headers", ".", "get", "(", "\"content-type\"", ",", "\"\"", ")", ".", "startswith", "(", "\"application/json\"", ")", ":", "data", "=", "json", ".", "loads", "(", "response", ".", "data", ".", "decode", "(", "'utf-8'", ")", ")", "error", "=", "data", ".", "get", "(", "'error'", ",", "{", "}", ")", "error_trace", "=", "data", ".", "get", "(", "'error_trace'", ",", "None", ")", "if", "\"results\"", "in", "data", ":", "errors", "=", "[", "res", "[", "\"error_message\"", "]", "for", "res", "in", "data", "[", "\"results\"", "]", "if", "res", ".", "get", "(", "\"error_message\"", ")", "]", "if", "errors", ":", "raise", "ProgrammingError", "(", "\"\\n\"", ".", "join", "(", "errors", ")", ")", "if", "isinstance", "(", "error", ",", "dict", ")", ":", "raise", "ProgrammingError", "(", "error", ".", "get", "(", "'message'", ",", "''", ")", ",", "error_trace", "=", "error_trace", ")", "raise", "ProgrammingError", "(", "error", ",", "error_trace", "=", "error_trace", ")", "raise", "ProgrammingError", "(", "message", ")" ]
make sure that only crate.exceptions are raised that are defined in the DB-API specification
[ "make", "sure", "that", "only", "crate", ".", "exceptions", "are", "raised", "that", "are", "defined", "in", "the", "DB", "-", "API", "specification" ]
68e39c95f5bbe88b74bbfa26de4347fc644636a8
https://github.com/crate/crate-python/blob/68e39c95f5bbe88b74bbfa26de4347fc644636a8/src/crate/client/http.py#L164-L189
18,109
crate/crate-python
src/crate/client/http.py
_server_url
def _server_url(server): """ Normalizes a given server string to an url >>> print(_server_url('a')) http://a >>> print(_server_url('a:9345')) http://a:9345 >>> print(_server_url('https://a:9345')) https://a:9345 >>> print(_server_url('https://a')) https://a >>> print(_server_url('demo.crate.io')) http://demo.crate.io """ if not _HTTP_PAT.match(server): server = 'http://%s' % server parsed = urlparse(server) url = '%s://%s' % (parsed.scheme, parsed.netloc) return url
python
def _server_url(server): """ Normalizes a given server string to an url >>> print(_server_url('a')) http://a >>> print(_server_url('a:9345')) http://a:9345 >>> print(_server_url('https://a:9345')) https://a:9345 >>> print(_server_url('https://a')) https://a >>> print(_server_url('demo.crate.io')) http://demo.crate.io """ if not _HTTP_PAT.match(server): server = 'http://%s' % server parsed = urlparse(server) url = '%s://%s' % (parsed.scheme, parsed.netloc) return url
[ "def", "_server_url", "(", "server", ")", ":", "if", "not", "_HTTP_PAT", ".", "match", "(", "server", ")", ":", "server", "=", "'http://%s'", "%", "server", "parsed", "=", "urlparse", "(", "server", ")", "url", "=", "'%s://%s'", "%", "(", "parsed", ".", "scheme", ",", "parsed", ".", "netloc", ")", "return", "url" ]
Normalizes a given server string to an url >>> print(_server_url('a')) http://a >>> print(_server_url('a:9345')) http://a:9345 >>> print(_server_url('https://a:9345')) https://a:9345 >>> print(_server_url('https://a')) https://a >>> print(_server_url('demo.crate.io')) http://demo.crate.io
[ "Normalizes", "a", "given", "server", "string", "to", "an", "url" ]
68e39c95f5bbe88b74bbfa26de4347fc644636a8
https://github.com/crate/crate-python/blob/68e39c95f5bbe88b74bbfa26de4347fc644636a8/src/crate/client/http.py#L192-L211
18,110
crate/crate-python
src/crate/client/http.py
Client.sql
def sql(self, stmt, parameters=None, bulk_parameters=None): """ Execute SQL stmt against the crate server. """ if stmt is None: return None data = _create_sql_payload(stmt, parameters, bulk_parameters) logger.debug( 'Sending request to %s with payload: %s', self.path, data) content = self._json_request('POST', self.path, data=data) logger.debug("JSON response for stmt(%s): %s", stmt, content) return content
python
def sql(self, stmt, parameters=None, bulk_parameters=None): """ Execute SQL stmt against the crate server. """ if stmt is None: return None data = _create_sql_payload(stmt, parameters, bulk_parameters) logger.debug( 'Sending request to %s with payload: %s', self.path, data) content = self._json_request('POST', self.path, data=data) logger.debug("JSON response for stmt(%s): %s", stmt, content) return content
[ "def", "sql", "(", "self", ",", "stmt", ",", "parameters", "=", "None", ",", "bulk_parameters", "=", "None", ")", ":", "if", "stmt", "is", "None", ":", "return", "None", "data", "=", "_create_sql_payload", "(", "stmt", ",", "parameters", ",", "bulk_parameters", ")", "logger", ".", "debug", "(", "'Sending request to %s with payload: %s'", ",", "self", ".", "path", ",", "data", ")", "content", "=", "self", ".", "_json_request", "(", "'POST'", ",", "self", ".", "path", ",", "data", "=", "data", ")", "logger", ".", "debug", "(", "\"JSON response for stmt(%s): %s\"", ",", "stmt", ",", "content", ")", "return", "content" ]
Execute SQL stmt against the crate server.
[ "Execute", "SQL", "stmt", "against", "the", "crate", "server", "." ]
68e39c95f5bbe88b74bbfa26de4347fc644636a8
https://github.com/crate/crate-python/blob/68e39c95f5bbe88b74bbfa26de4347fc644636a8/src/crate/client/http.py#L318-L331
18,111
crate/crate-python
src/crate/client/http.py
Client.blob_put
def blob_put(self, table, digest, data): """ Stores the contents of the file like @data object in a blob under the given table and digest. """ response = self._request('PUT', _blob_path(table, digest), data=data) if response.status == 201: # blob created return True if response.status == 409: # blob exists return False if response.status in (400, 404): raise BlobLocationNotFoundException(table, digest) _raise_for_status(response)
python
def blob_put(self, table, digest, data): """ Stores the contents of the file like @data object in a blob under the given table and digest. """ response = self._request('PUT', _blob_path(table, digest), data=data) if response.status == 201: # blob created return True if response.status == 409: # blob exists return False if response.status in (400, 404): raise BlobLocationNotFoundException(table, digest) _raise_for_status(response)
[ "def", "blob_put", "(", "self", ",", "table", ",", "digest", ",", "data", ")", ":", "response", "=", "self", ".", "_request", "(", "'PUT'", ",", "_blob_path", "(", "table", ",", "digest", ")", ",", "data", "=", "data", ")", "if", "response", ".", "status", "==", "201", ":", "# blob created", "return", "True", "if", "response", ".", "status", "==", "409", ":", "# blob exists", "return", "False", "if", "response", ".", "status", "in", "(", "400", ",", "404", ")", ":", "raise", "BlobLocationNotFoundException", "(", "table", ",", "digest", ")", "_raise_for_status", "(", "response", ")" ]
Stores the contents of the file like @data object in a blob under the given table and digest.
[ "Stores", "the", "contents", "of", "the", "file", "like" ]
68e39c95f5bbe88b74bbfa26de4347fc644636a8
https://github.com/crate/crate-python/blob/68e39c95f5bbe88b74bbfa26de4347fc644636a8/src/crate/client/http.py#L341-L356
18,112
crate/crate-python
src/crate/client/http.py
Client.blob_get
def blob_get(self, table, digest, chunk_size=1024 * 128): """ Returns a file like object representing the contents of the blob with the given digest. """ response = self._request('GET', _blob_path(table, digest), stream=True) if response.status == 404: raise DigestNotFoundException(table, digest) _raise_for_status(response) return response.stream(amt=chunk_size)
python
def blob_get(self, table, digest, chunk_size=1024 * 128): """ Returns a file like object representing the contents of the blob with the given digest. """ response = self._request('GET', _blob_path(table, digest), stream=True) if response.status == 404: raise DigestNotFoundException(table, digest) _raise_for_status(response) return response.stream(amt=chunk_size)
[ "def", "blob_get", "(", "self", ",", "table", ",", "digest", ",", "chunk_size", "=", "1024", "*", "128", ")", ":", "response", "=", "self", ".", "_request", "(", "'GET'", ",", "_blob_path", "(", "table", ",", "digest", ")", ",", "stream", "=", "True", ")", "if", "response", ".", "status", "==", "404", ":", "raise", "DigestNotFoundException", "(", "table", ",", "digest", ")", "_raise_for_status", "(", "response", ")", "return", "response", ".", "stream", "(", "amt", "=", "chunk_size", ")" ]
Returns a file like object representing the contents of the blob with the given digest.
[ "Returns", "a", "file", "like", "object", "representing", "the", "contents", "of", "the", "blob", "with", "the", "given", "digest", "." ]
68e39c95f5bbe88b74bbfa26de4347fc644636a8
https://github.com/crate/crate-python/blob/68e39c95f5bbe88b74bbfa26de4347fc644636a8/src/crate/client/http.py#L369-L378
18,113
crate/crate-python
src/crate/client/http.py
Client.blob_exists
def blob_exists(self, table, digest): """ Returns true if the blob with the given digest exists under the given table. """ response = self._request('HEAD', _blob_path(table, digest)) if response.status == 200: return True elif response.status == 404: return False _raise_for_status(response)
python
def blob_exists(self, table, digest): """ Returns true if the blob with the given digest exists under the given table. """ response = self._request('HEAD', _blob_path(table, digest)) if response.status == 200: return True elif response.status == 404: return False _raise_for_status(response)
[ "def", "blob_exists", "(", "self", ",", "table", ",", "digest", ")", ":", "response", "=", "self", ".", "_request", "(", "'HEAD'", ",", "_blob_path", "(", "table", ",", "digest", ")", ")", "if", "response", ".", "status", "==", "200", ":", "return", "True", "elif", "response", ".", "status", "==", "404", ":", "return", "False", "_raise_for_status", "(", "response", ")" ]
Returns true if the blob with the given digest exists under the given table.
[ "Returns", "true", "if", "the", "blob", "with", "the", "given", "digest", "exists", "under", "the", "given", "table", "." ]
68e39c95f5bbe88b74bbfa26de4347fc644636a8
https://github.com/crate/crate-python/blob/68e39c95f5bbe88b74bbfa26de4347fc644636a8/src/crate/client/http.py#L380-L390
18,114
crate/crate-python
src/crate/client/http.py
Client._request
def _request(self, method, path, server=None, **kwargs): """Execute a request to the cluster A server is selected from the server pool. """ while True: next_server = server or self._get_server() try: response = self.server_pool[next_server].request( method, path, username=self.username, password=self.password, schema=self.schema, **kwargs) redirect_location = response.get_redirect_location() if redirect_location and 300 <= response.status <= 308: redirect_server = _server_url(redirect_location) self._add_server(redirect_server) return self._request( method, path, server=redirect_server, **kwargs) if not server and response.status in SRV_UNAVAILABLE_STATUSES: with self._lock: # drop server from active ones self._drop_server(next_server, response.reason) else: return response except (urllib3.exceptions.MaxRetryError, urllib3.exceptions.ReadTimeoutError, urllib3.exceptions.SSLError, urllib3.exceptions.HTTPError, urllib3.exceptions.ProxyError,) as ex: ex_message = _ex_to_message(ex) if server: raise ConnectionError( "Server not available, exception: %s" % ex_message ) preserve_server = False if isinstance(ex, urllib3.exceptions.ProtocolError): preserve_server = any( t in [type(arg) for arg in ex.args] for t in PRESERVE_ACTIVE_SERVER_EXCEPTIONS ) if (not preserve_server): with self._lock: # drop server from active ones self._drop_server(next_server, ex_message) except Exception as e: raise ProgrammingError(_ex_to_message(e))
python
def _request(self, method, path, server=None, **kwargs): """Execute a request to the cluster A server is selected from the server pool. """ while True: next_server = server or self._get_server() try: response = self.server_pool[next_server].request( method, path, username=self.username, password=self.password, schema=self.schema, **kwargs) redirect_location = response.get_redirect_location() if redirect_location and 300 <= response.status <= 308: redirect_server = _server_url(redirect_location) self._add_server(redirect_server) return self._request( method, path, server=redirect_server, **kwargs) if not server and response.status in SRV_UNAVAILABLE_STATUSES: with self._lock: # drop server from active ones self._drop_server(next_server, response.reason) else: return response except (urllib3.exceptions.MaxRetryError, urllib3.exceptions.ReadTimeoutError, urllib3.exceptions.SSLError, urllib3.exceptions.HTTPError, urllib3.exceptions.ProxyError,) as ex: ex_message = _ex_to_message(ex) if server: raise ConnectionError( "Server not available, exception: %s" % ex_message ) preserve_server = False if isinstance(ex, urllib3.exceptions.ProtocolError): preserve_server = any( t in [type(arg) for arg in ex.args] for t in PRESERVE_ACTIVE_SERVER_EXCEPTIONS ) if (not preserve_server): with self._lock: # drop server from active ones self._drop_server(next_server, ex_message) except Exception as e: raise ProgrammingError(_ex_to_message(e))
[ "def", "_request", "(", "self", ",", "method", ",", "path", ",", "server", "=", "None", ",", "*", "*", "kwargs", ")", ":", "while", "True", ":", "next_server", "=", "server", "or", "self", ".", "_get_server", "(", ")", "try", ":", "response", "=", "self", ".", "server_pool", "[", "next_server", "]", ".", "request", "(", "method", ",", "path", ",", "username", "=", "self", ".", "username", ",", "password", "=", "self", ".", "password", ",", "schema", "=", "self", ".", "schema", ",", "*", "*", "kwargs", ")", "redirect_location", "=", "response", ".", "get_redirect_location", "(", ")", "if", "redirect_location", "and", "300", "<=", "response", ".", "status", "<=", "308", ":", "redirect_server", "=", "_server_url", "(", "redirect_location", ")", "self", ".", "_add_server", "(", "redirect_server", ")", "return", "self", ".", "_request", "(", "method", ",", "path", ",", "server", "=", "redirect_server", ",", "*", "*", "kwargs", ")", "if", "not", "server", "and", "response", ".", "status", "in", "SRV_UNAVAILABLE_STATUSES", ":", "with", "self", ".", "_lock", ":", "# drop server from active ones", "self", ".", "_drop_server", "(", "next_server", ",", "response", ".", "reason", ")", "else", ":", "return", "response", "except", "(", "urllib3", ".", "exceptions", ".", "MaxRetryError", ",", "urllib3", ".", "exceptions", ".", "ReadTimeoutError", ",", "urllib3", ".", "exceptions", ".", "SSLError", ",", "urllib3", ".", "exceptions", ".", "HTTPError", ",", "urllib3", ".", "exceptions", ".", "ProxyError", ",", ")", "as", "ex", ":", "ex_message", "=", "_ex_to_message", "(", "ex", ")", "if", "server", ":", "raise", "ConnectionError", "(", "\"Server not available, exception: %s\"", "%", "ex_message", ")", "preserve_server", "=", "False", "if", "isinstance", "(", "ex", ",", "urllib3", ".", "exceptions", ".", "ProtocolError", ")", ":", "preserve_server", "=", "any", "(", "t", "in", "[", "type", "(", "arg", ")", "for", "arg", "in", "ex", ".", "args", "]", "for", "t", "in", "PRESERVE_ACTIVE_SERVER_EXCEPTIONS", ")", "if", "(", "not", "preserve_server", ")", ":", "with", "self", ".", "_lock", ":", "# drop server from active ones", "self", ".", "_drop_server", "(", "next_server", ",", "ex_message", ")", "except", "Exception", "as", "e", ":", "raise", "ProgrammingError", "(", "_ex_to_message", "(", "e", ")", ")" ]
Execute a request to the cluster A server is selected from the server pool.
[ "Execute", "a", "request", "to", "the", "cluster" ]
68e39c95f5bbe88b74bbfa26de4347fc644636a8
https://github.com/crate/crate-python/blob/68e39c95f5bbe88b74bbfa26de4347fc644636a8/src/crate/client/http.py#L397-L440
18,115
crate/crate-python
src/crate/client/http.py
Client._json_request
def _json_request(self, method, path, data): """ Issue request against the crate HTTP API. """ response = self._request(method, path, data=data) _raise_for_status(response) if len(response.data) > 0: return _json_from_response(response) return response.data
python
def _json_request(self, method, path, data): """ Issue request against the crate HTTP API. """ response = self._request(method, path, data=data) _raise_for_status(response) if len(response.data) > 0: return _json_from_response(response) return response.data
[ "def", "_json_request", "(", "self", ",", "method", ",", "path", ",", "data", ")", ":", "response", "=", "self", ".", "_request", "(", "method", ",", "path", ",", "data", "=", "data", ")", "_raise_for_status", "(", "response", ")", "if", "len", "(", "response", ".", "data", ")", ">", "0", ":", "return", "_json_from_response", "(", "response", ")", "return", "response", ".", "data" ]
Issue request against the crate HTTP API.
[ "Issue", "request", "against", "the", "crate", "HTTP", "API", "." ]
68e39c95f5bbe88b74bbfa26de4347fc644636a8
https://github.com/crate/crate-python/blob/68e39c95f5bbe88b74bbfa26de4347fc644636a8/src/crate/client/http.py#L442-L451
18,116
crate/crate-python
src/crate/client/http.py
Client._get_server
def _get_server(self): """ Get server to use for request. Also process inactive server list, re-add them after given interval. """ with self._lock: inactive_server_count = len(self._inactive_servers) for i in range(inactive_server_count): try: ts, server, message = heapq.heappop(self._inactive_servers) except IndexError: pass else: if (ts + self.retry_interval) > time(): # Not yet, put it back heapq.heappush(self._inactive_servers, (ts, server, message)) else: self._active_servers.append(server) logger.warn("Restored server %s into active pool", server) # if none is old enough, use oldest if not self._active_servers: ts, server, message = heapq.heappop(self._inactive_servers) self._active_servers.append(server) logger.info("Restored server %s into active pool", server) server = self._active_servers[0] self._roundrobin() return server
python
def _get_server(self): """ Get server to use for request. Also process inactive server list, re-add them after given interval. """ with self._lock: inactive_server_count = len(self._inactive_servers) for i in range(inactive_server_count): try: ts, server, message = heapq.heappop(self._inactive_servers) except IndexError: pass else: if (ts + self.retry_interval) > time(): # Not yet, put it back heapq.heappush(self._inactive_servers, (ts, server, message)) else: self._active_servers.append(server) logger.warn("Restored server %s into active pool", server) # if none is old enough, use oldest if not self._active_servers: ts, server, message = heapq.heappop(self._inactive_servers) self._active_servers.append(server) logger.info("Restored server %s into active pool", server) server = self._active_servers[0] self._roundrobin() return server
[ "def", "_get_server", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "inactive_server_count", "=", "len", "(", "self", ".", "_inactive_servers", ")", "for", "i", "in", "range", "(", "inactive_server_count", ")", ":", "try", ":", "ts", ",", "server", ",", "message", "=", "heapq", ".", "heappop", "(", "self", ".", "_inactive_servers", ")", "except", "IndexError", ":", "pass", "else", ":", "if", "(", "ts", "+", "self", ".", "retry_interval", ")", ">", "time", "(", ")", ":", "# Not yet, put it back", "heapq", ".", "heappush", "(", "self", ".", "_inactive_servers", ",", "(", "ts", ",", "server", ",", "message", ")", ")", "else", ":", "self", ".", "_active_servers", ".", "append", "(", "server", ")", "logger", ".", "warn", "(", "\"Restored server %s into active pool\"", ",", "server", ")", "# if none is old enough, use oldest", "if", "not", "self", ".", "_active_servers", ":", "ts", ",", "server", ",", "message", "=", "heapq", ".", "heappop", "(", "self", ".", "_inactive_servers", ")", "self", ".", "_active_servers", ".", "append", "(", "server", ")", "logger", ".", "info", "(", "\"Restored server %s into active pool\"", ",", "server", ")", "server", "=", "self", ".", "_active_servers", "[", "0", "]", "self", ".", "_roundrobin", "(", ")", "return", "server" ]
Get server to use for request. Also process inactive server list, re-add them after given interval.
[ "Get", "server", "to", "use", "for", "request", ".", "Also", "process", "inactive", "server", "list", "re", "-", "add", "them", "after", "given", "interval", "." ]
68e39c95f5bbe88b74bbfa26de4347fc644636a8
https://github.com/crate/crate-python/blob/68e39c95f5bbe88b74bbfa26de4347fc644636a8/src/crate/client/http.py#L453-L484
18,117
crate/crate-python
src/crate/client/http.py
Client._drop_server
def _drop_server(self, server, message): """ Drop server from active list and adds it to the inactive ones. """ try: self._active_servers.remove(server) except ValueError: pass else: heapq.heappush(self._inactive_servers, (time(), server, message)) logger.warning("Removed server %s from active pool", server) # if this is the last server raise exception, otherwise try next if not self._active_servers: raise ConnectionError( ("No more Servers available, " "exception from last server: %s") % message)
python
def _drop_server(self, server, message): """ Drop server from active list and adds it to the inactive ones. """ try: self._active_servers.remove(server) except ValueError: pass else: heapq.heappush(self._inactive_servers, (time(), server, message)) logger.warning("Removed server %s from active pool", server) # if this is the last server raise exception, otherwise try next if not self._active_servers: raise ConnectionError( ("No more Servers available, " "exception from last server: %s") % message)
[ "def", "_drop_server", "(", "self", ",", "server", ",", "message", ")", ":", "try", ":", "self", ".", "_active_servers", ".", "remove", "(", "server", ")", "except", "ValueError", ":", "pass", "else", ":", "heapq", ".", "heappush", "(", "self", ".", "_inactive_servers", ",", "(", "time", "(", ")", ",", "server", ",", "message", ")", ")", "logger", ".", "warning", "(", "\"Removed server %s from active pool\"", ",", "server", ")", "# if this is the last server raise exception, otherwise try next", "if", "not", "self", ".", "_active_servers", ":", "raise", "ConnectionError", "(", "(", "\"No more Servers available, \"", "\"exception from last server: %s\"", ")", "%", "message", ")" ]
Drop server from active list and adds it to the inactive ones.
[ "Drop", "server", "from", "active", "list", "and", "adds", "it", "to", "the", "inactive", "ones", "." ]
68e39c95f5bbe88b74bbfa26de4347fc644636a8
https://github.com/crate/crate-python/blob/68e39c95f5bbe88b74bbfa26de4347fc644636a8/src/crate/client/http.py#L492-L508
18,118
crate/crate-python
src/crate/client/sqlalchemy/predicates/__init__.py
match
def match(column, term, match_type=None, options=None): """Generates match predicate for fulltext search :param column: A reference to a column or an index, or a subcolumn, or a dictionary of subcolumns with boost values. :param term: The term to match against. This string is analyzed and the resulting tokens are compared to the index. :param match_type (optional): The match type. Determine how the term is applied and the score calculated. :param options (optional): The match options. Specify match type behaviour. (Not possible without a specified match type.) Match options must be supplied as a dictionary. """ return Match(column, term, match_type, options)
python
def match(column, term, match_type=None, options=None): """Generates match predicate for fulltext search :param column: A reference to a column or an index, or a subcolumn, or a dictionary of subcolumns with boost values. :param term: The term to match against. This string is analyzed and the resulting tokens are compared to the index. :param match_type (optional): The match type. Determine how the term is applied and the score calculated. :param options (optional): The match options. Specify match type behaviour. (Not possible without a specified match type.) Match options must be supplied as a dictionary. """ return Match(column, term, match_type, options)
[ "def", "match", "(", "column", ",", "term", ",", "match_type", "=", "None", ",", "options", "=", "None", ")", ":", "return", "Match", "(", "column", ",", "term", ",", "match_type", ",", "options", ")" ]
Generates match predicate for fulltext search :param column: A reference to a column or an index, or a subcolumn, or a dictionary of subcolumns with boost values. :param term: The term to match against. This string is analyzed and the resulting tokens are compared to the index. :param match_type (optional): The match type. Determine how the term is applied and the score calculated. :param options (optional): The match options. Specify match type behaviour. (Not possible without a specified match type.) Match options must be supplied as a dictionary.
[ "Generates", "match", "predicate", "for", "fulltext", "search" ]
68e39c95f5bbe88b74bbfa26de4347fc644636a8
https://github.com/crate/crate-python/blob/68e39c95f5bbe88b74bbfa26de4347fc644636a8/src/crate/client/sqlalchemy/predicates/__init__.py#L70-L86
18,119
crate/crate-python
src/crate/client/blob.py
BlobContainer.put
def put(self, f, digest=None): """ Upload a blob :param f: File object to be uploaded (required to support seek if digest is not provided). :param digest: Optional SHA-1 hex digest of the file contents. Gets computed before actual upload if not provided, which requires an extra file read. :return: The hex digest of the uploaded blob if not provided in the call. Otherwise a boolean indicating if the blob has been newly created. """ if digest: actual_digest = digest else: actual_digest = self._compute_digest(f) created = self.conn.client.blob_put(self.container_name, actual_digest, f) if digest: return created return actual_digest
python
def put(self, f, digest=None): """ Upload a blob :param f: File object to be uploaded (required to support seek if digest is not provided). :param digest: Optional SHA-1 hex digest of the file contents. Gets computed before actual upload if not provided, which requires an extra file read. :return: The hex digest of the uploaded blob if not provided in the call. Otherwise a boolean indicating if the blob has been newly created. """ if digest: actual_digest = digest else: actual_digest = self._compute_digest(f) created = self.conn.client.blob_put(self.container_name, actual_digest, f) if digest: return created return actual_digest
[ "def", "put", "(", "self", ",", "f", ",", "digest", "=", "None", ")", ":", "if", "digest", ":", "actual_digest", "=", "digest", "else", ":", "actual_digest", "=", "self", ".", "_compute_digest", "(", "f", ")", "created", "=", "self", ".", "conn", ".", "client", ".", "blob_put", "(", "self", ".", "container_name", ",", "actual_digest", ",", "f", ")", "if", "digest", ":", "return", "created", "return", "actual_digest" ]
Upload a blob :param f: File object to be uploaded (required to support seek if digest is not provided). :param digest: Optional SHA-1 hex digest of the file contents. Gets computed before actual upload if not provided, which requires an extra file read. :return: The hex digest of the uploaded blob if not provided in the call. Otherwise a boolean indicating if the blob has been newly created.
[ "Upload", "a", "blob" ]
68e39c95f5bbe88b74bbfa26de4347fc644636a8
https://github.com/crate/crate-python/blob/68e39c95f5bbe88b74bbfa26de4347fc644636a8/src/crate/client/blob.py#L46-L71
18,120
crate/crate-python
src/crate/client/blob.py
BlobContainer.get
def get(self, digest, chunk_size=1024 * 128): """ Return the contents of a blob :param digest: the hex digest of the blob to return :param chunk_size: the size of the chunks returned on each iteration :return: generator returning chunks of data """ return self.conn.client.blob_get(self.container_name, digest, chunk_size)
python
def get(self, digest, chunk_size=1024 * 128): """ Return the contents of a blob :param digest: the hex digest of the blob to return :param chunk_size: the size of the chunks returned on each iteration :return: generator returning chunks of data """ return self.conn.client.blob_get(self.container_name, digest, chunk_size)
[ "def", "get", "(", "self", ",", "digest", ",", "chunk_size", "=", "1024", "*", "128", ")", ":", "return", "self", ".", "conn", ".", "client", ".", "blob_get", "(", "self", ".", "container_name", ",", "digest", ",", "chunk_size", ")" ]
Return the contents of a blob :param digest: the hex digest of the blob to return :param chunk_size: the size of the chunks returned on each iteration :return: generator returning chunks of data
[ "Return", "the", "contents", "of", "a", "blob" ]
68e39c95f5bbe88b74bbfa26de4347fc644636a8
https://github.com/crate/crate-python/blob/68e39c95f5bbe88b74bbfa26de4347fc644636a8/src/crate/client/blob.py#L73-L82
18,121
crate/crate-python
src/crate/client/blob.py
BlobContainer.delete
def delete(self, digest): """ Delete a blob :param digest: the hex digest of the blob to be deleted :return: True if blob existed """ return self.conn.client.blob_del(self.container_name, digest)
python
def delete(self, digest): """ Delete a blob :param digest: the hex digest of the blob to be deleted :return: True if blob existed """ return self.conn.client.blob_del(self.container_name, digest)
[ "def", "delete", "(", "self", ",", "digest", ")", ":", "return", "self", ".", "conn", ".", "client", ".", "blob_del", "(", "self", ".", "container_name", ",", "digest", ")" ]
Delete a blob :param digest: the hex digest of the blob to be deleted :return: True if blob existed
[ "Delete", "a", "blob" ]
68e39c95f5bbe88b74bbfa26de4347fc644636a8
https://github.com/crate/crate-python/blob/68e39c95f5bbe88b74bbfa26de4347fc644636a8/src/crate/client/blob.py#L84-L91
18,122
crate/crate-python
src/crate/client/blob.py
BlobContainer.exists
def exists(self, digest): """ Check if a blob exists :param digest: Hex digest of the blob :return: Boolean indicating existence of the blob """ return self.conn.client.blob_exists(self.container_name, digest)
python
def exists(self, digest): """ Check if a blob exists :param digest: Hex digest of the blob :return: Boolean indicating existence of the blob """ return self.conn.client.blob_exists(self.container_name, digest)
[ "def", "exists", "(", "self", ",", "digest", ")", ":", "return", "self", ".", "conn", ".", "client", ".", "blob_exists", "(", "self", ".", "container_name", ",", "digest", ")" ]
Check if a blob exists :param digest: Hex digest of the blob :return: Boolean indicating existence of the blob
[ "Check", "if", "a", "blob", "exists" ]
68e39c95f5bbe88b74bbfa26de4347fc644636a8
https://github.com/crate/crate-python/blob/68e39c95f5bbe88b74bbfa26de4347fc644636a8/src/crate/client/blob.py#L93-L100
18,123
crate/crate-python
src/crate/client/cursor.py
Cursor.next
def next(self): """ Return the next row of a query result set, respecting if cursor was closed. """ if self.rows is None: raise ProgrammingError( "No result available. " + "execute() or executemany() must be called first." ) elif not self._closed: return next(self.rows) else: raise ProgrammingError("Cursor closed")
python
def next(self): """ Return the next row of a query result set, respecting if cursor was closed. """ if self.rows is None: raise ProgrammingError( "No result available. " + "execute() or executemany() must be called first." ) elif not self._closed: return next(self.rows) else: raise ProgrammingError("Cursor closed")
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "rows", "is", "None", ":", "raise", "ProgrammingError", "(", "\"No result available. \"", "+", "\"execute() or executemany() must be called first.\"", ")", "elif", "not", "self", ".", "_closed", ":", "return", "next", "(", "self", ".", "rows", ")", "else", ":", "raise", "ProgrammingError", "(", "\"Cursor closed\"", ")" ]
Return the next row of a query result set, respecting if cursor was closed.
[ "Return", "the", "next", "row", "of", "a", "query", "result", "set", "respecting", "if", "cursor", "was", "closed", "." ]
68e39c95f5bbe88b74bbfa26de4347fc644636a8
https://github.com/crate/crate-python/blob/68e39c95f5bbe88b74bbfa26de4347fc644636a8/src/crate/client/cursor.py#L175-L188
18,124
crate/crate-python
src/crate/client/cursor.py
Cursor.duration
def duration(self): """ This read-only attribute specifies the server-side duration of a query in milliseconds. """ if self._closed or \ not self._result or \ "duration" not in self._result: return -1 return self._result.get("duration", 0)
python
def duration(self): """ This read-only attribute specifies the server-side duration of a query in milliseconds. """ if self._closed or \ not self._result or \ "duration" not in self._result: return -1 return self._result.get("duration", 0)
[ "def", "duration", "(", "self", ")", ":", "if", "self", ".", "_closed", "or", "not", "self", ".", "_result", "or", "\"duration\"", "not", "in", "self", ".", "_result", ":", "return", "-", "1", "return", "self", ".", "_result", ".", "get", "(", "\"duration\"", ",", "0", ")" ]
This read-only attribute specifies the server-side duration of a query in milliseconds.
[ "This", "read", "-", "only", "attribute", "specifies", "the", "server", "-", "side", "duration", "of", "a", "query", "in", "milliseconds", "." ]
68e39c95f5bbe88b74bbfa26de4347fc644636a8
https://github.com/crate/crate-python/blob/68e39c95f5bbe88b74bbfa26de4347fc644636a8/src/crate/client/cursor.py#L212-L221
18,125
crate/crate-python
src/crate/client/sqlalchemy/compiler.py
rewrite_update
def rewrite_update(clauseelement, multiparams, params): """ change the params to enable partial updates sqlalchemy by default only supports updates of complex types in the form of "col = ?", ({"x": 1, "y": 2} but crate supports "col['x'] = ?, col['y'] = ?", (1, 2) by using the `Craty` (`MutableDict`) type. The update statement is only rewritten if an item of the MutableDict was changed. """ newmultiparams = [] _multiparams = multiparams[0] if len(_multiparams) == 0: return clauseelement, multiparams, params for _params in _multiparams: newparams = {} for key, val in _params.items(): if ( not isinstance(val, MutableDict) or (not any(val._changed_keys) and not any(val._deleted_keys)) ): newparams[key] = val continue for subkey, subval in val.items(): if subkey in val._changed_keys: newparams["{0}['{1}']".format(key, subkey)] = subval for subkey in val._deleted_keys: newparams["{0}['{1}']".format(key, subkey)] = None newmultiparams.append(newparams) _multiparams = (newmultiparams, ) clause = clauseelement.values(newmultiparams[0]) clause._crate_specific = True return clause, _multiparams, params
python
def rewrite_update(clauseelement, multiparams, params): """ change the params to enable partial updates sqlalchemy by default only supports updates of complex types in the form of "col = ?", ({"x": 1, "y": 2} but crate supports "col['x'] = ?, col['y'] = ?", (1, 2) by using the `Craty` (`MutableDict`) type. The update statement is only rewritten if an item of the MutableDict was changed. """ newmultiparams = [] _multiparams = multiparams[0] if len(_multiparams) == 0: return clauseelement, multiparams, params for _params in _multiparams: newparams = {} for key, val in _params.items(): if ( not isinstance(val, MutableDict) or (not any(val._changed_keys) and not any(val._deleted_keys)) ): newparams[key] = val continue for subkey, subval in val.items(): if subkey in val._changed_keys: newparams["{0}['{1}']".format(key, subkey)] = subval for subkey in val._deleted_keys: newparams["{0}['{1}']".format(key, subkey)] = None newmultiparams.append(newparams) _multiparams = (newmultiparams, ) clause = clauseelement.values(newmultiparams[0]) clause._crate_specific = True return clause, _multiparams, params
[ "def", "rewrite_update", "(", "clauseelement", ",", "multiparams", ",", "params", ")", ":", "newmultiparams", "=", "[", "]", "_multiparams", "=", "multiparams", "[", "0", "]", "if", "len", "(", "_multiparams", ")", "==", "0", ":", "return", "clauseelement", ",", "multiparams", ",", "params", "for", "_params", "in", "_multiparams", ":", "newparams", "=", "{", "}", "for", "key", ",", "val", "in", "_params", ".", "items", "(", ")", ":", "if", "(", "not", "isinstance", "(", "val", ",", "MutableDict", ")", "or", "(", "not", "any", "(", "val", ".", "_changed_keys", ")", "and", "not", "any", "(", "val", ".", "_deleted_keys", ")", ")", ")", ":", "newparams", "[", "key", "]", "=", "val", "continue", "for", "subkey", ",", "subval", "in", "val", ".", "items", "(", ")", ":", "if", "subkey", "in", "val", ".", "_changed_keys", ":", "newparams", "[", "\"{0}['{1}']\"", ".", "format", "(", "key", ",", "subkey", ")", "]", "=", "subval", "for", "subkey", "in", "val", ".", "_deleted_keys", ":", "newparams", "[", "\"{0}['{1}']\"", ".", "format", "(", "key", ",", "subkey", ")", "]", "=", "None", "newmultiparams", ".", "append", "(", "newparams", ")", "_multiparams", "=", "(", "newmultiparams", ",", ")", "clause", "=", "clauseelement", ".", "values", "(", "newmultiparams", "[", "0", "]", ")", "clause", ".", "_crate_specific", "=", "True", "return", "clause", ",", "_multiparams", ",", "params" ]
change the params to enable partial updates sqlalchemy by default only supports updates of complex types in the form of "col = ?", ({"x": 1, "y": 2} but crate supports "col['x'] = ?, col['y'] = ?", (1, 2) by using the `Craty` (`MutableDict`) type. The update statement is only rewritten if an item of the MutableDict was changed.
[ "change", "the", "params", "to", "enable", "partial", "updates" ]
68e39c95f5bbe88b74bbfa26de4347fc644636a8
https://github.com/crate/crate-python/blob/68e39c95f5bbe88b74bbfa26de4347fc644636a8/src/crate/client/sqlalchemy/compiler.py#L32-L70
18,126
crate/crate-python
src/crate/client/sqlalchemy/compiler.py
CrateCompiler._get_crud_params
def _get_crud_params(compiler, stmt, **kw): """ extract values from crud parameters taken from SQLAlchemy's crud module (since 1.0.x) and adapted for Crate dialect""" compiler.postfetch = [] compiler.insert_prefetch = [] compiler.update_prefetch = [] compiler.returning = [] # no parameters in the statement, no parameters in the # compiled params - return binds for all columns if compiler.column_keys is None and stmt.parameters is None: return [(c, crud._create_bind_param(compiler, c, None, required=True)) for c in stmt.table.columns] if stmt._has_multi_parameters: stmt_parameters = stmt.parameters[0] else: stmt_parameters = stmt.parameters # getters - these are normally just column.key, # but in the case of mysql multi-table update, the rules for # .key must conditionally take tablename into account if SA_VERSION >= SA_1_1: _column_as_key, _getattr_col_key, _col_bind_name = \ crud._key_getters_for_crud_column(compiler, stmt) else: _column_as_key, _getattr_col_key, _col_bind_name = \ crud._key_getters_for_crud_column(compiler) # if we have statement parameters - set defaults in the # compiled params if compiler.column_keys is None: parameters = {} else: parameters = dict((_column_as_key(key), crud.REQUIRED) for key in compiler.column_keys if not stmt_parameters or key not in stmt_parameters) # create a list of column assignment clauses as tuples values = [] if stmt_parameters is not None: crud._get_stmt_parameters_params( compiler, parameters, stmt_parameters, _column_as_key, values, kw) check_columns = {} crud._scan_cols(compiler, stmt, parameters, _getattr_col_key, _column_as_key, _col_bind_name, check_columns, values, kw) if stmt._has_multi_parameters: values = crud._extend_values_for_multiparams(compiler, stmt, values, kw) return values
python
def _get_crud_params(compiler, stmt, **kw): """ extract values from crud parameters taken from SQLAlchemy's crud module (since 1.0.x) and adapted for Crate dialect""" compiler.postfetch = [] compiler.insert_prefetch = [] compiler.update_prefetch = [] compiler.returning = [] # no parameters in the statement, no parameters in the # compiled params - return binds for all columns if compiler.column_keys is None and stmt.parameters is None: return [(c, crud._create_bind_param(compiler, c, None, required=True)) for c in stmt.table.columns] if stmt._has_multi_parameters: stmt_parameters = stmt.parameters[0] else: stmt_parameters = stmt.parameters # getters - these are normally just column.key, # but in the case of mysql multi-table update, the rules for # .key must conditionally take tablename into account if SA_VERSION >= SA_1_1: _column_as_key, _getattr_col_key, _col_bind_name = \ crud._key_getters_for_crud_column(compiler, stmt) else: _column_as_key, _getattr_col_key, _col_bind_name = \ crud._key_getters_for_crud_column(compiler) # if we have statement parameters - set defaults in the # compiled params if compiler.column_keys is None: parameters = {} else: parameters = dict((_column_as_key(key), crud.REQUIRED) for key in compiler.column_keys if not stmt_parameters or key not in stmt_parameters) # create a list of column assignment clauses as tuples values = [] if stmt_parameters is not None: crud._get_stmt_parameters_params( compiler, parameters, stmt_parameters, _column_as_key, values, kw) check_columns = {} crud._scan_cols(compiler, stmt, parameters, _getattr_col_key, _column_as_key, _col_bind_name, check_columns, values, kw) if stmt._has_multi_parameters: values = crud._extend_values_for_multiparams(compiler, stmt, values, kw) return values
[ "def", "_get_crud_params", "(", "compiler", ",", "stmt", ",", "*", "*", "kw", ")", ":", "compiler", ".", "postfetch", "=", "[", "]", "compiler", ".", "insert_prefetch", "=", "[", "]", "compiler", ".", "update_prefetch", "=", "[", "]", "compiler", ".", "returning", "=", "[", "]", "# no parameters in the statement, no parameters in the", "# compiled params - return binds for all columns", "if", "compiler", ".", "column_keys", "is", "None", "and", "stmt", ".", "parameters", "is", "None", ":", "return", "[", "(", "c", ",", "crud", ".", "_create_bind_param", "(", "compiler", ",", "c", ",", "None", ",", "required", "=", "True", ")", ")", "for", "c", "in", "stmt", ".", "table", ".", "columns", "]", "if", "stmt", ".", "_has_multi_parameters", ":", "stmt_parameters", "=", "stmt", ".", "parameters", "[", "0", "]", "else", ":", "stmt_parameters", "=", "stmt", ".", "parameters", "# getters - these are normally just column.key,", "# but in the case of mysql multi-table update, the rules for", "# .key must conditionally take tablename into account", "if", "SA_VERSION", ">=", "SA_1_1", ":", "_column_as_key", ",", "_getattr_col_key", ",", "_col_bind_name", "=", "crud", ".", "_key_getters_for_crud_column", "(", "compiler", ",", "stmt", ")", "else", ":", "_column_as_key", ",", "_getattr_col_key", ",", "_col_bind_name", "=", "crud", ".", "_key_getters_for_crud_column", "(", "compiler", ")", "# if we have statement parameters - set defaults in the", "# compiled params", "if", "compiler", ".", "column_keys", "is", "None", ":", "parameters", "=", "{", "}", "else", ":", "parameters", "=", "dict", "(", "(", "_column_as_key", "(", "key", ")", ",", "crud", ".", "REQUIRED", ")", "for", "key", "in", "compiler", ".", "column_keys", "if", "not", "stmt_parameters", "or", "key", "not", "in", "stmt_parameters", ")", "# create a list of column assignment clauses as tuples", "values", "=", "[", "]", "if", "stmt_parameters", "is", "not", "None", ":", "crud", ".", "_get_stmt_parameters_params", "(", "compiler", ",", "parameters", ",", "stmt_parameters", ",", "_column_as_key", ",", "values", ",", "kw", ")", "check_columns", "=", "{", "}", "crud", ".", "_scan_cols", "(", "compiler", ",", "stmt", ",", "parameters", ",", "_getattr_col_key", ",", "_column_as_key", ",", "_col_bind_name", ",", "check_columns", ",", "values", ",", "kw", ")", "if", "stmt", ".", "_has_multi_parameters", ":", "values", "=", "crud", ".", "_extend_values_for_multiparams", "(", "compiler", ",", "stmt", ",", "values", ",", "kw", ")", "return", "values" ]
extract values from crud parameters taken from SQLAlchemy's crud module (since 1.0.x) and adapted for Crate dialect
[ "extract", "values", "from", "crud", "parameters" ]
68e39c95f5bbe88b74bbfa26de4347fc644636a8
https://github.com/crate/crate-python/blob/68e39c95f5bbe88b74bbfa26de4347fc644636a8/src/crate/client/sqlalchemy/compiler.py#L362-L423
18,127
kstateome/django-cas
cas/models.py
get_tgt_for
def get_tgt_for(user): """ Fetch a ticket granting ticket for a given user. :param user: UserObj :return: TGT or Exepction """ if not settings.CAS_PROXY_CALLBACK: raise CasConfigException("No proxy callback set in settings") try: return Tgt.objects.get(username=user.username) except ObjectDoesNotExist: logger.warning('No ticket found for user {user}'.format( user=user.username )) raise CasTicketException("no ticket found for user " + user.username)
python
def get_tgt_for(user): """ Fetch a ticket granting ticket for a given user. :param user: UserObj :return: TGT or Exepction """ if not settings.CAS_PROXY_CALLBACK: raise CasConfigException("No proxy callback set in settings") try: return Tgt.objects.get(username=user.username) except ObjectDoesNotExist: logger.warning('No ticket found for user {user}'.format( user=user.username )) raise CasTicketException("no ticket found for user " + user.username)
[ "def", "get_tgt_for", "(", "user", ")", ":", "if", "not", "settings", ".", "CAS_PROXY_CALLBACK", ":", "raise", "CasConfigException", "(", "\"No proxy callback set in settings\"", ")", "try", ":", "return", "Tgt", ".", "objects", ".", "get", "(", "username", "=", "user", ".", "username", ")", "except", "ObjectDoesNotExist", ":", "logger", ".", "warning", "(", "'No ticket found for user {user}'", ".", "format", "(", "user", "=", "user", ".", "username", ")", ")", "raise", "CasTicketException", "(", "\"no ticket found for user \"", "+", "user", ".", "username", ")" ]
Fetch a ticket granting ticket for a given user. :param user: UserObj :return: TGT or Exepction
[ "Fetch", "a", "ticket", "granting", "ticket", "for", "a", "given", "user", "." ]
8a871093966f001b4dadf7d097ac326169f3c066
https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/models.py#L77-L94
18,128
kstateome/django-cas
cas/models.py
Tgt.get_proxy_ticket_for
def get_proxy_ticket_for(self, service): """ Verifies CAS 2.0+ XML-based authentication ticket. :param: service Returns username on success and None on failure. """ if not settings.CAS_PROXY_CALLBACK: raise CasConfigException("No proxy callback set in settings") params = {'pgt': self.tgt, 'targetService': service} url = (urljoin(settings.CAS_SERVER_URL, 'proxy') + '?' + urlencode(params)) page = urlopen(url) try: response = page.read() tree = ElementTree.fromstring(response) if tree[0].tag.endswith('proxySuccess'): return tree[0][0].text else: logger.warning('Failed to get proxy ticket') raise CasTicketException('Failed to get proxy ticket: %s' % \ tree[0].text.strip()) finally: page.close()
python
def get_proxy_ticket_for(self, service): """ Verifies CAS 2.0+ XML-based authentication ticket. :param: service Returns username on success and None on failure. """ if not settings.CAS_PROXY_CALLBACK: raise CasConfigException("No proxy callback set in settings") params = {'pgt': self.tgt, 'targetService': service} url = (urljoin(settings.CAS_SERVER_URL, 'proxy') + '?' + urlencode(params)) page = urlopen(url) try: response = page.read() tree = ElementTree.fromstring(response) if tree[0].tag.endswith('proxySuccess'): return tree[0][0].text else: logger.warning('Failed to get proxy ticket') raise CasTicketException('Failed to get proxy ticket: %s' % \ tree[0].text.strip()) finally: page.close()
[ "def", "get_proxy_ticket_for", "(", "self", ",", "service", ")", ":", "if", "not", "settings", ".", "CAS_PROXY_CALLBACK", ":", "raise", "CasConfigException", "(", "\"No proxy callback set in settings\"", ")", "params", "=", "{", "'pgt'", ":", "self", ".", "tgt", ",", "'targetService'", ":", "service", "}", "url", "=", "(", "urljoin", "(", "settings", ".", "CAS_SERVER_URL", ",", "'proxy'", ")", "+", "'?'", "+", "urlencode", "(", "params", ")", ")", "page", "=", "urlopen", "(", "url", ")", "try", ":", "response", "=", "page", ".", "read", "(", ")", "tree", "=", "ElementTree", ".", "fromstring", "(", "response", ")", "if", "tree", "[", "0", "]", ".", "tag", ".", "endswith", "(", "'proxySuccess'", ")", ":", "return", "tree", "[", "0", "]", "[", "0", "]", ".", "text", "else", ":", "logger", ".", "warning", "(", "'Failed to get proxy ticket'", ")", "raise", "CasTicketException", "(", "'Failed to get proxy ticket: %s'", "%", "tree", "[", "0", "]", ".", "text", ".", "strip", "(", ")", ")", "finally", ":", "page", ".", "close", "(", ")" ]
Verifies CAS 2.0+ XML-based authentication ticket. :param: service Returns username on success and None on failure.
[ "Verifies", "CAS", "2", ".", "0", "+", "XML", "-", "based", "authentication", "ticket", "." ]
8a871093966f001b4dadf7d097ac326169f3c066
https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/models.py#L36-L65
18,129
kstateome/django-cas
cas/backends.py
_internal_verify_cas
def _internal_verify_cas(ticket, service, suffix): """Verifies CAS 2.0 and 3.0 XML-based authentication ticket. Returns username on success and None on failure. """ params = {'ticket': ticket, 'service': service} if settings.CAS_PROXY_CALLBACK: params['pgtUrl'] = settings.CAS_PROXY_CALLBACK url = (urljoin(settings.CAS_SERVER_URL, suffix) + '?' + urlencode(params)) page = urlopen(url) username = None try: response = page.read() tree = ElementTree.fromstring(response) document = minidom.parseString(response) if tree[0].tag.endswith('authenticationSuccess'): if settings.CAS_RESPONSE_CALLBACKS: cas_response_callbacks(tree) username = tree[0][0].text pgt_el = document.getElementsByTagName('cas:proxyGrantingTicket') if pgt_el: pgt = pgt_el[0].firstChild.nodeValue try: pgtIou = _get_pgtiou(pgt) tgt = Tgt.objects.get(username=username) tgt.tgt = pgtIou.tgt tgt.save() pgtIou.delete() except Tgt.DoesNotExist: Tgt.objects.create(username=username, tgt=pgtIou.tgt) logger.info('Creating TGT ticket for {user}'.format( user=username )) pgtIou.delete() except Exception as e: logger.warning('Failed to do proxy authentication. {message}'.format( message=e )) else: failure = document.getElementsByTagName('cas:authenticationFailure') if failure: logger.warn('Authentication failed from CAS server: %s', failure[0].firstChild.nodeValue) except Exception as e: logger.error('Failed to verify CAS authentication: {message}'.format( message=e )) finally: page.close() return username
python
def _internal_verify_cas(ticket, service, suffix): """Verifies CAS 2.0 and 3.0 XML-based authentication ticket. Returns username on success and None on failure. """ params = {'ticket': ticket, 'service': service} if settings.CAS_PROXY_CALLBACK: params['pgtUrl'] = settings.CAS_PROXY_CALLBACK url = (urljoin(settings.CAS_SERVER_URL, suffix) + '?' + urlencode(params)) page = urlopen(url) username = None try: response = page.read() tree = ElementTree.fromstring(response) document = minidom.parseString(response) if tree[0].tag.endswith('authenticationSuccess'): if settings.CAS_RESPONSE_CALLBACKS: cas_response_callbacks(tree) username = tree[0][0].text pgt_el = document.getElementsByTagName('cas:proxyGrantingTicket') if pgt_el: pgt = pgt_el[0].firstChild.nodeValue try: pgtIou = _get_pgtiou(pgt) tgt = Tgt.objects.get(username=username) tgt.tgt = pgtIou.tgt tgt.save() pgtIou.delete() except Tgt.DoesNotExist: Tgt.objects.create(username=username, tgt=pgtIou.tgt) logger.info('Creating TGT ticket for {user}'.format( user=username )) pgtIou.delete() except Exception as e: logger.warning('Failed to do proxy authentication. {message}'.format( message=e )) else: failure = document.getElementsByTagName('cas:authenticationFailure') if failure: logger.warn('Authentication failed from CAS server: %s', failure[0].firstChild.nodeValue) except Exception as e: logger.error('Failed to verify CAS authentication: {message}'.format( message=e )) finally: page.close() return username
[ "def", "_internal_verify_cas", "(", "ticket", ",", "service", ",", "suffix", ")", ":", "params", "=", "{", "'ticket'", ":", "ticket", ",", "'service'", ":", "service", "}", "if", "settings", ".", "CAS_PROXY_CALLBACK", ":", "params", "[", "'pgtUrl'", "]", "=", "settings", ".", "CAS_PROXY_CALLBACK", "url", "=", "(", "urljoin", "(", "settings", ".", "CAS_SERVER_URL", ",", "suffix", ")", "+", "'?'", "+", "urlencode", "(", "params", ")", ")", "page", "=", "urlopen", "(", "url", ")", "username", "=", "None", "try", ":", "response", "=", "page", ".", "read", "(", ")", "tree", "=", "ElementTree", ".", "fromstring", "(", "response", ")", "document", "=", "minidom", ".", "parseString", "(", "response", ")", "if", "tree", "[", "0", "]", ".", "tag", ".", "endswith", "(", "'authenticationSuccess'", ")", ":", "if", "settings", ".", "CAS_RESPONSE_CALLBACKS", ":", "cas_response_callbacks", "(", "tree", ")", "username", "=", "tree", "[", "0", "]", "[", "0", "]", ".", "text", "pgt_el", "=", "document", ".", "getElementsByTagName", "(", "'cas:proxyGrantingTicket'", ")", "if", "pgt_el", ":", "pgt", "=", "pgt_el", "[", "0", "]", ".", "firstChild", ".", "nodeValue", "try", ":", "pgtIou", "=", "_get_pgtiou", "(", "pgt", ")", "tgt", "=", "Tgt", ".", "objects", ".", "get", "(", "username", "=", "username", ")", "tgt", ".", "tgt", "=", "pgtIou", ".", "tgt", "tgt", ".", "save", "(", ")", "pgtIou", ".", "delete", "(", ")", "except", "Tgt", ".", "DoesNotExist", ":", "Tgt", ".", "objects", ".", "create", "(", "username", "=", "username", ",", "tgt", "=", "pgtIou", ".", "tgt", ")", "logger", ".", "info", "(", "'Creating TGT ticket for {user}'", ".", "format", "(", "user", "=", "username", ")", ")", "pgtIou", ".", "delete", "(", ")", "except", "Exception", "as", "e", ":", "logger", ".", "warning", "(", "'Failed to do proxy authentication. {message}'", ".", "format", "(", "message", "=", "e", ")", ")", "else", ":", "failure", "=", "document", ".", "getElementsByTagName", "(", "'cas:authenticationFailure'", ")", "if", "failure", ":", "logger", ".", "warn", "(", "'Authentication failed from CAS server: %s'", ",", "failure", "[", "0", "]", ".", "firstChild", ".", "nodeValue", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "'Failed to verify CAS authentication: {message}'", ".", "format", "(", "message", "=", "e", ")", ")", "finally", ":", "page", ".", "close", "(", ")", "return", "username" ]
Verifies CAS 2.0 and 3.0 XML-based authentication ticket. Returns username on success and None on failure.
[ "Verifies", "CAS", "2", ".", "0", "and", "3", ".", "0", "XML", "-", "based", "authentication", "ticket", "." ]
8a871093966f001b4dadf7d097ac326169f3c066
https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/backends.py#L75-L138
18,130
kstateome/django-cas
cas/backends.py
verify_proxy_ticket
def verify_proxy_ticket(ticket, service): """ Verifies CAS 2.0+ XML-based proxy ticket. :param: ticket :param: service Returns username on success and None on failure. """ params = {'ticket': ticket, 'service': service} url = (urljoin(settings.CAS_SERVER_URL, 'proxyValidate') + '?' + urlencode(params)) page = urlopen(url) try: response = page.read() tree = ElementTree.fromstring(response) if tree[0].tag.endswith('authenticationSuccess'): username = tree[0][0].text proxies = [] if len(tree[0]) > 1: for element in tree[0][1]: proxies.append(element.text) return {"username": username, "proxies": proxies} else: return None finally: page.close()
python
def verify_proxy_ticket(ticket, service): """ Verifies CAS 2.0+ XML-based proxy ticket. :param: ticket :param: service Returns username on success and None on failure. """ params = {'ticket': ticket, 'service': service} url = (urljoin(settings.CAS_SERVER_URL, 'proxyValidate') + '?' + urlencode(params)) page = urlopen(url) try: response = page.read() tree = ElementTree.fromstring(response) if tree[0].tag.endswith('authenticationSuccess'): username = tree[0][0].text proxies = [] if len(tree[0]) > 1: for element in tree[0][1]: proxies.append(element.text) return {"username": username, "proxies": proxies} else: return None finally: page.close()
[ "def", "verify_proxy_ticket", "(", "ticket", ",", "service", ")", ":", "params", "=", "{", "'ticket'", ":", "ticket", ",", "'service'", ":", "service", "}", "url", "=", "(", "urljoin", "(", "settings", ".", "CAS_SERVER_URL", ",", "'proxyValidate'", ")", "+", "'?'", "+", "urlencode", "(", "params", ")", ")", "page", "=", "urlopen", "(", "url", ")", "try", ":", "response", "=", "page", ".", "read", "(", ")", "tree", "=", "ElementTree", ".", "fromstring", "(", "response", ")", "if", "tree", "[", "0", "]", ".", "tag", ".", "endswith", "(", "'authenticationSuccess'", ")", ":", "username", "=", "tree", "[", "0", "]", "[", "0", "]", ".", "text", "proxies", "=", "[", "]", "if", "len", "(", "tree", "[", "0", "]", ")", ">", "1", ":", "for", "element", "in", "tree", "[", "0", "]", "[", "1", "]", ":", "proxies", ".", "append", "(", "element", ".", "text", ")", "return", "{", "\"username\"", ":", "username", ",", "\"proxies\"", ":", "proxies", "}", "else", ":", "return", "None", "finally", ":", "page", ".", "close", "(", ")" ]
Verifies CAS 2.0+ XML-based proxy ticket. :param: ticket :param: service Returns username on success and None on failure.
[ "Verifies", "CAS", "2", ".", "0", "+", "XML", "-", "based", "proxy", "ticket", "." ]
8a871093966f001b4dadf7d097ac326169f3c066
https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/backends.py#L141-L171
18,131
kstateome/django-cas
cas/backends.py
_get_pgtiou
def _get_pgtiou(pgt): """ Returns a PgtIOU object given a pgt. The PgtIOU (tgt) is set by the CAS server in a different request that has completed before this call, however, it may not be found in the database by this calling thread, hence the attempt to get the ticket is retried for up to 5 seconds. This should be handled some better way. Users can opt out of this waiting period by setting CAS_PGT_FETCH_WAIT = False :param: pgt """ pgtIou = None retries_left = 5 if not settings.CAS_PGT_FETCH_WAIT: retries_left = 1 while not pgtIou and retries_left: try: return PgtIOU.objects.get(tgt=pgt) except PgtIOU.DoesNotExist: if settings.CAS_PGT_FETCH_WAIT: time.sleep(1) retries_left -= 1 logger.info('Did not fetch ticket, trying again. {tries} tries left.'.format( tries=retries_left )) raise CasTicketException("Could not find pgtIou for pgt %s" % pgt)
python
def _get_pgtiou(pgt): """ Returns a PgtIOU object given a pgt. The PgtIOU (tgt) is set by the CAS server in a different request that has completed before this call, however, it may not be found in the database by this calling thread, hence the attempt to get the ticket is retried for up to 5 seconds. This should be handled some better way. Users can opt out of this waiting period by setting CAS_PGT_FETCH_WAIT = False :param: pgt """ pgtIou = None retries_left = 5 if not settings.CAS_PGT_FETCH_WAIT: retries_left = 1 while not pgtIou and retries_left: try: return PgtIOU.objects.get(tgt=pgt) except PgtIOU.DoesNotExist: if settings.CAS_PGT_FETCH_WAIT: time.sleep(1) retries_left -= 1 logger.info('Did not fetch ticket, trying again. {tries} tries left.'.format( tries=retries_left )) raise CasTicketException("Could not find pgtIou for pgt %s" % pgt)
[ "def", "_get_pgtiou", "(", "pgt", ")", ":", "pgtIou", "=", "None", "retries_left", "=", "5", "if", "not", "settings", ".", "CAS_PGT_FETCH_WAIT", ":", "retries_left", "=", "1", "while", "not", "pgtIou", "and", "retries_left", ":", "try", ":", "return", "PgtIOU", ".", "objects", ".", "get", "(", "tgt", "=", "pgt", ")", "except", "PgtIOU", ".", "DoesNotExist", ":", "if", "settings", ".", "CAS_PGT_FETCH_WAIT", ":", "time", ".", "sleep", "(", "1", ")", "retries_left", "-=", "1", "logger", ".", "info", "(", "'Did not fetch ticket, trying again. {tries} tries left.'", ".", "format", "(", "tries", "=", "retries_left", ")", ")", "raise", "CasTicketException", "(", "\"Could not find pgtIou for pgt %s\"", "%", "pgt", ")" ]
Returns a PgtIOU object given a pgt. The PgtIOU (tgt) is set by the CAS server in a different request that has completed before this call, however, it may not be found in the database by this calling thread, hence the attempt to get the ticket is retried for up to 5 seconds. This should be handled some better way. Users can opt out of this waiting period by setting CAS_PGT_FETCH_WAIT = False :param: pgt
[ "Returns", "a", "PgtIOU", "object", "given", "a", "pgt", "." ]
8a871093966f001b4dadf7d097ac326169f3c066
https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/backends.py#L181-L213
18,132
kstateome/django-cas
cas/decorators.py
gateway
def gateway(): """ Authenticates single sign on session if ticket is available, but doesn't redirect to sign in url otherwise. """ if settings.CAS_GATEWAY == False: raise ImproperlyConfigured('CAS_GATEWAY must be set to True') def wrap(func): def wrapped_f(*args): from cas.views import login request = args[0] try: # use callable for pre-django 2.0 is_authenticated = request.user.is_authenticated() except TypeError: is_authenticated = request.user.is_authenticated if is_authenticated: # Is Authed, fine pass else: path_with_params = request.path + '?' + urlencode(request.GET.copy()) if request.GET.get('ticket'): # Not Authed, but have a ticket! # Try to authenticate response = login(request, path_with_params, False, True) if isinstance(response, HttpResponseRedirect): # For certain instances where a forbidden occurs, we need to pass instead of return a response. return response else: #Not Authed, but no ticket gatewayed = request.GET.get('gatewayed') if gatewayed == 'true': pass else: # Not Authed, try to authenticate response = login(request, path_with_params, False, True) if isinstance(response, HttpResponseRedirect): return response return func(*args) return wrapped_f return wrap
python
def gateway(): """ Authenticates single sign on session if ticket is available, but doesn't redirect to sign in url otherwise. """ if settings.CAS_GATEWAY == False: raise ImproperlyConfigured('CAS_GATEWAY must be set to True') def wrap(func): def wrapped_f(*args): from cas.views import login request = args[0] try: # use callable for pre-django 2.0 is_authenticated = request.user.is_authenticated() except TypeError: is_authenticated = request.user.is_authenticated if is_authenticated: # Is Authed, fine pass else: path_with_params = request.path + '?' + urlencode(request.GET.copy()) if request.GET.get('ticket'): # Not Authed, but have a ticket! # Try to authenticate response = login(request, path_with_params, False, True) if isinstance(response, HttpResponseRedirect): # For certain instances where a forbidden occurs, we need to pass instead of return a response. return response else: #Not Authed, but no ticket gatewayed = request.GET.get('gatewayed') if gatewayed == 'true': pass else: # Not Authed, try to authenticate response = login(request, path_with_params, False, True) if isinstance(response, HttpResponseRedirect): return response return func(*args) return wrapped_f return wrap
[ "def", "gateway", "(", ")", ":", "if", "settings", ".", "CAS_GATEWAY", "==", "False", ":", "raise", "ImproperlyConfigured", "(", "'CAS_GATEWAY must be set to True'", ")", "def", "wrap", "(", "func", ")", ":", "def", "wrapped_f", "(", "*", "args", ")", ":", "from", "cas", ".", "views", "import", "login", "request", "=", "args", "[", "0", "]", "try", ":", "# use callable for pre-django 2.0", "is_authenticated", "=", "request", ".", "user", ".", "is_authenticated", "(", ")", "except", "TypeError", ":", "is_authenticated", "=", "request", ".", "user", ".", "is_authenticated", "if", "is_authenticated", ":", "# Is Authed, fine", "pass", "else", ":", "path_with_params", "=", "request", ".", "path", "+", "'?'", "+", "urlencode", "(", "request", ".", "GET", ".", "copy", "(", ")", ")", "if", "request", ".", "GET", ".", "get", "(", "'ticket'", ")", ":", "# Not Authed, but have a ticket!", "# Try to authenticate", "response", "=", "login", "(", "request", ",", "path_with_params", ",", "False", ",", "True", ")", "if", "isinstance", "(", "response", ",", "HttpResponseRedirect", ")", ":", "# For certain instances where a forbidden occurs, we need to pass instead of return a response.", "return", "response", "else", ":", "#Not Authed, but no ticket", "gatewayed", "=", "request", ".", "GET", ".", "get", "(", "'gatewayed'", ")", "if", "gatewayed", "==", "'true'", ":", "pass", "else", ":", "# Not Authed, try to authenticate", "response", "=", "login", "(", "request", ",", "path_with_params", ",", "False", ",", "True", ")", "if", "isinstance", "(", "response", ",", "HttpResponseRedirect", ")", ":", "return", "response", "return", "func", "(", "*", "args", ")", "return", "wrapped_f", "return", "wrap" ]
Authenticates single sign on session if ticket is available, but doesn't redirect to sign in url otherwise.
[ "Authenticates", "single", "sign", "on", "session", "if", "ticket", "is", "available", "but", "doesn", "t", "redirect", "to", "sign", "in", "url", "otherwise", "." ]
8a871093966f001b4dadf7d097ac326169f3c066
https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/decorators.py#L60-L106
18,133
kstateome/django-cas
cas/views.py
_service_url
def _service_url(request, redirect_to=None, gateway=False): """ Generates application service URL for CAS :param: request Request Object :param: redirect_to URL to redriect to :param: gateway Should this be a gatewayed pass through """ if settings.CAS_FORCE_SSL_SERVICE_URL: protocol = 'https://' else: protocol = ('http://', 'https://')[request.is_secure()] host = request.get_host() service = protocol + host + request.path if redirect_to: if '?' in service: service += '&' else: service += '?' if gateway: """ If gateway, capture params and reencode them before returning a url """ gateway_params = [(REDIRECT_FIELD_NAME, redirect_to), ('gatewayed', 'true')] query_dict = request.GET.copy() try: del query_dict['ticket'] except: pass query_list = query_dict.items() # remove duplicate params for item in query_list: for index, item2 in enumerate(gateway_params): if item[0] == item2[0]: gateway_params.pop(index) extra_params = gateway_params + query_list #Sort params by key name so they are always in the same order. sorted_params = sorted(extra_params, key=itemgetter(0)) service += urlencode(sorted_params) else: service += urlencode({REDIRECT_FIELD_NAME: redirect_to}) return service
python
def _service_url(request, redirect_to=None, gateway=False): """ Generates application service URL for CAS :param: request Request Object :param: redirect_to URL to redriect to :param: gateway Should this be a gatewayed pass through """ if settings.CAS_FORCE_SSL_SERVICE_URL: protocol = 'https://' else: protocol = ('http://', 'https://')[request.is_secure()] host = request.get_host() service = protocol + host + request.path if redirect_to: if '?' in service: service += '&' else: service += '?' if gateway: """ If gateway, capture params and reencode them before returning a url """ gateway_params = [(REDIRECT_FIELD_NAME, redirect_to), ('gatewayed', 'true')] query_dict = request.GET.copy() try: del query_dict['ticket'] except: pass query_list = query_dict.items() # remove duplicate params for item in query_list: for index, item2 in enumerate(gateway_params): if item[0] == item2[0]: gateway_params.pop(index) extra_params = gateway_params + query_list #Sort params by key name so they are always in the same order. sorted_params = sorted(extra_params, key=itemgetter(0)) service += urlencode(sorted_params) else: service += urlencode({REDIRECT_FIELD_NAME: redirect_to}) return service
[ "def", "_service_url", "(", "request", ",", "redirect_to", "=", "None", ",", "gateway", "=", "False", ")", ":", "if", "settings", ".", "CAS_FORCE_SSL_SERVICE_URL", ":", "protocol", "=", "'https://'", "else", ":", "protocol", "=", "(", "'http://'", ",", "'https://'", ")", "[", "request", ".", "is_secure", "(", ")", "]", "host", "=", "request", ".", "get_host", "(", ")", "service", "=", "protocol", "+", "host", "+", "request", ".", "path", "if", "redirect_to", ":", "if", "'?'", "in", "service", ":", "service", "+=", "'&'", "else", ":", "service", "+=", "'?'", "if", "gateway", ":", "\"\"\" If gateway, capture params and reencode them before returning a url \"\"\"", "gateway_params", "=", "[", "(", "REDIRECT_FIELD_NAME", ",", "redirect_to", ")", ",", "(", "'gatewayed'", ",", "'true'", ")", "]", "query_dict", "=", "request", ".", "GET", ".", "copy", "(", ")", "try", ":", "del", "query_dict", "[", "'ticket'", "]", "except", ":", "pass", "query_list", "=", "query_dict", ".", "items", "(", ")", "# remove duplicate params", "for", "item", "in", "query_list", ":", "for", "index", ",", "item2", "in", "enumerate", "(", "gateway_params", ")", ":", "if", "item", "[", "0", "]", "==", "item2", "[", "0", "]", ":", "gateway_params", ".", "pop", "(", "index", ")", "extra_params", "=", "gateway_params", "+", "query_list", "#Sort params by key name so they are always in the same order.", "sorted_params", "=", "sorted", "(", "extra_params", ",", "key", "=", "itemgetter", "(", "0", ")", ")", "service", "+=", "urlencode", "(", "sorted_params", ")", "else", ":", "service", "+=", "urlencode", "(", "{", "REDIRECT_FIELD_NAME", ":", "redirect_to", "}", ")", "return", "service" ]
Generates application service URL for CAS :param: request Request Object :param: redirect_to URL to redriect to :param: gateway Should this be a gatewayed pass through
[ "Generates", "application", "service", "URL", "for", "CAS" ]
8a871093966f001b4dadf7d097ac326169f3c066
https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/views.py#L32-L79
18,134
kstateome/django-cas
cas/views.py
proxy_callback
def proxy_callback(request): """Handles CAS 2.0+ XML-based proxy callback call. Stores the proxy granting ticket in the database for future use. NB: Use created and set it in python in case database has issues with setting up the default timestamp value """ pgtIou = request.GET.get('pgtIou') tgt = request.GET.get('pgtId') if not (pgtIou and tgt): logger.info('No pgtIou or tgt found in request.GET') return HttpResponse('No pgtIOO', content_type="text/plain") try: PgtIOU.objects.create(tgt=tgt, pgtIou=pgtIou, created=datetime.datetime.now()) request.session['pgt-TICKET'] = pgtIou return HttpResponse('PGT ticket is: {ticket}'.format(ticket=pgtIou), content_type="text/plain") except Exception as e: logger.warning('PGT storage failed. {message}'.format( message=e )) return HttpResponse('PGT storage failed for {request}'.format(request=str(request.GET)), content_type="text/plain")
python
def proxy_callback(request): """Handles CAS 2.0+ XML-based proxy callback call. Stores the proxy granting ticket in the database for future use. NB: Use created and set it in python in case database has issues with setting up the default timestamp value """ pgtIou = request.GET.get('pgtIou') tgt = request.GET.get('pgtId') if not (pgtIou and tgt): logger.info('No pgtIou or tgt found in request.GET') return HttpResponse('No pgtIOO', content_type="text/plain") try: PgtIOU.objects.create(tgt=tgt, pgtIou=pgtIou, created=datetime.datetime.now()) request.session['pgt-TICKET'] = pgtIou return HttpResponse('PGT ticket is: {ticket}'.format(ticket=pgtIou), content_type="text/plain") except Exception as e: logger.warning('PGT storage failed. {message}'.format( message=e )) return HttpResponse('PGT storage failed for {request}'.format(request=str(request.GET)), content_type="text/plain")
[ "def", "proxy_callback", "(", "request", ")", ":", "pgtIou", "=", "request", ".", "GET", ".", "get", "(", "'pgtIou'", ")", "tgt", "=", "request", ".", "GET", ".", "get", "(", "'pgtId'", ")", "if", "not", "(", "pgtIou", "and", "tgt", ")", ":", "logger", ".", "info", "(", "'No pgtIou or tgt found in request.GET'", ")", "return", "HttpResponse", "(", "'No pgtIOO'", ",", "content_type", "=", "\"text/plain\"", ")", "try", ":", "PgtIOU", ".", "objects", ".", "create", "(", "tgt", "=", "tgt", ",", "pgtIou", "=", "pgtIou", ",", "created", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ")", "request", ".", "session", "[", "'pgt-TICKET'", "]", "=", "pgtIou", "return", "HttpResponse", "(", "'PGT ticket is: {ticket}'", ".", "format", "(", "ticket", "=", "pgtIou", ")", ",", "content_type", "=", "\"text/plain\"", ")", "except", "Exception", "as", "e", ":", "logger", ".", "warning", "(", "'PGT storage failed. {message}'", ".", "format", "(", "message", "=", "e", ")", ")", "return", "HttpResponse", "(", "'PGT storage failed for {request}'", ".", "format", "(", "request", "=", "str", "(", "request", ".", "GET", ")", ")", ",", "content_type", "=", "\"text/plain\"", ")" ]
Handles CAS 2.0+ XML-based proxy callback call. Stores the proxy granting ticket in the database for future use. NB: Use created and set it in python in case database has issues with setting up the default timestamp value
[ "Handles", "CAS", "2", ".", "0", "+", "XML", "-", "based", "proxy", "callback", "call", ".", "Stores", "the", "proxy", "granting", "ticket", "in", "the", "database", "for", "future", "use", "." ]
8a871093966f001b4dadf7d097ac326169f3c066
https://github.com/kstateome/django-cas/blob/8a871093966f001b4dadf7d097ac326169f3c066/cas/views.py#L245-L270
18,135
eventbrite/eventbrite-sdk-python
eventbrite/decorators.py
objectify
def objectify(func): """ Converts the returned value from a models.Payload to a models.EventbriteObject. Used by the access methods of the client.Eventbrite object """ @functools.wraps(func) def wrapper(*args, **kwargs): try: payload = func(*args, **kwargs) except requests.exceptions.ConnectionError as e: raise InternetConnectionError(e) return EventbriteObject.create(payload) return wrapper
python
def objectify(func): """ Converts the returned value from a models.Payload to a models.EventbriteObject. Used by the access methods of the client.Eventbrite object """ @functools.wraps(func) def wrapper(*args, **kwargs): try: payload = func(*args, **kwargs) except requests.exceptions.ConnectionError as e: raise InternetConnectionError(e) return EventbriteObject.create(payload) return wrapper
[ "def", "objectify", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "payload", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "requests", ".", "exceptions", ".", "ConnectionError", "as", "e", ":", "raise", "InternetConnectionError", "(", "e", ")", "return", "EventbriteObject", ".", "create", "(", "payload", ")", "return", "wrapper" ]
Converts the returned value from a models.Payload to a models.EventbriteObject. Used by the access methods of the client.Eventbrite object
[ "Converts", "the", "returned", "value", "from", "a", "models", ".", "Payload", "to", "a", "models", ".", "EventbriteObject", ".", "Used", "by", "the", "access", "methods", "of", "the", "client", ".", "Eventbrite", "object" ]
f2e5dc5aa1aa3e45766de13f16fd65722163d91a
https://github.com/eventbrite/eventbrite-sdk-python/blob/f2e5dc5aa1aa3e45766de13f16fd65722163d91a/eventbrite/decorators.py#L9-L22
18,136
eventbrite/eventbrite-sdk-python
eventbrite/client.py
Eventbrite.get_user
def get_user(self, user_id=None): """ Returns a user for the specified user as user. GET users/:id/ :param int user_id: (optional) The id assigned to a user """ if user_id: return self.get('/users/{0}/'.format(user_id)) return self.get('/users/me/')
python
def get_user(self, user_id=None): """ Returns a user for the specified user as user. GET users/:id/ :param int user_id: (optional) The id assigned to a user """ if user_id: return self.get('/users/{0}/'.format(user_id)) return self.get('/users/me/')
[ "def", "get_user", "(", "self", ",", "user_id", "=", "None", ")", ":", "if", "user_id", ":", "return", "self", ".", "get", "(", "'/users/{0}/'", ".", "format", "(", "user_id", ")", ")", "return", "self", ".", "get", "(", "'/users/me/'", ")" ]
Returns a user for the specified user as user. GET users/:id/ :param int user_id: (optional) The id assigned to a user
[ "Returns", "a", "user", "for", "the", "specified", "user", "as", "user", "." ]
f2e5dc5aa1aa3e45766de13f16fd65722163d91a
https://github.com/eventbrite/eventbrite-sdk-python/blob/f2e5dc5aa1aa3e45766de13f16fd65722163d91a/eventbrite/client.py#L94-L105
18,137
eventbrite/eventbrite-sdk-python
eventbrite/client.py
Eventbrite.get_event_attendees
def get_event_attendees(self, event_id, status=None, changed_since=None): """ Returns a paginated response with a key of attendees, containing a list of attendee. GET /events/:id/attendees/ """ data = {} if status: # TODO - check the types of valid status data['status'] = status if changed_since: data['changed_since'] = changed_since return self.get("/events/{0}/attendees/".format(event_id), data=data)
python
def get_event_attendees(self, event_id, status=None, changed_since=None): """ Returns a paginated response with a key of attendees, containing a list of attendee. GET /events/:id/attendees/ """ data = {} if status: # TODO - check the types of valid status data['status'] = status if changed_since: data['changed_since'] = changed_since return self.get("/events/{0}/attendees/".format(event_id), data=data)
[ "def", "get_event_attendees", "(", "self", ",", "event_id", ",", "status", "=", "None", ",", "changed_since", "=", "None", ")", ":", "data", "=", "{", "}", "if", "status", ":", "# TODO - check the types of valid status", "data", "[", "'status'", "]", "=", "status", "if", "changed_since", ":", "data", "[", "'changed_since'", "]", "=", "changed_since", "return", "self", ".", "get", "(", "\"/events/{0}/attendees/\"", ".", "format", "(", "event_id", ")", ",", "data", "=", "data", ")" ]
Returns a paginated response with a key of attendees, containing a list of attendee. GET /events/:id/attendees/
[ "Returns", "a", "paginated", "response", "with", "a", "key", "of", "attendees", "containing", "a", "list", "of", "attendee", "." ]
f2e5dc5aa1aa3e45766de13f16fd65722163d91a
https://github.com/eventbrite/eventbrite-sdk-python/blob/f2e5dc5aa1aa3e45766de13f16fd65722163d91a/eventbrite/client.py#L133-L145
18,138
eventbrite/eventbrite-sdk-python
eventbrite/client.py
Eventbrite.webhook_to_object
def webhook_to_object(self, webhook): """ Converts JSON sent by an Eventbrite Webhook to the appropriate Eventbrite object. # TODO - Add capability to handle Django request objects """ if isinstance(webhook, string_type): # If still JSON, convert to a Python dict webhook = json.dumps(webhook) # if a flask.Request object, try to convert that to a webhook if not isinstance(webhook, dict): webhook = get_webhook_from_request(webhook) try: webhook['api_url'] except KeyError: raise InvalidWebhook payload = self.get(webhook['api_url']) return payload
python
def webhook_to_object(self, webhook): """ Converts JSON sent by an Eventbrite Webhook to the appropriate Eventbrite object. # TODO - Add capability to handle Django request objects """ if isinstance(webhook, string_type): # If still JSON, convert to a Python dict webhook = json.dumps(webhook) # if a flask.Request object, try to convert that to a webhook if not isinstance(webhook, dict): webhook = get_webhook_from_request(webhook) try: webhook['api_url'] except KeyError: raise InvalidWebhook payload = self.get(webhook['api_url']) return payload
[ "def", "webhook_to_object", "(", "self", ",", "webhook", ")", ":", "if", "isinstance", "(", "webhook", ",", "string_type", ")", ":", "# If still JSON, convert to a Python dict", "webhook", "=", "json", ".", "dumps", "(", "webhook", ")", "# if a flask.Request object, try to convert that to a webhook", "if", "not", "isinstance", "(", "webhook", ",", "dict", ")", ":", "webhook", "=", "get_webhook_from_request", "(", "webhook", ")", "try", ":", "webhook", "[", "'api_url'", "]", "except", "KeyError", ":", "raise", "InvalidWebhook", "payload", "=", "self", ".", "get", "(", "webhook", "[", "'api_url'", "]", ")", "return", "payload" ]
Converts JSON sent by an Eventbrite Webhook to the appropriate Eventbrite object. # TODO - Add capability to handle Django request objects
[ "Converts", "JSON", "sent", "by", "an", "Eventbrite", "Webhook", "to", "the", "appropriate", "Eventbrite", "object", "." ]
f2e5dc5aa1aa3e45766de13f16fd65722163d91a
https://github.com/eventbrite/eventbrite-sdk-python/blob/f2e5dc5aa1aa3e45766de13f16fd65722163d91a/eventbrite/client.py#L227-L249
18,139
eventbrite/eventbrite-sdk-python
utils/generate_access_methods.py
get_params_from_page
def get_params_from_page(path, file_name, method_count): """ This function accesses the rendered content. We must do this because how the params are not defined in the docs, but rather the rendered HTML """ # open the rendered file. file_name = file_name.replace(".rst", "") file_path = "{0}/../_build/html/endpoints/{1}/index.html".format( path, file_name) soup = bs4.BeautifulSoup(open(file_path)) # Pull out the relevant section section = soup.find_all('div', class_='section')[method_count] # get the tbody of the params table tbody = section.find('tbody') params = [] if tbody is not None: for row in tbody.find_all('tr'): name, param_type, required, description = row.find_all('td') required = required.text == 'Yes' param = dict( name=name.text, type=param_type.text, required=required, description=description.text ) params.append(param) params = sorted(params, key=lambda k: not k['required']) return params
python
def get_params_from_page(path, file_name, method_count): """ This function accesses the rendered content. We must do this because how the params are not defined in the docs, but rather the rendered HTML """ # open the rendered file. file_name = file_name.replace(".rst", "") file_path = "{0}/../_build/html/endpoints/{1}/index.html".format( path, file_name) soup = bs4.BeautifulSoup(open(file_path)) # Pull out the relevant section section = soup.find_all('div', class_='section')[method_count] # get the tbody of the params table tbody = section.find('tbody') params = [] if tbody is not None: for row in tbody.find_all('tr'): name, param_type, required, description = row.find_all('td') required = required.text == 'Yes' param = dict( name=name.text, type=param_type.text, required=required, description=description.text ) params.append(param) params = sorted(params, key=lambda k: not k['required']) return params
[ "def", "get_params_from_page", "(", "path", ",", "file_name", ",", "method_count", ")", ":", "# open the rendered file.", "file_name", "=", "file_name", ".", "replace", "(", "\".rst\"", ",", "\"\"", ")", "file_path", "=", "\"{0}/../_build/html/endpoints/{1}/index.html\"", ".", "format", "(", "path", ",", "file_name", ")", "soup", "=", "bs4", ".", "BeautifulSoup", "(", "open", "(", "file_path", ")", ")", "# Pull out the relevant section", "section", "=", "soup", ".", "find_all", "(", "'div'", ",", "class_", "=", "'section'", ")", "[", "method_count", "]", "# get the tbody of the params table", "tbody", "=", "section", ".", "find", "(", "'tbody'", ")", "params", "=", "[", "]", "if", "tbody", "is", "not", "None", ":", "for", "row", "in", "tbody", ".", "find_all", "(", "'tr'", ")", ":", "name", ",", "param_type", ",", "required", ",", "description", "=", "row", ".", "find_all", "(", "'td'", ")", "required", "=", "required", ".", "text", "==", "'Yes'", "param", "=", "dict", "(", "name", "=", "name", ".", "text", ",", "type", "=", "param_type", ".", "text", ",", "required", "=", "required", ",", "description", "=", "description", ".", "text", ")", "params", ".", "append", "(", "param", ")", "params", "=", "sorted", "(", "params", ",", "key", "=", "lambda", "k", ":", "not", "k", "[", "'required'", "]", ")", "return", "params" ]
This function accesses the rendered content. We must do this because how the params are not defined in the docs, but rather the rendered HTML
[ "This", "function", "accesses", "the", "rendered", "content", ".", "We", "must", "do", "this", "because", "how", "the", "params", "are", "not", "defined", "in", "the", "docs", "but", "rather", "the", "rendered", "HTML" ]
f2e5dc5aa1aa3e45766de13f16fd65722163d91a
https://github.com/eventbrite/eventbrite-sdk-python/blob/f2e5dc5aa1aa3e45766de13f16fd65722163d91a/utils/generate_access_methods.py#L172-L201
18,140
robromano/django-adminrestrict
adminrestrict/middleware.py
AdminPagesRestrictMiddleware.process_request
def process_request(self, request): """ Check if the request is made form an allowed IP """ # Section adjusted to restrict login to ?edit # (sing cms-toolbar-login)into DjangoCMS login. restricted_request_uri = request.path.startswith( reverse('admin:index') or "cms-toolbar-login" in request.build_absolute_uri() ) if restricted_request_uri and request.method == 'POST': # AllowedIP table emty means access is always granted if AllowedIP.objects.count() > 0: # If there are wildcard IPs access is always granted if AllowedIP.objects.filter(ip_address="*").count() == 0: request_ip = get_ip_address_from_request(request) # If the request_ip is in the AllowedIP the access # is granted if AllowedIP.objects.filter(ip_address=request_ip).count() == 0: # We check regular expressions defining ranges # of IPs. If any range contains the request_ip # the access is granted for regex_ip_range in AllowedIP.objects.filter(ip_address__endswith="*"): if re.match(regex_ip_range.ip_address.replace("*", ".*"), request_ip): return None return HttpResponseForbidden("Access to admin is denied.")
python
def process_request(self, request): """ Check if the request is made form an allowed IP """ # Section adjusted to restrict login to ?edit # (sing cms-toolbar-login)into DjangoCMS login. restricted_request_uri = request.path.startswith( reverse('admin:index') or "cms-toolbar-login" in request.build_absolute_uri() ) if restricted_request_uri and request.method == 'POST': # AllowedIP table emty means access is always granted if AllowedIP.objects.count() > 0: # If there are wildcard IPs access is always granted if AllowedIP.objects.filter(ip_address="*").count() == 0: request_ip = get_ip_address_from_request(request) # If the request_ip is in the AllowedIP the access # is granted if AllowedIP.objects.filter(ip_address=request_ip).count() == 0: # We check regular expressions defining ranges # of IPs. If any range contains the request_ip # the access is granted for regex_ip_range in AllowedIP.objects.filter(ip_address__endswith="*"): if re.match(regex_ip_range.ip_address.replace("*", ".*"), request_ip): return None return HttpResponseForbidden("Access to admin is denied.")
[ "def", "process_request", "(", "self", ",", "request", ")", ":", "# Section adjusted to restrict login to ?edit", "# (sing cms-toolbar-login)into DjangoCMS login.", "restricted_request_uri", "=", "request", ".", "path", ".", "startswith", "(", "reverse", "(", "'admin:index'", ")", "or", "\"cms-toolbar-login\"", "in", "request", ".", "build_absolute_uri", "(", ")", ")", "if", "restricted_request_uri", "and", "request", ".", "method", "==", "'POST'", ":", "# AllowedIP table emty means access is always granted", "if", "AllowedIP", ".", "objects", ".", "count", "(", ")", ">", "0", ":", "# If there are wildcard IPs access is always granted", "if", "AllowedIP", ".", "objects", ".", "filter", "(", "ip_address", "=", "\"*\"", ")", ".", "count", "(", ")", "==", "0", ":", "request_ip", "=", "get_ip_address_from_request", "(", "request", ")", "# If the request_ip is in the AllowedIP the access", "# is granted", "if", "AllowedIP", ".", "objects", ".", "filter", "(", "ip_address", "=", "request_ip", ")", ".", "count", "(", ")", "==", "0", ":", "# We check regular expressions defining ranges", "# of IPs. If any range contains the request_ip", "# the access is granted", "for", "regex_ip_range", "in", "AllowedIP", ".", "objects", ".", "filter", "(", "ip_address__endswith", "=", "\"*\"", ")", ":", "if", "re", ".", "match", "(", "regex_ip_range", ".", "ip_address", ".", "replace", "(", "\"*\"", ",", "\".*\"", ")", ",", "request_ip", ")", ":", "return", "None", "return", "HttpResponseForbidden", "(", "\"Access to admin is denied.\"", ")" ]
Check if the request is made form an allowed IP
[ "Check", "if", "the", "request", "is", "made", "form", "an", "allowed", "IP" ]
f05fd21e49677731e3d291da956b84bcac9a5c69
https://github.com/robromano/django-adminrestrict/blob/f05fd21e49677731e3d291da956b84bcac9a5c69/adminrestrict/middleware.py#L87-L116
18,141
pydanny-archive/django-wysiwyg
django_wysiwyg/templatetags/wysiwyg.py
get_settings
def get_settings(editor_override=None): """Utility function to retrieve settings.py values with defaults""" flavor = getattr(settings, "DJANGO_WYSIWYG_FLAVOR", "yui") if editor_override is not None: flavor = editor_override return { "DJANGO_WYSIWYG_MEDIA_URL": getattr(settings, "DJANGO_WYSIWYG_MEDIA_URL", urljoin(settings.STATIC_URL, flavor) + '/'), "DJANGO_WYSIWYG_FLAVOR": flavor, }
python
def get_settings(editor_override=None): """Utility function to retrieve settings.py values with defaults""" flavor = getattr(settings, "DJANGO_WYSIWYG_FLAVOR", "yui") if editor_override is not None: flavor = editor_override return { "DJANGO_WYSIWYG_MEDIA_URL": getattr(settings, "DJANGO_WYSIWYG_MEDIA_URL", urljoin(settings.STATIC_URL, flavor) + '/'), "DJANGO_WYSIWYG_FLAVOR": flavor, }
[ "def", "get_settings", "(", "editor_override", "=", "None", ")", ":", "flavor", "=", "getattr", "(", "settings", ",", "\"DJANGO_WYSIWYG_FLAVOR\"", ",", "\"yui\"", ")", "if", "editor_override", "is", "not", "None", ":", "flavor", "=", "editor_override", "return", "{", "\"DJANGO_WYSIWYG_MEDIA_URL\"", ":", "getattr", "(", "settings", ",", "\"DJANGO_WYSIWYG_MEDIA_URL\"", ",", "urljoin", "(", "settings", ".", "STATIC_URL", ",", "flavor", ")", "+", "'/'", ")", ",", "\"DJANGO_WYSIWYG_FLAVOR\"", ":", "flavor", ",", "}" ]
Utility function to retrieve settings.py values with defaults
[ "Utility", "function", "to", "retrieve", "settings", ".", "py", "values", "with", "defaults" ]
f05866356d417309624ec4863acdebd2084b1bc2
https://github.com/pydanny-archive/django-wysiwyg/blob/f05866356d417309624ec4863acdebd2084b1bc2/django_wysiwyg/templatetags/wysiwyg.py#L13-L23
18,142
paragbaxi/qualysapi
qualysapi/config.py
QualysConnectConfig.get_auth
def get_auth(self): ''' Returns username from the configfile. ''' return (self._cfgparse.get(self._section, 'username'), self._cfgparse.get(self._section, 'password'))
python
def get_auth(self): ''' Returns username from the configfile. ''' return (self._cfgparse.get(self._section, 'username'), self._cfgparse.get(self._section, 'password'))
[ "def", "get_auth", "(", "self", ")", ":", "return", "(", "self", ".", "_cfgparse", ".", "get", "(", "self", ".", "_section", ",", "'username'", ")", ",", "self", ".", "_cfgparse", ".", "get", "(", "self", ".", "_section", ",", "'password'", ")", ")" ]
Returns username from the configfile.
[ "Returns", "username", "from", "the", "configfile", "." ]
2c8bf1d5d300117403062885c8e10b5665eb4615
https://github.com/paragbaxi/qualysapi/blob/2c8bf1d5d300117403062885c8e10b5665eb4615/qualysapi/config.py#L211-L213
18,143
paragbaxi/qualysapi
qualysapi/util.py
connect
def connect(config_file=qcs.default_filename, section='info', remember_me=False, remember_me_always=False): """ Return a QGAPIConnect object for v1 API pulling settings from config file. """ # Retrieve login credentials. conf = qcconf.QualysConnectConfig(filename=config_file, section=section, remember_me=remember_me, remember_me_always=remember_me_always) connect = qcconn.QGConnector(conf.get_auth(), conf.get_hostname(), conf.proxies, conf.max_retries) logger.info("Finished building connector.") return connect
python
def connect(config_file=qcs.default_filename, section='info', remember_me=False, remember_me_always=False): """ Return a QGAPIConnect object for v1 API pulling settings from config file. """ # Retrieve login credentials. conf = qcconf.QualysConnectConfig(filename=config_file, section=section, remember_me=remember_me, remember_me_always=remember_me_always) connect = qcconn.QGConnector(conf.get_auth(), conf.get_hostname(), conf.proxies, conf.max_retries) logger.info("Finished building connector.") return connect
[ "def", "connect", "(", "config_file", "=", "qcs", ".", "default_filename", ",", "section", "=", "'info'", ",", "remember_me", "=", "False", ",", "remember_me_always", "=", "False", ")", ":", "# Retrieve login credentials.", "conf", "=", "qcconf", ".", "QualysConnectConfig", "(", "filename", "=", "config_file", ",", "section", "=", "section", ",", "remember_me", "=", "remember_me", ",", "remember_me_always", "=", "remember_me_always", ")", "connect", "=", "qcconn", ".", "QGConnector", "(", "conf", ".", "get_auth", "(", ")", ",", "conf", ".", "get_hostname", "(", ")", ",", "conf", ".", "proxies", ",", "conf", ".", "max_retries", ")", "logger", ".", "info", "(", "\"Finished building connector.\"", ")", "return", "connect" ]
Return a QGAPIConnect object for v1 API pulling settings from config file.
[ "Return", "a", "QGAPIConnect", "object", "for", "v1", "API", "pulling", "settings", "from", "config", "file", "." ]
2c8bf1d5d300117403062885c8e10b5665eb4615
https://github.com/paragbaxi/qualysapi/blob/2c8bf1d5d300117403062885c8e10b5665eb4615/qualysapi/util.py#L18-L30
18,144
paragbaxi/qualysapi
qualysapi/connector.py
QGConnector.format_api_version
def format_api_version(self, api_version): """ Return QualysGuard API version for api_version specified. """ # Convert to int. if type(api_version) == str: api_version = api_version.lower() if api_version[0] == 'v' and api_version[1].isdigit(): # Remove first 'v' in case the user typed 'v1' or 'v2', etc. api_version = api_version[1:] # Check for input matching Qualys modules. if api_version in ('asset management', 'assets', 'tag', 'tagging', 'tags'): # Convert to Asset Management API. api_version = 'am' elif api_version in ('am2'): # Convert to Asset Management API v2 api_version = 'am2' elif api_version in ('webapp', 'web application scanning', 'webapp scanning'): # Convert to WAS API. api_version = 'was' elif api_version in ('pol', 'pc'): # Convert PC module to API number 2. api_version = 2 else: api_version = int(api_version) return api_version
python
def format_api_version(self, api_version): """ Return QualysGuard API version for api_version specified. """ # Convert to int. if type(api_version) == str: api_version = api_version.lower() if api_version[0] == 'v' and api_version[1].isdigit(): # Remove first 'v' in case the user typed 'v1' or 'v2', etc. api_version = api_version[1:] # Check for input matching Qualys modules. if api_version in ('asset management', 'assets', 'tag', 'tagging', 'tags'): # Convert to Asset Management API. api_version = 'am' elif api_version in ('am2'): # Convert to Asset Management API v2 api_version = 'am2' elif api_version in ('webapp', 'web application scanning', 'webapp scanning'): # Convert to WAS API. api_version = 'was' elif api_version in ('pol', 'pc'): # Convert PC module to API number 2. api_version = 2 else: api_version = int(api_version) return api_version
[ "def", "format_api_version", "(", "self", ",", "api_version", ")", ":", "# Convert to int.", "if", "type", "(", "api_version", ")", "==", "str", ":", "api_version", "=", "api_version", ".", "lower", "(", ")", "if", "api_version", "[", "0", "]", "==", "'v'", "and", "api_version", "[", "1", "]", ".", "isdigit", "(", ")", ":", "# Remove first 'v' in case the user typed 'v1' or 'v2', etc.", "api_version", "=", "api_version", "[", "1", ":", "]", "# Check for input matching Qualys modules.", "if", "api_version", "in", "(", "'asset management'", ",", "'assets'", ",", "'tag'", ",", "'tagging'", ",", "'tags'", ")", ":", "# Convert to Asset Management API.", "api_version", "=", "'am'", "elif", "api_version", "in", "(", "'am2'", ")", ":", "# Convert to Asset Management API v2", "api_version", "=", "'am2'", "elif", "api_version", "in", "(", "'webapp'", ",", "'web application scanning'", ",", "'webapp scanning'", ")", ":", "# Convert to WAS API.", "api_version", "=", "'was'", "elif", "api_version", "in", "(", "'pol'", ",", "'pc'", ")", ":", "# Convert PC module to API number 2.", "api_version", "=", "2", "else", ":", "api_version", "=", "int", "(", "api_version", ")", "return", "api_version" ]
Return QualysGuard API version for api_version specified.
[ "Return", "QualysGuard", "API", "version", "for", "api_version", "specified", "." ]
2c8bf1d5d300117403062885c8e10b5665eb4615
https://github.com/paragbaxi/qualysapi/blob/2c8bf1d5d300117403062885c8e10b5665eb4615/qualysapi/connector.py#L72-L97
18,145
paragbaxi/qualysapi
qualysapi/connector.py
QGConnector.which_api_version
def which_api_version(self, api_call): """ Return QualysGuard API version for api_call specified. """ # Leverage patterns of calls to API methods. if api_call.endswith('.php'): # API v1. return 1 elif api_call.startswith('api/2.0/'): # API v2. return 2 elif '/am/' in api_call: # Asset Management API. return 'am' elif '/was/' in api_call: # WAS API. return 'was' return False
python
def which_api_version(self, api_call): """ Return QualysGuard API version for api_call specified. """ # Leverage patterns of calls to API methods. if api_call.endswith('.php'): # API v1. return 1 elif api_call.startswith('api/2.0/'): # API v2. return 2 elif '/am/' in api_call: # Asset Management API. return 'am' elif '/was/' in api_call: # WAS API. return 'was' return False
[ "def", "which_api_version", "(", "self", ",", "api_call", ")", ":", "# Leverage patterns of calls to API methods.", "if", "api_call", ".", "endswith", "(", "'.php'", ")", ":", "# API v1.", "return", "1", "elif", "api_call", ".", "startswith", "(", "'api/2.0/'", ")", ":", "# API v2.", "return", "2", "elif", "'/am/'", "in", "api_call", ":", "# Asset Management API.", "return", "'am'", "elif", "'/was/'", "in", "api_call", ":", "# WAS API.", "return", "'was'", "return", "False" ]
Return QualysGuard API version for api_call specified.
[ "Return", "QualysGuard", "API", "version", "for", "api_call", "specified", "." ]
2c8bf1d5d300117403062885c8e10b5665eb4615
https://github.com/paragbaxi/qualysapi/blob/2c8bf1d5d300117403062885c8e10b5665eb4615/qualysapi/connector.py#L99-L116
18,146
paragbaxi/qualysapi
qualysapi/connector.py
QGConnector.url_api_version
def url_api_version(self, api_version): """ Return base API url string for the QualysGuard api_version and server. """ # Set base url depending on API version. if api_version == 1: # QualysGuard API v1 url. url = "https://%s/msp/" % (self.server,) elif api_version == 2: # QualysGuard API v2 url. url = "https://%s/" % (self.server,) elif api_version == 'was': # QualysGuard REST v3 API url (Portal API). url = "https://%s/qps/rest/3.0/" % (self.server,) elif api_version == 'am': # QualysGuard REST v1 API url (Portal API). url = "https://%s/qps/rest/1.0/" % (self.server,) elif api_version == 'am2': # QualysGuard REST v1 API url (Portal API). url = "https://%s/qps/rest/2.0/" % (self.server,) else: raise Exception("Unknown QualysGuard API Version Number (%s)" % (api_version,)) logger.debug("Base url =\n%s" % (url)) return url
python
def url_api_version(self, api_version): """ Return base API url string for the QualysGuard api_version and server. """ # Set base url depending on API version. if api_version == 1: # QualysGuard API v1 url. url = "https://%s/msp/" % (self.server,) elif api_version == 2: # QualysGuard API v2 url. url = "https://%s/" % (self.server,) elif api_version == 'was': # QualysGuard REST v3 API url (Portal API). url = "https://%s/qps/rest/3.0/" % (self.server,) elif api_version == 'am': # QualysGuard REST v1 API url (Portal API). url = "https://%s/qps/rest/1.0/" % (self.server,) elif api_version == 'am2': # QualysGuard REST v1 API url (Portal API). url = "https://%s/qps/rest/2.0/" % (self.server,) else: raise Exception("Unknown QualysGuard API Version Number (%s)" % (api_version,)) logger.debug("Base url =\n%s" % (url)) return url
[ "def", "url_api_version", "(", "self", ",", "api_version", ")", ":", "# Set base url depending on API version.", "if", "api_version", "==", "1", ":", "# QualysGuard API v1 url.", "url", "=", "\"https://%s/msp/\"", "%", "(", "self", ".", "server", ",", ")", "elif", "api_version", "==", "2", ":", "# QualysGuard API v2 url.", "url", "=", "\"https://%s/\"", "%", "(", "self", ".", "server", ",", ")", "elif", "api_version", "==", "'was'", ":", "# QualysGuard REST v3 API url (Portal API).", "url", "=", "\"https://%s/qps/rest/3.0/\"", "%", "(", "self", ".", "server", ",", ")", "elif", "api_version", "==", "'am'", ":", "# QualysGuard REST v1 API url (Portal API).", "url", "=", "\"https://%s/qps/rest/1.0/\"", "%", "(", "self", ".", "server", ",", ")", "elif", "api_version", "==", "'am2'", ":", "# QualysGuard REST v1 API url (Portal API).", "url", "=", "\"https://%s/qps/rest/2.0/\"", "%", "(", "self", ".", "server", ",", ")", "else", ":", "raise", "Exception", "(", "\"Unknown QualysGuard API Version Number (%s)\"", "%", "(", "api_version", ",", ")", ")", "logger", ".", "debug", "(", "\"Base url =\\n%s\"", "%", "(", "url", ")", ")", "return", "url" ]
Return base API url string for the QualysGuard api_version and server.
[ "Return", "base", "API", "url", "string", "for", "the", "QualysGuard", "api_version", "and", "server", "." ]
2c8bf1d5d300117403062885c8e10b5665eb4615
https://github.com/paragbaxi/qualysapi/blob/2c8bf1d5d300117403062885c8e10b5665eb4615/qualysapi/connector.py#L118-L141
18,147
paragbaxi/qualysapi
qualysapi/connector.py
QGConnector.format_http_method
def format_http_method(self, api_version, api_call, data): """ Return QualysGuard API http method, with POST preferred.. """ # Define get methods for automatic http request methodology. # # All API v2 requests are POST methods. if api_version == 2: return 'post' elif api_version == 1: if api_call in self.api_methods['1 post']: return 'post' else: return 'get' elif api_version == 'was': # WAS API call. # Because WAS API enables user to GET API resources in URI, let's chop off the resource. # '/download/was/report/18823' --> '/download/was/report/' api_call_endpoint = api_call[:api_call.rfind('/') + 1] if api_call_endpoint in self.api_methods['was get']: return 'get' # Post calls with no payload will result in HTTPError: 415 Client Error: Unsupported Media Type. if data is None: # No post data. Some calls change to GET with no post data. if api_call_endpoint in self.api_methods['was no data get']: return 'get' else: return 'post' else: # Call with post data. return 'post' else: # Asset Management API call. if api_call in self.api_methods['am get']: return 'get' else: return 'post'
python
def format_http_method(self, api_version, api_call, data): """ Return QualysGuard API http method, with POST preferred.. """ # Define get methods for automatic http request methodology. # # All API v2 requests are POST methods. if api_version == 2: return 'post' elif api_version == 1: if api_call in self.api_methods['1 post']: return 'post' else: return 'get' elif api_version == 'was': # WAS API call. # Because WAS API enables user to GET API resources in URI, let's chop off the resource. # '/download/was/report/18823' --> '/download/was/report/' api_call_endpoint = api_call[:api_call.rfind('/') + 1] if api_call_endpoint in self.api_methods['was get']: return 'get' # Post calls with no payload will result in HTTPError: 415 Client Error: Unsupported Media Type. if data is None: # No post data. Some calls change to GET with no post data. if api_call_endpoint in self.api_methods['was no data get']: return 'get' else: return 'post' else: # Call with post data. return 'post' else: # Asset Management API call. if api_call in self.api_methods['am get']: return 'get' else: return 'post'
[ "def", "format_http_method", "(", "self", ",", "api_version", ",", "api_call", ",", "data", ")", ":", "# Define get methods for automatic http request methodology.", "#", "# All API v2 requests are POST methods.", "if", "api_version", "==", "2", ":", "return", "'post'", "elif", "api_version", "==", "1", ":", "if", "api_call", "in", "self", ".", "api_methods", "[", "'1 post'", "]", ":", "return", "'post'", "else", ":", "return", "'get'", "elif", "api_version", "==", "'was'", ":", "# WAS API call.", "# Because WAS API enables user to GET API resources in URI, let's chop off the resource.", "# '/download/was/report/18823' --> '/download/was/report/'", "api_call_endpoint", "=", "api_call", "[", ":", "api_call", ".", "rfind", "(", "'/'", ")", "+", "1", "]", "if", "api_call_endpoint", "in", "self", ".", "api_methods", "[", "'was get'", "]", ":", "return", "'get'", "# Post calls with no payload will result in HTTPError: 415 Client Error: Unsupported Media Type.", "if", "data", "is", "None", ":", "# No post data. Some calls change to GET with no post data.", "if", "api_call_endpoint", "in", "self", ".", "api_methods", "[", "'was no data get'", "]", ":", "return", "'get'", "else", ":", "return", "'post'", "else", ":", "# Call with post data.", "return", "'post'", "else", ":", "# Asset Management API call.", "if", "api_call", "in", "self", ".", "api_methods", "[", "'am get'", "]", ":", "return", "'get'", "else", ":", "return", "'post'" ]
Return QualysGuard API http method, with POST preferred..
[ "Return", "QualysGuard", "API", "http", "method", "with", "POST", "preferred", ".." ]
2c8bf1d5d300117403062885c8e10b5665eb4615
https://github.com/paragbaxi/qualysapi/blob/2c8bf1d5d300117403062885c8e10b5665eb4615/qualysapi/connector.py#L143-L179
18,148
paragbaxi/qualysapi
qualysapi/connector.py
QGConnector.preformat_call
def preformat_call(self, api_call): """ Return properly formatted QualysGuard API call. """ # Remove possible starting slashes or trailing question marks in call. api_call_formatted = api_call.lstrip('/') api_call_formatted = api_call_formatted.rstrip('?') if api_call != api_call_formatted: # Show difference logger.debug('api_call post strip =\n%s' % api_call_formatted) return api_call_formatted
python
def preformat_call(self, api_call): """ Return properly formatted QualysGuard API call. """ # Remove possible starting slashes or trailing question marks in call. api_call_formatted = api_call.lstrip('/') api_call_formatted = api_call_formatted.rstrip('?') if api_call != api_call_formatted: # Show difference logger.debug('api_call post strip =\n%s' % api_call_formatted) return api_call_formatted
[ "def", "preformat_call", "(", "self", ",", "api_call", ")", ":", "# Remove possible starting slashes or trailing question marks in call.", "api_call_formatted", "=", "api_call", ".", "lstrip", "(", "'/'", ")", "api_call_formatted", "=", "api_call_formatted", ".", "rstrip", "(", "'?'", ")", "if", "api_call", "!=", "api_call_formatted", ":", "# Show difference", "logger", ".", "debug", "(", "'api_call post strip =\\n%s'", "%", "api_call_formatted", ")", "return", "api_call_formatted" ]
Return properly formatted QualysGuard API call.
[ "Return", "properly", "formatted", "QualysGuard", "API", "call", "." ]
2c8bf1d5d300117403062885c8e10b5665eb4615
https://github.com/paragbaxi/qualysapi/blob/2c8bf1d5d300117403062885c8e10b5665eb4615/qualysapi/connector.py#L181-L191
18,149
paragbaxi/qualysapi
qualysapi/connector.py
QGConnector.format_call
def format_call(self, api_version, api_call): """ Return properly formatted QualysGuard API call according to api_version etiquette. """ # Remove possible starting slashes or trailing question marks in call. api_call = api_call.lstrip('/') api_call = api_call.rstrip('?') logger.debug('api_call post strip =\n%s' % api_call) # Make sure call always ends in slash for API v2 calls. if (api_version == 2 and api_call[-1] != '/'): # Add slash. logger.debug('Adding "/" to api_call.') api_call += '/' if api_call in self.api_methods_with_trailing_slash[api_version]: # Add slash. logger.debug('Adding "/" to api_call.') api_call += '/' return api_call
python
def format_call(self, api_version, api_call): """ Return properly formatted QualysGuard API call according to api_version etiquette. """ # Remove possible starting slashes or trailing question marks in call. api_call = api_call.lstrip('/') api_call = api_call.rstrip('?') logger.debug('api_call post strip =\n%s' % api_call) # Make sure call always ends in slash for API v2 calls. if (api_version == 2 and api_call[-1] != '/'): # Add slash. logger.debug('Adding "/" to api_call.') api_call += '/' if api_call in self.api_methods_with_trailing_slash[api_version]: # Add slash. logger.debug('Adding "/" to api_call.') api_call += '/' return api_call
[ "def", "format_call", "(", "self", ",", "api_version", ",", "api_call", ")", ":", "# Remove possible starting slashes or trailing question marks in call.", "api_call", "=", "api_call", ".", "lstrip", "(", "'/'", ")", "api_call", "=", "api_call", ".", "rstrip", "(", "'?'", ")", "logger", ".", "debug", "(", "'api_call post strip =\\n%s'", "%", "api_call", ")", "# Make sure call always ends in slash for API v2 calls.", "if", "(", "api_version", "==", "2", "and", "api_call", "[", "-", "1", "]", "!=", "'/'", ")", ":", "# Add slash.", "logger", ".", "debug", "(", "'Adding \"/\" to api_call.'", ")", "api_call", "+=", "'/'", "if", "api_call", "in", "self", ".", "api_methods_with_trailing_slash", "[", "api_version", "]", ":", "# Add slash.", "logger", ".", "debug", "(", "'Adding \"/\" to api_call.'", ")", "api_call", "+=", "'/'", "return", "api_call" ]
Return properly formatted QualysGuard API call according to api_version etiquette.
[ "Return", "properly", "formatted", "QualysGuard", "API", "call", "according", "to", "api_version", "etiquette", "." ]
2c8bf1d5d300117403062885c8e10b5665eb4615
https://github.com/paragbaxi/qualysapi/blob/2c8bf1d5d300117403062885c8e10b5665eb4615/qualysapi/connector.py#L193-L210
18,150
paragbaxi/qualysapi
qualysapi/connector.py
QGConnector.format_payload
def format_payload(self, api_version, data): """ Return appropriate QualysGuard API call. """ # Check if payload is for API v1 or API v2. if (api_version in (1, 2)): # Check if string type. if type(data) == str: # Convert to dictionary. logger.debug('Converting string to dict:\n%s' % data) # Remove possible starting question mark & ending ampersands. data = data.lstrip('?') data = data.rstrip('&') # Convert to dictionary. data = parse_qs(data) logger.debug('Converted:\n%s' % str(data)) elif api_version in ('am', 'was', 'am2'): if type(data) == etree._Element: logger.debug('Converting lxml.builder.E to string') data = etree.tostring(data) logger.debug('Converted:\n%s' % data) return data
python
def format_payload(self, api_version, data): """ Return appropriate QualysGuard API call. """ # Check if payload is for API v1 or API v2. if (api_version in (1, 2)): # Check if string type. if type(data) == str: # Convert to dictionary. logger.debug('Converting string to dict:\n%s' % data) # Remove possible starting question mark & ending ampersands. data = data.lstrip('?') data = data.rstrip('&') # Convert to dictionary. data = parse_qs(data) logger.debug('Converted:\n%s' % str(data)) elif api_version in ('am', 'was', 'am2'): if type(data) == etree._Element: logger.debug('Converting lxml.builder.E to string') data = etree.tostring(data) logger.debug('Converted:\n%s' % data) return data
[ "def", "format_payload", "(", "self", ",", "api_version", ",", "data", ")", ":", "# Check if payload is for API v1 or API v2.", "if", "(", "api_version", "in", "(", "1", ",", "2", ")", ")", ":", "# Check if string type.", "if", "type", "(", "data", ")", "==", "str", ":", "# Convert to dictionary.", "logger", ".", "debug", "(", "'Converting string to dict:\\n%s'", "%", "data", ")", "# Remove possible starting question mark & ending ampersands.", "data", "=", "data", ".", "lstrip", "(", "'?'", ")", "data", "=", "data", ".", "rstrip", "(", "'&'", ")", "# Convert to dictionary.", "data", "=", "parse_qs", "(", "data", ")", "logger", ".", "debug", "(", "'Converted:\\n%s'", "%", "str", "(", "data", ")", ")", "elif", "api_version", "in", "(", "'am'", ",", "'was'", ",", "'am2'", ")", ":", "if", "type", "(", "data", ")", "==", "etree", ".", "_Element", ":", "logger", ".", "debug", "(", "'Converting lxml.builder.E to string'", ")", "data", "=", "etree", ".", "tostring", "(", "data", ")", "logger", ".", "debug", "(", "'Converted:\\n%s'", "%", "data", ")", "return", "data" ]
Return appropriate QualysGuard API call.
[ "Return", "appropriate", "QualysGuard", "API", "call", "." ]
2c8bf1d5d300117403062885c8e10b5665eb4615
https://github.com/paragbaxi/qualysapi/blob/2c8bf1d5d300117403062885c8e10b5665eb4615/qualysapi/connector.py#L212-L233
18,151
tox-dev/tox-travis
src/tox_travis/after.py
travis_after
def travis_after(ini, envlist): """Wait for all jobs to finish, then exit successfully.""" # after-all disabled for pull requests if os.environ.get('TRAVIS_PULL_REQUEST', 'false') != 'false': return if not after_config_matches(ini, envlist): return # This is not the one that needs to wait github_token = os.environ.get('GITHUB_TOKEN') if not github_token: print('No GitHub token given.', file=sys.stderr) sys.exit(NO_GITHUB_TOKEN) api_url = os.environ.get('TRAVIS_API_URL', 'https://api.travis-ci.org') build_id = os.environ.get('TRAVIS_BUILD_ID') job_number = os.environ.get('TRAVIS_JOB_NUMBER') try: polling_interval = int(os.environ.get('TRAVIS_POLLING_INTERVAL', 5)) except ValueError: print('Invalid polling interval given: {0}'.format( repr(os.environ.get('TRAVIS_POLLING_INTERVAL'))), file=sys.stderr) sys.exit(INVALID_POLLING_INTERVAL) if not all([api_url, build_id, job_number]): print('Required Travis environment not given.', file=sys.stderr) sys.exit(INCOMPLETE_TRAVIS_ENVIRONMENT) # This may raise an Exception, and it should be printed job_statuses = get_job_statuses( github_token, api_url, build_id, polling_interval, job_number) if not all(job_statuses): print('Some jobs were not successful.') sys.exit(JOBS_FAILED) print('All required jobs were successful.')
python
def travis_after(ini, envlist): """Wait for all jobs to finish, then exit successfully.""" # after-all disabled for pull requests if os.environ.get('TRAVIS_PULL_REQUEST', 'false') != 'false': return if not after_config_matches(ini, envlist): return # This is not the one that needs to wait github_token = os.environ.get('GITHUB_TOKEN') if not github_token: print('No GitHub token given.', file=sys.stderr) sys.exit(NO_GITHUB_TOKEN) api_url = os.environ.get('TRAVIS_API_URL', 'https://api.travis-ci.org') build_id = os.environ.get('TRAVIS_BUILD_ID') job_number = os.environ.get('TRAVIS_JOB_NUMBER') try: polling_interval = int(os.environ.get('TRAVIS_POLLING_INTERVAL', 5)) except ValueError: print('Invalid polling interval given: {0}'.format( repr(os.environ.get('TRAVIS_POLLING_INTERVAL'))), file=sys.stderr) sys.exit(INVALID_POLLING_INTERVAL) if not all([api_url, build_id, job_number]): print('Required Travis environment not given.', file=sys.stderr) sys.exit(INCOMPLETE_TRAVIS_ENVIRONMENT) # This may raise an Exception, and it should be printed job_statuses = get_job_statuses( github_token, api_url, build_id, polling_interval, job_number) if not all(job_statuses): print('Some jobs were not successful.') sys.exit(JOBS_FAILED) print('All required jobs were successful.')
[ "def", "travis_after", "(", "ini", ",", "envlist", ")", ":", "# after-all disabled for pull requests", "if", "os", ".", "environ", ".", "get", "(", "'TRAVIS_PULL_REQUEST'", ",", "'false'", ")", "!=", "'false'", ":", "return", "if", "not", "after_config_matches", "(", "ini", ",", "envlist", ")", ":", "return", "# This is not the one that needs to wait", "github_token", "=", "os", ".", "environ", ".", "get", "(", "'GITHUB_TOKEN'", ")", "if", "not", "github_token", ":", "print", "(", "'No GitHub token given.'", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "NO_GITHUB_TOKEN", ")", "api_url", "=", "os", ".", "environ", ".", "get", "(", "'TRAVIS_API_URL'", ",", "'https://api.travis-ci.org'", ")", "build_id", "=", "os", ".", "environ", ".", "get", "(", "'TRAVIS_BUILD_ID'", ")", "job_number", "=", "os", ".", "environ", ".", "get", "(", "'TRAVIS_JOB_NUMBER'", ")", "try", ":", "polling_interval", "=", "int", "(", "os", ".", "environ", ".", "get", "(", "'TRAVIS_POLLING_INTERVAL'", ",", "5", ")", ")", "except", "ValueError", ":", "print", "(", "'Invalid polling interval given: {0}'", ".", "format", "(", "repr", "(", "os", ".", "environ", ".", "get", "(", "'TRAVIS_POLLING_INTERVAL'", ")", ")", ")", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "INVALID_POLLING_INTERVAL", ")", "if", "not", "all", "(", "[", "api_url", ",", "build_id", ",", "job_number", "]", ")", ":", "print", "(", "'Required Travis environment not given.'", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "INCOMPLETE_TRAVIS_ENVIRONMENT", ")", "# This may raise an Exception, and it should be printed", "job_statuses", "=", "get_job_statuses", "(", "github_token", ",", "api_url", ",", "build_id", ",", "polling_interval", ",", "job_number", ")", "if", "not", "all", "(", "job_statuses", ")", ":", "print", "(", "'Some jobs were not successful.'", ")", "sys", ".", "exit", "(", "JOBS_FAILED", ")", "print", "(", "'All required jobs were successful.'", ")" ]
Wait for all jobs to finish, then exit successfully.
[ "Wait", "for", "all", "jobs", "to", "finish", "then", "exit", "successfully", "." ]
d97a966c19abb020298a7e4b91fe83dd1d0a4517
https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/after.py#L25-L62
18,152
tox-dev/tox-travis
src/tox_travis/after.py
after_config_matches
def after_config_matches(ini, envlist): """Determine if this job should wait for the others.""" section = ini.sections.get('travis:after', {}) if not section: return False # Never wait if it's not configured if 'envlist' in section or 'toxenv' in section: if 'toxenv' in section: print('The "toxenv" key of the [travis:after] section is ' 'deprecated in favor of the "envlist" key.', file=sys.stderr) toxenv = section.get('toxenv') required = set(split_env(section.get('envlist', toxenv) or '')) actual = set(envlist) if required - actual: return False # Translate travis requirements to env requirements env_requirements = [ (TRAVIS_FACTORS[factor], value) for factor, value in parse_dict(section.get('travis', '')).items() if factor in TRAVIS_FACTORS ] + [ (name, value) for name, value in parse_dict(section.get('env', '')).items() ] return all([ os.environ.get(name) == value for name, value in env_requirements ])
python
def after_config_matches(ini, envlist): """Determine if this job should wait for the others.""" section = ini.sections.get('travis:after', {}) if not section: return False # Never wait if it's not configured if 'envlist' in section or 'toxenv' in section: if 'toxenv' in section: print('The "toxenv" key of the [travis:after] section is ' 'deprecated in favor of the "envlist" key.', file=sys.stderr) toxenv = section.get('toxenv') required = set(split_env(section.get('envlist', toxenv) or '')) actual = set(envlist) if required - actual: return False # Translate travis requirements to env requirements env_requirements = [ (TRAVIS_FACTORS[factor], value) for factor, value in parse_dict(section.get('travis', '')).items() if factor in TRAVIS_FACTORS ] + [ (name, value) for name, value in parse_dict(section.get('env', '')).items() ] return all([ os.environ.get(name) == value for name, value in env_requirements ])
[ "def", "after_config_matches", "(", "ini", ",", "envlist", ")", ":", "section", "=", "ini", ".", "sections", ".", "get", "(", "'travis:after'", ",", "{", "}", ")", "if", "not", "section", ":", "return", "False", "# Never wait if it's not configured", "if", "'envlist'", "in", "section", "or", "'toxenv'", "in", "section", ":", "if", "'toxenv'", "in", "section", ":", "print", "(", "'The \"toxenv\" key of the [travis:after] section is '", "'deprecated in favor of the \"envlist\" key.'", ",", "file", "=", "sys", ".", "stderr", ")", "toxenv", "=", "section", ".", "get", "(", "'toxenv'", ")", "required", "=", "set", "(", "split_env", "(", "section", ".", "get", "(", "'envlist'", ",", "toxenv", ")", "or", "''", ")", ")", "actual", "=", "set", "(", "envlist", ")", "if", "required", "-", "actual", ":", "return", "False", "# Translate travis requirements to env requirements", "env_requirements", "=", "[", "(", "TRAVIS_FACTORS", "[", "factor", "]", ",", "value", ")", "for", "factor", ",", "value", "in", "parse_dict", "(", "section", ".", "get", "(", "'travis'", ",", "''", ")", ")", ".", "items", "(", ")", "if", "factor", "in", "TRAVIS_FACTORS", "]", "+", "[", "(", "name", ",", "value", ")", "for", "name", ",", "value", "in", "parse_dict", "(", "section", ".", "get", "(", "'env'", ",", "''", ")", ")", ".", "items", "(", ")", "]", "return", "all", "(", "[", "os", ".", "environ", ".", "get", "(", "name", ")", "==", "value", "for", "name", ",", "value", "in", "env_requirements", "]", ")" ]
Determine if this job should wait for the others.
[ "Determine", "if", "this", "job", "should", "wait", "for", "the", "others", "." ]
d97a966c19abb020298a7e4b91fe83dd1d0a4517
https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/after.py#L65-L96
18,153
tox-dev/tox-travis
src/tox_travis/after.py
get_job_statuses
def get_job_statuses(github_token, api_url, build_id, polling_interval, job_number): """Wait for all the travis jobs to complete. Once the other jobs are complete, return a list of booleans, indicating whether or not the job was successful. Ignore jobs marked "allow_failure". """ auth = get_json('{api_url}/auth/github'.format(api_url=api_url), data={'github_token': github_token})['access_token'] while True: build = get_json('{api_url}/builds/{build_id}'.format( api_url=api_url, build_id=build_id), auth=auth) jobs = [job for job in build['jobs'] if job['number'] != job_number and not job['allow_failure']] # Ignore allowed failures if all(job['finished_at'] for job in jobs): break # All the jobs have completed elif any(job['state'] != 'passed' for job in jobs if job['finished_at']): break # Some required job that finished did not pass print('Waiting for jobs to complete: {job_numbers}'.format( job_numbers=[job['number'] for job in jobs if not job['finished_at']])) time.sleep(polling_interval) return [job['state'] == 'passed' for job in jobs]
python
def get_job_statuses(github_token, api_url, build_id, polling_interval, job_number): """Wait for all the travis jobs to complete. Once the other jobs are complete, return a list of booleans, indicating whether or not the job was successful. Ignore jobs marked "allow_failure". """ auth = get_json('{api_url}/auth/github'.format(api_url=api_url), data={'github_token': github_token})['access_token'] while True: build = get_json('{api_url}/builds/{build_id}'.format( api_url=api_url, build_id=build_id), auth=auth) jobs = [job for job in build['jobs'] if job['number'] != job_number and not job['allow_failure']] # Ignore allowed failures if all(job['finished_at'] for job in jobs): break # All the jobs have completed elif any(job['state'] != 'passed' for job in jobs if job['finished_at']): break # Some required job that finished did not pass print('Waiting for jobs to complete: {job_numbers}'.format( job_numbers=[job['number'] for job in jobs if not job['finished_at']])) time.sleep(polling_interval) return [job['state'] == 'passed' for job in jobs]
[ "def", "get_job_statuses", "(", "github_token", ",", "api_url", ",", "build_id", ",", "polling_interval", ",", "job_number", ")", ":", "auth", "=", "get_json", "(", "'{api_url}/auth/github'", ".", "format", "(", "api_url", "=", "api_url", ")", ",", "data", "=", "{", "'github_token'", ":", "github_token", "}", ")", "[", "'access_token'", "]", "while", "True", ":", "build", "=", "get_json", "(", "'{api_url}/builds/{build_id}'", ".", "format", "(", "api_url", "=", "api_url", ",", "build_id", "=", "build_id", ")", ",", "auth", "=", "auth", ")", "jobs", "=", "[", "job", "for", "job", "in", "build", "[", "'jobs'", "]", "if", "job", "[", "'number'", "]", "!=", "job_number", "and", "not", "job", "[", "'allow_failure'", "]", "]", "# Ignore allowed failures", "if", "all", "(", "job", "[", "'finished_at'", "]", "for", "job", "in", "jobs", ")", ":", "break", "# All the jobs have completed", "elif", "any", "(", "job", "[", "'state'", "]", "!=", "'passed'", "for", "job", "in", "jobs", "if", "job", "[", "'finished_at'", "]", ")", ":", "break", "# Some required job that finished did not pass", "print", "(", "'Waiting for jobs to complete: {job_numbers}'", ".", "format", "(", "job_numbers", "=", "[", "job", "[", "'number'", "]", "for", "job", "in", "jobs", "if", "not", "job", "[", "'finished_at'", "]", "]", ")", ")", "time", ".", "sleep", "(", "polling_interval", ")", "return", "[", "job", "[", "'state'", "]", "==", "'passed'", "for", "job", "in", "jobs", "]" ]
Wait for all the travis jobs to complete. Once the other jobs are complete, return a list of booleans, indicating whether or not the job was successful. Ignore jobs marked "allow_failure".
[ "Wait", "for", "all", "the", "travis", "jobs", "to", "complete", "." ]
d97a966c19abb020298a7e4b91fe83dd1d0a4517
https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/after.py#L99-L127
18,154
tox-dev/tox-travis
src/tox_travis/after.py
get_json
def get_json(url, auth=None, data=None): """Make a GET request, and return the response as parsed JSON.""" headers = { 'Accept': 'application/vnd.travis-ci.2+json', 'User-Agent': 'Travis/Tox-Travis-1.0a', # User-Agent must start with "Travis/" in order to work } if auth: headers['Authorization'] = 'token {auth}'.format(auth=auth) params = {} if data: headers['Content-Type'] = 'application/json' params['data'] = json.dumps(data).encode('utf-8') request = urllib2.Request(url, headers=headers, **params) response = urllib2.urlopen(request).read() return json.loads(response.decode('utf-8'))
python
def get_json(url, auth=None, data=None): """Make a GET request, and return the response as parsed JSON.""" headers = { 'Accept': 'application/vnd.travis-ci.2+json', 'User-Agent': 'Travis/Tox-Travis-1.0a', # User-Agent must start with "Travis/" in order to work } if auth: headers['Authorization'] = 'token {auth}'.format(auth=auth) params = {} if data: headers['Content-Type'] = 'application/json' params['data'] = json.dumps(data).encode('utf-8') request = urllib2.Request(url, headers=headers, **params) response = urllib2.urlopen(request).read() return json.loads(response.decode('utf-8'))
[ "def", "get_json", "(", "url", ",", "auth", "=", "None", ",", "data", "=", "None", ")", ":", "headers", "=", "{", "'Accept'", ":", "'application/vnd.travis-ci.2+json'", ",", "'User-Agent'", ":", "'Travis/Tox-Travis-1.0a'", ",", "# User-Agent must start with \"Travis/\" in order to work", "}", "if", "auth", ":", "headers", "[", "'Authorization'", "]", "=", "'token {auth}'", ".", "format", "(", "auth", "=", "auth", ")", "params", "=", "{", "}", "if", "data", ":", "headers", "[", "'Content-Type'", "]", "=", "'application/json'", "params", "[", "'data'", "]", "=", "json", ".", "dumps", "(", "data", ")", ".", "encode", "(", "'utf-8'", ")", "request", "=", "urllib2", ".", "Request", "(", "url", ",", "headers", "=", "headers", ",", "*", "*", "params", ")", "response", "=", "urllib2", ".", "urlopen", "(", "request", ")", ".", "read", "(", ")", "return", "json", ".", "loads", "(", "response", ".", "decode", "(", "'utf-8'", ")", ")" ]
Make a GET request, and return the response as parsed JSON.
[ "Make", "a", "GET", "request", "and", "return", "the", "response", "as", "parsed", "JSON", "." ]
d97a966c19abb020298a7e4b91fe83dd1d0a4517
https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/after.py#L130-L147
18,155
tox-dev/tox-travis
src/tox_travis/envlist.py
detect_envlist
def detect_envlist(ini): """Default envlist automatically based on the Travis environment.""" # Find the envs that tox knows about declared_envs = get_declared_envs(ini) # Find all the envs for all the desired factors given desired_factors = get_desired_factors(ini) # Reduce desired factors desired_envs = ['-'.join(env) for env in product(*desired_factors)] # Find matching envs return match_envs(declared_envs, desired_envs, passthru=len(desired_factors) == 1)
python
def detect_envlist(ini): """Default envlist automatically based on the Travis environment.""" # Find the envs that tox knows about declared_envs = get_declared_envs(ini) # Find all the envs for all the desired factors given desired_factors = get_desired_factors(ini) # Reduce desired factors desired_envs = ['-'.join(env) for env in product(*desired_factors)] # Find matching envs return match_envs(declared_envs, desired_envs, passthru=len(desired_factors) == 1)
[ "def", "detect_envlist", "(", "ini", ")", ":", "# Find the envs that tox knows about", "declared_envs", "=", "get_declared_envs", "(", "ini", ")", "# Find all the envs for all the desired factors given", "desired_factors", "=", "get_desired_factors", "(", "ini", ")", "# Reduce desired factors", "desired_envs", "=", "[", "'-'", ".", "join", "(", "env", ")", "for", "env", "in", "product", "(", "*", "desired_factors", ")", "]", "# Find matching envs", "return", "match_envs", "(", "declared_envs", ",", "desired_envs", ",", "passthru", "=", "len", "(", "desired_factors", ")", "==", "1", ")" ]
Default envlist automatically based on the Travis environment.
[ "Default", "envlist", "automatically", "based", "on", "the", "Travis", "environment", "." ]
d97a966c19abb020298a7e4b91fe83dd1d0a4517
https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L14-L27
18,156
tox-dev/tox-travis
src/tox_travis/envlist.py
autogen_envconfigs
def autogen_envconfigs(config, envs): """Make the envconfigs for undeclared envs. This is a stripped-down version of parseini.__init__ made for making an envconfig. """ prefix = 'tox' if config.toxinipath.basename == 'setup.cfg' else None reader = tox.config.SectionReader("tox", config._cfg, prefix=prefix) distshare_default = "{homedir}/.tox/distshare" reader.addsubstitutions(toxinidir=config.toxinidir, homedir=config.homedir) reader.addsubstitutions(toxworkdir=config.toxworkdir) config.distdir = reader.getpath("distdir", "{toxworkdir}/dist") reader.addsubstitutions(distdir=config.distdir) config.distshare = reader.getpath("distshare", distshare_default) reader.addsubstitutions(distshare=config.distshare) try: make_envconfig = tox.config.ParseIni.make_envconfig # tox 3.4.0+ except AttributeError: make_envconfig = tox.config.parseini.make_envconfig # Dig past the unbound method in Python 2 make_envconfig = getattr(make_envconfig, '__func__', make_envconfig) # Create the undeclared envs for env in envs: section = tox.config.testenvprefix + env config.envconfigs[env] = make_envconfig( config, env, section, reader._subs, config)
python
def autogen_envconfigs(config, envs): """Make the envconfigs for undeclared envs. This is a stripped-down version of parseini.__init__ made for making an envconfig. """ prefix = 'tox' if config.toxinipath.basename == 'setup.cfg' else None reader = tox.config.SectionReader("tox", config._cfg, prefix=prefix) distshare_default = "{homedir}/.tox/distshare" reader.addsubstitutions(toxinidir=config.toxinidir, homedir=config.homedir) reader.addsubstitutions(toxworkdir=config.toxworkdir) config.distdir = reader.getpath("distdir", "{toxworkdir}/dist") reader.addsubstitutions(distdir=config.distdir) config.distshare = reader.getpath("distshare", distshare_default) reader.addsubstitutions(distshare=config.distshare) try: make_envconfig = tox.config.ParseIni.make_envconfig # tox 3.4.0+ except AttributeError: make_envconfig = tox.config.parseini.make_envconfig # Dig past the unbound method in Python 2 make_envconfig = getattr(make_envconfig, '__func__', make_envconfig) # Create the undeclared envs for env in envs: section = tox.config.testenvprefix + env config.envconfigs[env] = make_envconfig( config, env, section, reader._subs, config)
[ "def", "autogen_envconfigs", "(", "config", ",", "envs", ")", ":", "prefix", "=", "'tox'", "if", "config", ".", "toxinipath", ".", "basename", "==", "'setup.cfg'", "else", "None", "reader", "=", "tox", ".", "config", ".", "SectionReader", "(", "\"tox\"", ",", "config", ".", "_cfg", ",", "prefix", "=", "prefix", ")", "distshare_default", "=", "\"{homedir}/.tox/distshare\"", "reader", ".", "addsubstitutions", "(", "toxinidir", "=", "config", ".", "toxinidir", ",", "homedir", "=", "config", ".", "homedir", ")", "reader", ".", "addsubstitutions", "(", "toxworkdir", "=", "config", ".", "toxworkdir", ")", "config", ".", "distdir", "=", "reader", ".", "getpath", "(", "\"distdir\"", ",", "\"{toxworkdir}/dist\"", ")", "reader", ".", "addsubstitutions", "(", "distdir", "=", "config", ".", "distdir", ")", "config", ".", "distshare", "=", "reader", ".", "getpath", "(", "\"distshare\"", ",", "distshare_default", ")", "reader", ".", "addsubstitutions", "(", "distshare", "=", "config", ".", "distshare", ")", "try", ":", "make_envconfig", "=", "tox", ".", "config", ".", "ParseIni", ".", "make_envconfig", "# tox 3.4.0+", "except", "AttributeError", ":", "make_envconfig", "=", "tox", ".", "config", ".", "parseini", ".", "make_envconfig", "# Dig past the unbound method in Python 2", "make_envconfig", "=", "getattr", "(", "make_envconfig", ",", "'__func__'", ",", "make_envconfig", ")", "# Create the undeclared envs", "for", "env", "in", "envs", ":", "section", "=", "tox", ".", "config", ".", "testenvprefix", "+", "env", "config", ".", "envconfigs", "[", "env", "]", "=", "make_envconfig", "(", "config", ",", "env", ",", "section", ",", "reader", ".", "_subs", ",", "config", ")" ]
Make the envconfigs for undeclared envs. This is a stripped-down version of parseini.__init__ made for making an envconfig.
[ "Make", "the", "envconfigs", "for", "undeclared", "envs", "." ]
d97a966c19abb020298a7e4b91fe83dd1d0a4517
https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L30-L59
18,157
tox-dev/tox-travis
src/tox_travis/envlist.py
get_declared_envs
def get_declared_envs(ini): """Get the full list of envs from the tox ini. This notably also includes envs that aren't in the envlist, but are declared by having their own testenv:envname section. The envs are expected in a particular order. First the ones declared in the envlist, then the other testenvs in order. """ tox_section_name = 'tox:tox' if ini.path.endswith('setup.cfg') else 'tox' tox_section = ini.sections.get(tox_section_name, {}) envlist = split_env(tox_section.get('envlist', [])) # Add additional envs that are declared as sections in the ini section_envs = [ section[8:] for section in sorted(ini.sections, key=ini.lineof) if section.startswith('testenv:') ] return envlist + [env for env in section_envs if env not in envlist]
python
def get_declared_envs(ini): """Get the full list of envs from the tox ini. This notably also includes envs that aren't in the envlist, but are declared by having their own testenv:envname section. The envs are expected in a particular order. First the ones declared in the envlist, then the other testenvs in order. """ tox_section_name = 'tox:tox' if ini.path.endswith('setup.cfg') else 'tox' tox_section = ini.sections.get(tox_section_name, {}) envlist = split_env(tox_section.get('envlist', [])) # Add additional envs that are declared as sections in the ini section_envs = [ section[8:] for section in sorted(ini.sections, key=ini.lineof) if section.startswith('testenv:') ] return envlist + [env for env in section_envs if env not in envlist]
[ "def", "get_declared_envs", "(", "ini", ")", ":", "tox_section_name", "=", "'tox:tox'", "if", "ini", ".", "path", ".", "endswith", "(", "'setup.cfg'", ")", "else", "'tox'", "tox_section", "=", "ini", ".", "sections", ".", "get", "(", "tox_section_name", ",", "{", "}", ")", "envlist", "=", "split_env", "(", "tox_section", ".", "get", "(", "'envlist'", ",", "[", "]", ")", ")", "# Add additional envs that are declared as sections in the ini", "section_envs", "=", "[", "section", "[", "8", ":", "]", "for", "section", "in", "sorted", "(", "ini", ".", "sections", ",", "key", "=", "ini", ".", "lineof", ")", "if", "section", ".", "startswith", "(", "'testenv:'", ")", "]", "return", "envlist", "+", "[", "env", "for", "env", "in", "section_envs", "if", "env", "not", "in", "envlist", "]" ]
Get the full list of envs from the tox ini. This notably also includes envs that aren't in the envlist, but are declared by having their own testenv:envname section. The envs are expected in a particular order. First the ones declared in the envlist, then the other testenvs in order.
[ "Get", "the", "full", "list", "of", "envs", "from", "the", "tox", "ini", "." ]
d97a966c19abb020298a7e4b91fe83dd1d0a4517
https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L62-L81
18,158
tox-dev/tox-travis
src/tox_travis/envlist.py
get_version_info
def get_version_info(): """Get version info from the sys module. Override from environment for testing. """ overrides = os.environ.get('__TOX_TRAVIS_SYS_VERSION') if overrides: version, major, minor = overrides.split(',')[:3] major, minor = int(major), int(minor) else: version, (major, minor) = sys.version, sys.version_info[:2] return version, major, minor
python
def get_version_info(): """Get version info from the sys module. Override from environment for testing. """ overrides = os.environ.get('__TOX_TRAVIS_SYS_VERSION') if overrides: version, major, minor = overrides.split(',')[:3] major, minor = int(major), int(minor) else: version, (major, minor) = sys.version, sys.version_info[:2] return version, major, minor
[ "def", "get_version_info", "(", ")", ":", "overrides", "=", "os", ".", "environ", ".", "get", "(", "'__TOX_TRAVIS_SYS_VERSION'", ")", "if", "overrides", ":", "version", ",", "major", ",", "minor", "=", "overrides", ".", "split", "(", "','", ")", "[", ":", "3", "]", "major", ",", "minor", "=", "int", "(", "major", ")", ",", "int", "(", "minor", ")", "else", ":", "version", ",", "(", "major", ",", "minor", ")", "=", "sys", ".", "version", ",", "sys", ".", "version_info", "[", ":", "2", "]", "return", "version", ",", "major", ",", "minor" ]
Get version info from the sys module. Override from environment for testing.
[ "Get", "version", "info", "from", "the", "sys", "module", "." ]
d97a966c19abb020298a7e4b91fe83dd1d0a4517
https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L84-L95
18,159
tox-dev/tox-travis
src/tox_travis/envlist.py
guess_python_env
def guess_python_env(): """Guess the default python env to use.""" version, major, minor = get_version_info() if 'PyPy' in version: return 'pypy3' if major == 3 else 'pypy' return 'py{major}{minor}'.format(major=major, minor=minor)
python
def guess_python_env(): """Guess the default python env to use.""" version, major, minor = get_version_info() if 'PyPy' in version: return 'pypy3' if major == 3 else 'pypy' return 'py{major}{minor}'.format(major=major, minor=minor)
[ "def", "guess_python_env", "(", ")", ":", "version", ",", "major", ",", "minor", "=", "get_version_info", "(", ")", "if", "'PyPy'", "in", "version", ":", "return", "'pypy3'", "if", "major", "==", "3", "else", "'pypy'", "return", "'py{major}{minor}'", ".", "format", "(", "major", "=", "major", ",", "minor", "=", "minor", ")" ]
Guess the default python env to use.
[ "Guess", "the", "default", "python", "env", "to", "use", "." ]
d97a966c19abb020298a7e4b91fe83dd1d0a4517
https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L98-L103
18,160
tox-dev/tox-travis
src/tox_travis/envlist.py
get_default_envlist
def get_default_envlist(version): """Parse a default tox env based on the version. The version comes from the ``TRAVIS_PYTHON_VERSION`` environment variable. If that isn't set or is invalid, then use sys.version_info to come up with a reasonable default. """ if version in ['pypy', 'pypy3']: return version # Assume single digit major and minor versions match = re.match(r'^(\d)\.(\d)(?:\.\d+)?$', version or '') if match: major, minor = match.groups() return 'py{major}{minor}'.format(major=major, minor=minor) return guess_python_env()
python
def get_default_envlist(version): """Parse a default tox env based on the version. The version comes from the ``TRAVIS_PYTHON_VERSION`` environment variable. If that isn't set or is invalid, then use sys.version_info to come up with a reasonable default. """ if version in ['pypy', 'pypy3']: return version # Assume single digit major and minor versions match = re.match(r'^(\d)\.(\d)(?:\.\d+)?$', version or '') if match: major, minor = match.groups() return 'py{major}{minor}'.format(major=major, minor=minor) return guess_python_env()
[ "def", "get_default_envlist", "(", "version", ")", ":", "if", "version", "in", "[", "'pypy'", ",", "'pypy3'", "]", ":", "return", "version", "# Assume single digit major and minor versions", "match", "=", "re", ".", "match", "(", "r'^(\\d)\\.(\\d)(?:\\.\\d+)?$'", ",", "version", "or", "''", ")", "if", "match", ":", "major", ",", "minor", "=", "match", ".", "groups", "(", ")", "return", "'py{major}{minor}'", ".", "format", "(", "major", "=", "major", ",", "minor", "=", "minor", ")", "return", "guess_python_env", "(", ")" ]
Parse a default tox env based on the version. The version comes from the ``TRAVIS_PYTHON_VERSION`` environment variable. If that isn't set or is invalid, then use sys.version_info to come up with a reasonable default.
[ "Parse", "a", "default", "tox", "env", "based", "on", "the", "version", "." ]
d97a966c19abb020298a7e4b91fe83dd1d0a4517
https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L106-L122
18,161
tox-dev/tox-travis
src/tox_travis/envlist.py
get_desired_factors
def get_desired_factors(ini): """Get the list of desired envs per declared factor. Look at all the accepted configuration locations, and give a list of envlists, one for each Travis factor found. Look in the ``[travis]`` section for the known Travis factors, which are backed by environment variable checking behind the scenes, but provide a cleaner interface. Also look for the ``[tox:travis]`` section, which is deprecated, and treat it as an additional ``python`` key from the ``[travis]`` section. Finally, look for factors based directly on environment variables, listed in the ``[travis:env]`` section. Configuration found in the ``[travis]`` and ``[tox:travis]`` sections are converted to this form under the hood, and are considered in the same way. Special consideration is given to the ``python`` factor. If this factor is set in the environment, then an appropriate configuration will be provided automatically if no manual configuration is provided. To allow for the most flexible processing, the envlists provided by each factor are not combined after they are selected, but instead returned as a list of envlists, and expected to be combined as and when appropriate by the caller. This allows for special handling based on the number of factors that were found to apply to this environment. """ # Find configuration based on known travis factors travis_section = ini.sections.get('travis', {}) found_factors = [ (factor, parse_dict(travis_section[factor])) for factor in TRAVIS_FACTORS if factor in travis_section ] # Backward compatibility with the old tox:travis section if 'tox:travis' in ini.sections: print('The [tox:travis] section is deprecated in favor of' ' the "python" key of the [travis] section.', file=sys.stderr) found_factors.append(('python', ini.sections['tox:travis'])) # Inject any needed autoenv version = os.environ.get('TRAVIS_PYTHON_VERSION') if version: default_envlist = get_default_envlist(version) if not any(factor == 'python' for factor, _ in found_factors): found_factors.insert(0, ('python', {version: default_envlist})) python_factors = [(factor, mapping) for factor, mapping in found_factors if version and factor == 'python'] for _, mapping in python_factors: mapping.setdefault(version, default_envlist) # Convert known travis factors to env factors, # and combine with declared env factors. env_factors = [ (TRAVIS_FACTORS[factor], mapping) for factor, mapping in found_factors ] + [ (name, parse_dict(value)) for name, value in ini.sections.get('travis:env', {}).items() ] # Choose the correct envlists based on the factor values return [ split_env(mapping[os.environ[name]]) for name, mapping in env_factors if name in os.environ and os.environ[name] in mapping ]
python
def get_desired_factors(ini): """Get the list of desired envs per declared factor. Look at all the accepted configuration locations, and give a list of envlists, one for each Travis factor found. Look in the ``[travis]`` section for the known Travis factors, which are backed by environment variable checking behind the scenes, but provide a cleaner interface. Also look for the ``[tox:travis]`` section, which is deprecated, and treat it as an additional ``python`` key from the ``[travis]`` section. Finally, look for factors based directly on environment variables, listed in the ``[travis:env]`` section. Configuration found in the ``[travis]`` and ``[tox:travis]`` sections are converted to this form under the hood, and are considered in the same way. Special consideration is given to the ``python`` factor. If this factor is set in the environment, then an appropriate configuration will be provided automatically if no manual configuration is provided. To allow for the most flexible processing, the envlists provided by each factor are not combined after they are selected, but instead returned as a list of envlists, and expected to be combined as and when appropriate by the caller. This allows for special handling based on the number of factors that were found to apply to this environment. """ # Find configuration based on known travis factors travis_section = ini.sections.get('travis', {}) found_factors = [ (factor, parse_dict(travis_section[factor])) for factor in TRAVIS_FACTORS if factor in travis_section ] # Backward compatibility with the old tox:travis section if 'tox:travis' in ini.sections: print('The [tox:travis] section is deprecated in favor of' ' the "python" key of the [travis] section.', file=sys.stderr) found_factors.append(('python', ini.sections['tox:travis'])) # Inject any needed autoenv version = os.environ.get('TRAVIS_PYTHON_VERSION') if version: default_envlist = get_default_envlist(version) if not any(factor == 'python' for factor, _ in found_factors): found_factors.insert(0, ('python', {version: default_envlist})) python_factors = [(factor, mapping) for factor, mapping in found_factors if version and factor == 'python'] for _, mapping in python_factors: mapping.setdefault(version, default_envlist) # Convert known travis factors to env factors, # and combine with declared env factors. env_factors = [ (TRAVIS_FACTORS[factor], mapping) for factor, mapping in found_factors ] + [ (name, parse_dict(value)) for name, value in ini.sections.get('travis:env', {}).items() ] # Choose the correct envlists based on the factor values return [ split_env(mapping[os.environ[name]]) for name, mapping in env_factors if name in os.environ and os.environ[name] in mapping ]
[ "def", "get_desired_factors", "(", "ini", ")", ":", "# Find configuration based on known travis factors", "travis_section", "=", "ini", ".", "sections", ".", "get", "(", "'travis'", ",", "{", "}", ")", "found_factors", "=", "[", "(", "factor", ",", "parse_dict", "(", "travis_section", "[", "factor", "]", ")", ")", "for", "factor", "in", "TRAVIS_FACTORS", "if", "factor", "in", "travis_section", "]", "# Backward compatibility with the old tox:travis section", "if", "'tox:travis'", "in", "ini", ".", "sections", ":", "print", "(", "'The [tox:travis] section is deprecated in favor of'", "' the \"python\" key of the [travis] section.'", ",", "file", "=", "sys", ".", "stderr", ")", "found_factors", ".", "append", "(", "(", "'python'", ",", "ini", ".", "sections", "[", "'tox:travis'", "]", ")", ")", "# Inject any needed autoenv", "version", "=", "os", ".", "environ", ".", "get", "(", "'TRAVIS_PYTHON_VERSION'", ")", "if", "version", ":", "default_envlist", "=", "get_default_envlist", "(", "version", ")", "if", "not", "any", "(", "factor", "==", "'python'", "for", "factor", ",", "_", "in", "found_factors", ")", ":", "found_factors", ".", "insert", "(", "0", ",", "(", "'python'", ",", "{", "version", ":", "default_envlist", "}", ")", ")", "python_factors", "=", "[", "(", "factor", ",", "mapping", ")", "for", "factor", ",", "mapping", "in", "found_factors", "if", "version", "and", "factor", "==", "'python'", "]", "for", "_", ",", "mapping", "in", "python_factors", ":", "mapping", ".", "setdefault", "(", "version", ",", "default_envlist", ")", "# Convert known travis factors to env factors,", "# and combine with declared env factors.", "env_factors", "=", "[", "(", "TRAVIS_FACTORS", "[", "factor", "]", ",", "mapping", ")", "for", "factor", ",", "mapping", "in", "found_factors", "]", "+", "[", "(", "name", ",", "parse_dict", "(", "value", ")", ")", "for", "name", ",", "value", "in", "ini", ".", "sections", ".", "get", "(", "'travis:env'", ",", "{", "}", ")", ".", "items", "(", ")", "]", "# Choose the correct envlists based on the factor values", "return", "[", "split_env", "(", "mapping", "[", "os", ".", "environ", "[", "name", "]", "]", ")", "for", "name", ",", "mapping", "in", "env_factors", "if", "name", "in", "os", ".", "environ", "and", "os", ".", "environ", "[", "name", "]", "in", "mapping", "]" ]
Get the list of desired envs per declared factor. Look at all the accepted configuration locations, and give a list of envlists, one for each Travis factor found. Look in the ``[travis]`` section for the known Travis factors, which are backed by environment variable checking behind the scenes, but provide a cleaner interface. Also look for the ``[tox:travis]`` section, which is deprecated, and treat it as an additional ``python`` key from the ``[travis]`` section. Finally, look for factors based directly on environment variables, listed in the ``[travis:env]`` section. Configuration found in the ``[travis]`` and ``[tox:travis]`` sections are converted to this form under the hood, and are considered in the same way. Special consideration is given to the ``python`` factor. If this factor is set in the environment, then an appropriate configuration will be provided automatically if no manual configuration is provided. To allow for the most flexible processing, the envlists provided by each factor are not combined after they are selected, but instead returned as a list of envlists, and expected to be combined as and when appropriate by the caller. This allows for special handling based on the number of factors that were found to apply to this environment.
[ "Get", "the", "list", "of", "desired", "envs", "per", "declared", "factor", "." ]
d97a966c19abb020298a7e4b91fe83dd1d0a4517
https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L125-L197
18,162
tox-dev/tox-travis
src/tox_travis/envlist.py
match_envs
def match_envs(declared_envs, desired_envs, passthru): """Determine the envs that match the desired_envs. If ``passthru` is True, and none of the declared envs match the desired envs, then the desired envs will be used verbatim. :param declared_envs: The envs that are declared in the tox config. :param desired_envs: The envs desired from the tox-travis config. :param bool passthru: Whether to used the ``desired_envs`` as a fallback if no declared envs match. """ matched = [ declared for declared in declared_envs if any(env_matches(declared, desired) for desired in desired_envs) ] return desired_envs if not matched and passthru else matched
python
def match_envs(declared_envs, desired_envs, passthru): """Determine the envs that match the desired_envs. If ``passthru` is True, and none of the declared envs match the desired envs, then the desired envs will be used verbatim. :param declared_envs: The envs that are declared in the tox config. :param desired_envs: The envs desired from the tox-travis config. :param bool passthru: Whether to used the ``desired_envs`` as a fallback if no declared envs match. """ matched = [ declared for declared in declared_envs if any(env_matches(declared, desired) for desired in desired_envs) ] return desired_envs if not matched and passthru else matched
[ "def", "match_envs", "(", "declared_envs", ",", "desired_envs", ",", "passthru", ")", ":", "matched", "=", "[", "declared", "for", "declared", "in", "declared_envs", "if", "any", "(", "env_matches", "(", "declared", ",", "desired", ")", "for", "desired", "in", "desired_envs", ")", "]", "return", "desired_envs", "if", "not", "matched", "and", "passthru", "else", "matched" ]
Determine the envs that match the desired_envs. If ``passthru` is True, and none of the declared envs match the desired envs, then the desired envs will be used verbatim. :param declared_envs: The envs that are declared in the tox config. :param desired_envs: The envs desired from the tox-travis config. :param bool passthru: Whether to used the ``desired_envs`` as a fallback if no declared envs match.
[ "Determine", "the", "envs", "that", "match", "the", "desired_envs", "." ]
d97a966c19abb020298a7e4b91fe83dd1d0a4517
https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L200-L215
18,163
tox-dev/tox-travis
src/tox_travis/envlist.py
env_matches
def env_matches(declared, desired): """Determine if a declared env matches a desired env. Rather than simply using the name of the env verbatim, take a closer look to see if all the desired factors are fulfilled. If the desired factors are fulfilled, but there are other factors, it should still match the env. """ desired_factors = desired.split('-') declared_factors = declared.split('-') return all(factor in declared_factors for factor in desired_factors)
python
def env_matches(declared, desired): """Determine if a declared env matches a desired env. Rather than simply using the name of the env verbatim, take a closer look to see if all the desired factors are fulfilled. If the desired factors are fulfilled, but there are other factors, it should still match the env. """ desired_factors = desired.split('-') declared_factors = declared.split('-') return all(factor in declared_factors for factor in desired_factors)
[ "def", "env_matches", "(", "declared", ",", "desired", ")", ":", "desired_factors", "=", "desired", ".", "split", "(", "'-'", ")", "declared_factors", "=", "declared", ".", "split", "(", "'-'", ")", "return", "all", "(", "factor", "in", "declared_factors", "for", "factor", "in", "desired_factors", ")" ]
Determine if a declared env matches a desired env. Rather than simply using the name of the env verbatim, take a closer look to see if all the desired factors are fulfilled. If the desired factors are fulfilled, but there are other factors, it should still match the env.
[ "Determine", "if", "a", "declared", "env", "matches", "a", "desired", "env", "." ]
d97a966c19abb020298a7e4b91fe83dd1d0a4517
https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L218-L228
18,164
tox-dev/tox-travis
src/tox_travis/envlist.py
override_ignore_outcome
def override_ignore_outcome(ini): """Decide whether to override ignore_outcomes.""" travis_reader = tox.config.SectionReader("travis", ini) return travis_reader.getbool('unignore_outcomes', False)
python
def override_ignore_outcome(ini): """Decide whether to override ignore_outcomes.""" travis_reader = tox.config.SectionReader("travis", ini) return travis_reader.getbool('unignore_outcomes', False)
[ "def", "override_ignore_outcome", "(", "ini", ")", ":", "travis_reader", "=", "tox", ".", "config", ".", "SectionReader", "(", "\"travis\"", ",", "ini", ")", "return", "travis_reader", ".", "getbool", "(", "'unignore_outcomes'", ",", "False", ")" ]
Decide whether to override ignore_outcomes.
[ "Decide", "whether", "to", "override", "ignore_outcomes", "." ]
d97a966c19abb020298a7e4b91fe83dd1d0a4517
https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/envlist.py#L231-L234
18,165
tox-dev/tox-travis
src/tox_travis/hooks.py
tox_addoption
def tox_addoption(parser): """Add arguments and needed monkeypatches.""" parser.add_argument( '--travis-after', dest='travis_after', action='store_true', help='Exit successfully after all Travis jobs complete successfully.') if 'TRAVIS' in os.environ: pypy_version_monkeypatch() subcommand_test_monkeypatch(tox_subcommand_test_post)
python
def tox_addoption(parser): """Add arguments and needed monkeypatches.""" parser.add_argument( '--travis-after', dest='travis_after', action='store_true', help='Exit successfully after all Travis jobs complete successfully.') if 'TRAVIS' in os.environ: pypy_version_monkeypatch() subcommand_test_monkeypatch(tox_subcommand_test_post)
[ "def", "tox_addoption", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "'--travis-after'", ",", "dest", "=", "'travis_after'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Exit successfully after all Travis jobs complete successfully.'", ")", "if", "'TRAVIS'", "in", "os", ".", "environ", ":", "pypy_version_monkeypatch", "(", ")", "subcommand_test_monkeypatch", "(", "tox_subcommand_test_post", ")" ]
Add arguments and needed monkeypatches.
[ "Add", "arguments", "and", "needed", "monkeypatches", "." ]
d97a966c19abb020298a7e4b91fe83dd1d0a4517
https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/hooks.py#L19-L27
18,166
tox-dev/tox-travis
src/tox_travis/hooks.py
tox_configure
def tox_configure(config): """Check for the presence of the added options.""" if 'TRAVIS' not in os.environ: return ini = config._cfg # envlist if 'TOXENV' not in os.environ and not config.option.env: envlist = detect_envlist(ini) undeclared = set(envlist) - set(config.envconfigs) if undeclared: print('Matching undeclared envs is deprecated. Be sure all the ' 'envs that Tox should run are declared in the tox config.', file=sys.stderr) autogen_envconfigs(config, undeclared) config.envlist = envlist # Override ignore_outcomes if override_ignore_outcome(ini): for envconfig in config.envconfigs.values(): envconfig.ignore_outcome = False # after if config.option.travis_after: print('The after all feature has been deprecated. Check out Travis\' ' 'build stages, which are a better solution. ' 'See https://tox-travis.readthedocs.io/en/stable/after.html ' 'for more details.', file=sys.stderr)
python
def tox_configure(config): """Check for the presence of the added options.""" if 'TRAVIS' not in os.environ: return ini = config._cfg # envlist if 'TOXENV' not in os.environ and not config.option.env: envlist = detect_envlist(ini) undeclared = set(envlist) - set(config.envconfigs) if undeclared: print('Matching undeclared envs is deprecated. Be sure all the ' 'envs that Tox should run are declared in the tox config.', file=sys.stderr) autogen_envconfigs(config, undeclared) config.envlist = envlist # Override ignore_outcomes if override_ignore_outcome(ini): for envconfig in config.envconfigs.values(): envconfig.ignore_outcome = False # after if config.option.travis_after: print('The after all feature has been deprecated. Check out Travis\' ' 'build stages, which are a better solution. ' 'See https://tox-travis.readthedocs.io/en/stable/after.html ' 'for more details.', file=sys.stderr)
[ "def", "tox_configure", "(", "config", ")", ":", "if", "'TRAVIS'", "not", "in", "os", ".", "environ", ":", "return", "ini", "=", "config", ".", "_cfg", "# envlist", "if", "'TOXENV'", "not", "in", "os", ".", "environ", "and", "not", "config", ".", "option", ".", "env", ":", "envlist", "=", "detect_envlist", "(", "ini", ")", "undeclared", "=", "set", "(", "envlist", ")", "-", "set", "(", "config", ".", "envconfigs", ")", "if", "undeclared", ":", "print", "(", "'Matching undeclared envs is deprecated. Be sure all the '", "'envs that Tox should run are declared in the tox config.'", ",", "file", "=", "sys", ".", "stderr", ")", "autogen_envconfigs", "(", "config", ",", "undeclared", ")", "config", ".", "envlist", "=", "envlist", "# Override ignore_outcomes", "if", "override_ignore_outcome", "(", "ini", ")", ":", "for", "envconfig", "in", "config", ".", "envconfigs", ".", "values", "(", ")", ":", "envconfig", ".", "ignore_outcome", "=", "False", "# after", "if", "config", ".", "option", ".", "travis_after", ":", "print", "(", "'The after all feature has been deprecated. Check out Travis\\' '", "'build stages, which are a better solution. '", "'See https://tox-travis.readthedocs.io/en/stable/after.html '", "'for more details.'", ",", "file", "=", "sys", ".", "stderr", ")" ]
Check for the presence of the added options.
[ "Check", "for", "the", "presence", "of", "the", "added", "options", "." ]
d97a966c19abb020298a7e4b91fe83dd1d0a4517
https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/hooks.py#L31-L59
18,167
tox-dev/tox-travis
src/tox_travis/utils.py
parse_dict
def parse_dict(value): """Parse a dict value from the tox config. .. code-block: ini [travis] python = 2.7: py27, docs 3.5: py{35,36} With this config, the value of ``python`` would be parsed by this function, and would return:: { '2.7': 'py27, docs', '3.5': 'py{35,36}', } """ lines = [line.strip() for line in value.strip().splitlines()] pairs = [line.split(':', 1) for line in lines if line] return dict((k.strip(), v.strip()) for k, v in pairs)
python
def parse_dict(value): """Parse a dict value from the tox config. .. code-block: ini [travis] python = 2.7: py27, docs 3.5: py{35,36} With this config, the value of ``python`` would be parsed by this function, and would return:: { '2.7': 'py27, docs', '3.5': 'py{35,36}', } """ lines = [line.strip() for line in value.strip().splitlines()] pairs = [line.split(':', 1) for line in lines if line] return dict((k.strip(), v.strip()) for k, v in pairs)
[ "def", "parse_dict", "(", "value", ")", ":", "lines", "=", "[", "line", ".", "strip", "(", ")", "for", "line", "in", "value", ".", "strip", "(", ")", ".", "splitlines", "(", ")", "]", "pairs", "=", "[", "line", ".", "split", "(", "':'", ",", "1", ")", "for", "line", "in", "lines", "if", "line", "]", "return", "dict", "(", "(", "k", ".", "strip", "(", ")", ",", "v", ".", "strip", "(", ")", ")", "for", "k", ",", "v", "in", "pairs", ")" ]
Parse a dict value from the tox config. .. code-block: ini [travis] python = 2.7: py27, docs 3.5: py{35,36} With this config, the value of ``python`` would be parsed by this function, and would return:: { '2.7': 'py27, docs', '3.5': 'py{35,36}', }
[ "Parse", "a", "dict", "value", "from", "the", "tox", "config", "." ]
d97a966c19abb020298a7e4b91fe83dd1d0a4517
https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/utils.py#L11-L32
18,168
tox-dev/tox-travis
src/tox_travis/hacks.py
pypy_version_monkeypatch
def pypy_version_monkeypatch(): """Patch Tox to work with non-default PyPy 3 versions.""" # Travis virtualenv do not provide `pypy3`, which tox tries to execute. # This doesnt affect Travis python version `pypy3`, as the pyenv pypy3 # is in the PATH. # https://github.com/travis-ci/travis-ci/issues/6304 # Force use of the virtualenv `python`. version = os.environ.get('TRAVIS_PYTHON_VERSION') if version and default_factors and version.startswith('pypy3.3-'): default_factors['pypy3'] = 'python'
python
def pypy_version_monkeypatch(): """Patch Tox to work with non-default PyPy 3 versions.""" # Travis virtualenv do not provide `pypy3`, which tox tries to execute. # This doesnt affect Travis python version `pypy3`, as the pyenv pypy3 # is in the PATH. # https://github.com/travis-ci/travis-ci/issues/6304 # Force use of the virtualenv `python`. version = os.environ.get('TRAVIS_PYTHON_VERSION') if version and default_factors and version.startswith('pypy3.3-'): default_factors['pypy3'] = 'python'
[ "def", "pypy_version_monkeypatch", "(", ")", ":", "# Travis virtualenv do not provide `pypy3`, which tox tries to execute.", "# This doesnt affect Travis python version `pypy3`, as the pyenv pypy3", "# is in the PATH.", "# https://github.com/travis-ci/travis-ci/issues/6304", "# Force use of the virtualenv `python`.", "version", "=", "os", ".", "environ", ".", "get", "(", "'TRAVIS_PYTHON_VERSION'", ")", "if", "version", "and", "default_factors", "and", "version", ".", "startswith", "(", "'pypy3.3-'", ")", ":", "default_factors", "[", "'pypy3'", "]", "=", "'python'" ]
Patch Tox to work with non-default PyPy 3 versions.
[ "Patch", "Tox", "to", "work", "with", "non", "-", "default", "PyPy", "3", "versions", "." ]
d97a966c19abb020298a7e4b91fe83dd1d0a4517
https://github.com/tox-dev/tox-travis/blob/d97a966c19abb020298a7e4b91fe83dd1d0a4517/src/tox_travis/hacks.py#L9-L18
18,169
adafruit/Adafruit_CircuitPython_MCP230xx
adafruit_mcp230xx.py
DigitalInOut.direction
def direction(self): """The direction of the pin, either True for an input or False for an output. """ if _get_bit(self._mcp.iodir, self._pin): return digitalio.Direction.INPUT return digitalio.Direction.OUTPUT
python
def direction(self): """The direction of the pin, either True for an input or False for an output. """ if _get_bit(self._mcp.iodir, self._pin): return digitalio.Direction.INPUT return digitalio.Direction.OUTPUT
[ "def", "direction", "(", "self", ")", ":", "if", "_get_bit", "(", "self", ".", "_mcp", ".", "iodir", ",", "self", ".", "_pin", ")", ":", "return", "digitalio", ".", "Direction", ".", "INPUT", "return", "digitalio", ".", "Direction", ".", "OUTPUT" ]
The direction of the pin, either True for an input or False for an output.
[ "The", "direction", "of", "the", "pin", "either", "True", "for", "an", "input", "or", "False", "for", "an", "output", "." ]
da9480befecef31c2428062919b9f3da6f428d15
https://github.com/adafruit/Adafruit_CircuitPython_MCP230xx/blob/da9480befecef31c2428062919b9f3da6f428d15/adafruit_mcp230xx.py#L148-L154
18,170
adafruit/Adafruit_CircuitPython_MCP230xx
adafruit_mcp230xx.py
DigitalInOut.pull
def pull(self): """Enable or disable internal pull-up resistors for this pin. A value of digitalio.Pull.UP will enable a pull-up resistor, and None will disable it. Pull-down resistors are NOT supported! """ if _get_bit(self._mcp.gppu, self._pin): return digitalio.Pull.UP return None
python
def pull(self): """Enable or disable internal pull-up resistors for this pin. A value of digitalio.Pull.UP will enable a pull-up resistor, and None will disable it. Pull-down resistors are NOT supported! """ if _get_bit(self._mcp.gppu, self._pin): return digitalio.Pull.UP return None
[ "def", "pull", "(", "self", ")", ":", "if", "_get_bit", "(", "self", ".", "_mcp", ".", "gppu", ",", "self", ".", "_pin", ")", ":", "return", "digitalio", ".", "Pull", ".", "UP", "return", "None" ]
Enable or disable internal pull-up resistors for this pin. A value of digitalio.Pull.UP will enable a pull-up resistor, and None will disable it. Pull-down resistors are NOT supported!
[ "Enable", "or", "disable", "internal", "pull", "-", "up", "resistors", "for", "this", "pin", ".", "A", "value", "of", "digitalio", ".", "Pull", ".", "UP", "will", "enable", "a", "pull", "-", "up", "resistor", "and", "None", "will", "disable", "it", ".", "Pull", "-", "down", "resistors", "are", "NOT", "supported!" ]
da9480befecef31c2428062919b9f3da6f428d15
https://github.com/adafruit/Adafruit_CircuitPython_MCP230xx/blob/da9480befecef31c2428062919b9f3da6f428d15/adafruit_mcp230xx.py#L166-L173
18,171
sebdah/dynamic-dynamodb
dynamic_dynamodb/statistics/table.py
get_throttled_read_event_count
def get_throttled_read_event_count( table_name, lookback_window_start=15, lookback_period=5): """ Returns the number of throttled read events during a given time frame :type table_name: str :param table_name: Name of the DynamoDB table :type lookback_window_start: int :param lookback_window_start: Relative start time for the CloudWatch metric :type lookback_period: int :param lookback_period: Number of minutes to look at :returns: int -- Number of throttled read events during the time period """ try: metrics = __get_aws_metric( table_name, lookback_window_start, lookback_period, 'ReadThrottleEvents') except BotoServerError: raise if metrics: throttled_read_events = int(metrics[0]['Sum']) else: throttled_read_events = 0 logger.info('{0} - Read throttle count: {1:d}'.format( table_name, throttled_read_events)) return throttled_read_events
python
def get_throttled_read_event_count( table_name, lookback_window_start=15, lookback_period=5): """ Returns the number of throttled read events during a given time frame :type table_name: str :param table_name: Name of the DynamoDB table :type lookback_window_start: int :param lookback_window_start: Relative start time for the CloudWatch metric :type lookback_period: int :param lookback_period: Number of minutes to look at :returns: int -- Number of throttled read events during the time period """ try: metrics = __get_aws_metric( table_name, lookback_window_start, lookback_period, 'ReadThrottleEvents') except BotoServerError: raise if metrics: throttled_read_events = int(metrics[0]['Sum']) else: throttled_read_events = 0 logger.info('{0} - Read throttle count: {1:d}'.format( table_name, throttled_read_events)) return throttled_read_events
[ "def", "get_throttled_read_event_count", "(", "table_name", ",", "lookback_window_start", "=", "15", ",", "lookback_period", "=", "5", ")", ":", "try", ":", "metrics", "=", "__get_aws_metric", "(", "table_name", ",", "lookback_window_start", ",", "lookback_period", ",", "'ReadThrottleEvents'", ")", "except", "BotoServerError", ":", "raise", "if", "metrics", ":", "throttled_read_events", "=", "int", "(", "metrics", "[", "0", "]", "[", "'Sum'", "]", ")", "else", ":", "throttled_read_events", "=", "0", "logger", ".", "info", "(", "'{0} - Read throttle count: {1:d}'", ".", "format", "(", "table_name", ",", "throttled_read_events", ")", ")", "return", "throttled_read_events" ]
Returns the number of throttled read events during a given time frame :type table_name: str :param table_name: Name of the DynamoDB table :type lookback_window_start: int :param lookback_window_start: Relative start time for the CloudWatch metric :type lookback_period: int :param lookback_period: Number of minutes to look at :returns: int -- Number of throttled read events during the time period
[ "Returns", "the", "number", "of", "throttled", "read", "events", "during", "a", "given", "time", "frame" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/statistics/table.py#L58-L86
18,172
sebdah/dynamic-dynamodb
dynamic_dynamodb/statistics/table.py
get_throttled_by_consumed_read_percent
def get_throttled_by_consumed_read_percent( table_name, lookback_window_start=15, lookback_period=5): """ Returns the number of throttled read events in percent of consumption :type table_name: str :param table_name: Name of the DynamoDB table :type lookback_window_start: int :param lookback_window_start: Relative start time for the CloudWatch metric :type lookback_period: int :param lookback_period: Number of minutes to look at :returns: float -- Percent of throttled read events by consumption """ try: metrics1 = __get_aws_metric( table_name, lookback_window_start, lookback_period, 'ConsumedReadCapacityUnits') metrics2 = __get_aws_metric( table_name, lookback_window_start, lookback_period, 'ReadThrottleEvents') except BotoServerError: raise if metrics1 and metrics2: lookback_seconds = lookback_period * 60 throttled_by_consumed_read_percent = ( ( (float(metrics2[0]['Sum']) / float(lookback_seconds)) / (float(metrics1[0]['Sum']) / float(lookback_seconds)) ) * 100) else: throttled_by_consumed_read_percent = 0 logger.info('{0} - Throttled read percent by consumption: {1:.2f}%'.format( table_name, throttled_by_consumed_read_percent)) return throttled_by_consumed_read_percent
python
def get_throttled_by_consumed_read_percent( table_name, lookback_window_start=15, lookback_period=5): """ Returns the number of throttled read events in percent of consumption :type table_name: str :param table_name: Name of the DynamoDB table :type lookback_window_start: int :param lookback_window_start: Relative start time for the CloudWatch metric :type lookback_period: int :param lookback_period: Number of minutes to look at :returns: float -- Percent of throttled read events by consumption """ try: metrics1 = __get_aws_metric( table_name, lookback_window_start, lookback_period, 'ConsumedReadCapacityUnits') metrics2 = __get_aws_metric( table_name, lookback_window_start, lookback_period, 'ReadThrottleEvents') except BotoServerError: raise if metrics1 and metrics2: lookback_seconds = lookback_period * 60 throttled_by_consumed_read_percent = ( ( (float(metrics2[0]['Sum']) / float(lookback_seconds)) / (float(metrics1[0]['Sum']) / float(lookback_seconds)) ) * 100) else: throttled_by_consumed_read_percent = 0 logger.info('{0} - Throttled read percent by consumption: {1:.2f}%'.format( table_name, throttled_by_consumed_read_percent)) return throttled_by_consumed_read_percent
[ "def", "get_throttled_by_consumed_read_percent", "(", "table_name", ",", "lookback_window_start", "=", "15", ",", "lookback_period", "=", "5", ")", ":", "try", ":", "metrics1", "=", "__get_aws_metric", "(", "table_name", ",", "lookback_window_start", ",", "lookback_period", ",", "'ConsumedReadCapacityUnits'", ")", "metrics2", "=", "__get_aws_metric", "(", "table_name", ",", "lookback_window_start", ",", "lookback_period", ",", "'ReadThrottleEvents'", ")", "except", "BotoServerError", ":", "raise", "if", "metrics1", "and", "metrics2", ":", "lookback_seconds", "=", "lookback_period", "*", "60", "throttled_by_consumed_read_percent", "=", "(", "(", "(", "float", "(", "metrics2", "[", "0", "]", "[", "'Sum'", "]", ")", "/", "float", "(", "lookback_seconds", ")", ")", "/", "(", "float", "(", "metrics1", "[", "0", "]", "[", "'Sum'", "]", ")", "/", "float", "(", "lookback_seconds", ")", ")", ")", "*", "100", ")", "else", ":", "throttled_by_consumed_read_percent", "=", "0", "logger", ".", "info", "(", "'{0} - Throttled read percent by consumption: {1:.2f}%'", ".", "format", "(", "table_name", ",", "throttled_by_consumed_read_percent", ")", ")", "return", "throttled_by_consumed_read_percent" ]
Returns the number of throttled read events in percent of consumption :type table_name: str :param table_name: Name of the DynamoDB table :type lookback_window_start: int :param lookback_window_start: Relative start time for the CloudWatch metric :type lookback_period: int :param lookback_period: Number of minutes to look at :returns: float -- Percent of throttled read events by consumption
[ "Returns", "the", "number", "of", "throttled", "read", "events", "in", "percent", "of", "consumption" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/statistics/table.py#L132-L171
18,173
sebdah/dynamic-dynamodb
dynamic_dynamodb/statistics/table.py
get_throttled_by_consumed_write_percent
def get_throttled_by_consumed_write_percent( table_name, lookback_window_start=15, lookback_period=5): """ Returns the number of throttled write events in percent of consumption :type table_name: str :param table_name: Name of the DynamoDB table :type lookback_window_start: int :param lookback_window_start: Relative start time for the CloudWatch metric :type lookback_period: int :param lookback_period: Number of minutes to look at :returns: float -- Percent of throttled write events by consumption """ try: metrics1 = __get_aws_metric( table_name, lookback_window_start, lookback_period, 'ConsumedWriteCapacityUnits') metrics2 = __get_aws_metric( table_name, lookback_window_start, lookback_period, 'WriteThrottleEvents') except BotoServerError: raise if metrics1 and metrics2: lookback_seconds = lookback_period * 60 throttled_by_consumed_write_percent = ( ( (float(metrics2[0]['Sum']) / float(lookback_seconds)) / (float(metrics1[0]['Sum']) / float(lookback_seconds)) ) * 100) else: throttled_by_consumed_write_percent = 0 logger.info( '{0} - Throttled write percent by consumption: {1:.2f}%'.format( table_name, throttled_by_consumed_write_percent)) return throttled_by_consumed_write_percent
python
def get_throttled_by_consumed_write_percent( table_name, lookback_window_start=15, lookback_period=5): """ Returns the number of throttled write events in percent of consumption :type table_name: str :param table_name: Name of the DynamoDB table :type lookback_window_start: int :param lookback_window_start: Relative start time for the CloudWatch metric :type lookback_period: int :param lookback_period: Number of minutes to look at :returns: float -- Percent of throttled write events by consumption """ try: metrics1 = __get_aws_metric( table_name, lookback_window_start, lookback_period, 'ConsumedWriteCapacityUnits') metrics2 = __get_aws_metric( table_name, lookback_window_start, lookback_period, 'WriteThrottleEvents') except BotoServerError: raise if metrics1 and metrics2: lookback_seconds = lookback_period * 60 throttled_by_consumed_write_percent = ( ( (float(metrics2[0]['Sum']) / float(lookback_seconds)) / (float(metrics1[0]['Sum']) / float(lookback_seconds)) ) * 100) else: throttled_by_consumed_write_percent = 0 logger.info( '{0} - Throttled write percent by consumption: {1:.2f}%'.format( table_name, throttled_by_consumed_write_percent)) return throttled_by_consumed_write_percent
[ "def", "get_throttled_by_consumed_write_percent", "(", "table_name", ",", "lookback_window_start", "=", "15", ",", "lookback_period", "=", "5", ")", ":", "try", ":", "metrics1", "=", "__get_aws_metric", "(", "table_name", ",", "lookback_window_start", ",", "lookback_period", ",", "'ConsumedWriteCapacityUnits'", ")", "metrics2", "=", "__get_aws_metric", "(", "table_name", ",", "lookback_window_start", ",", "lookback_period", ",", "'WriteThrottleEvents'", ")", "except", "BotoServerError", ":", "raise", "if", "metrics1", "and", "metrics2", ":", "lookback_seconds", "=", "lookback_period", "*", "60", "throttled_by_consumed_write_percent", "=", "(", "(", "(", "float", "(", "metrics2", "[", "0", "]", "[", "'Sum'", "]", ")", "/", "float", "(", "lookback_seconds", ")", ")", "/", "(", "float", "(", "metrics1", "[", "0", "]", "[", "'Sum'", "]", ")", "/", "float", "(", "lookback_seconds", ")", ")", ")", "*", "100", ")", "else", ":", "throttled_by_consumed_write_percent", "=", "0", "logger", ".", "info", "(", "'{0} - Throttled write percent by consumption: {1:.2f}%'", ".", "format", "(", "table_name", ",", "throttled_by_consumed_write_percent", ")", ")", "return", "throttled_by_consumed_write_percent" ]
Returns the number of throttled write events in percent of consumption :type table_name: str :param table_name: Name of the DynamoDB table :type lookback_window_start: int :param lookback_window_start: Relative start time for the CloudWatch metric :type lookback_period: int :param lookback_period: Number of minutes to look at :returns: float -- Percent of throttled write events by consumption
[ "Returns", "the", "number", "of", "throttled", "write", "events", "in", "percent", "of", "consumption" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/statistics/table.py#L291-L332
18,174
sebdah/dynamic-dynamodb
dynamic_dynamodb/statistics/table.py
__get_aws_metric
def __get_aws_metric(table_name, lookback_window_start, lookback_period, metric_name): """ Returns a metric list from the AWS CloudWatch service, may return None if no metric exists :type table_name: str :param table_name: Name of the DynamoDB table :type lookback_window_start: int :param lookback_window_start: How many minutes to look at :type lookback_period: int :type lookback_period: Length of the lookback period in minutes :type metric_name: str :param metric_name: Name of the metric to retrieve from CloudWatch :returns: list -- A list of time series data for the given metric, may be None if there was no data """ try: now = datetime.utcnow() start_time = now - timedelta(minutes=lookback_window_start) end_time = now - timedelta( minutes=lookback_window_start - lookback_period) return cloudwatch_connection.get_metric_statistics( period=lookback_period * 60, start_time=start_time, end_time=end_time, metric_name=metric_name, namespace='AWS/DynamoDB', statistics=['Sum'], dimensions={'TableName': table_name}, unit='Count') except BotoServerError as error: logger.error( 'Unknown boto error. Status: "{0}". ' 'Reason: "{1}". Message: {2}'.format( error.status, error.reason, error.message)) raise
python
def __get_aws_metric(table_name, lookback_window_start, lookback_period, metric_name): """ Returns a metric list from the AWS CloudWatch service, may return None if no metric exists :type table_name: str :param table_name: Name of the DynamoDB table :type lookback_window_start: int :param lookback_window_start: How many minutes to look at :type lookback_period: int :type lookback_period: Length of the lookback period in minutes :type metric_name: str :param metric_name: Name of the metric to retrieve from CloudWatch :returns: list -- A list of time series data for the given metric, may be None if there was no data """ try: now = datetime.utcnow() start_time = now - timedelta(minutes=lookback_window_start) end_time = now - timedelta( minutes=lookback_window_start - lookback_period) return cloudwatch_connection.get_metric_statistics( period=lookback_period * 60, start_time=start_time, end_time=end_time, metric_name=metric_name, namespace='AWS/DynamoDB', statistics=['Sum'], dimensions={'TableName': table_name}, unit='Count') except BotoServerError as error: logger.error( 'Unknown boto error. Status: "{0}". ' 'Reason: "{1}". Message: {2}'.format( error.status, error.reason, error.message)) raise
[ "def", "__get_aws_metric", "(", "table_name", ",", "lookback_window_start", ",", "lookback_period", ",", "metric_name", ")", ":", "try", ":", "now", "=", "datetime", ".", "utcnow", "(", ")", "start_time", "=", "now", "-", "timedelta", "(", "minutes", "=", "lookback_window_start", ")", "end_time", "=", "now", "-", "timedelta", "(", "minutes", "=", "lookback_window_start", "-", "lookback_period", ")", "return", "cloudwatch_connection", ".", "get_metric_statistics", "(", "period", "=", "lookback_period", "*", "60", ",", "start_time", "=", "start_time", ",", "end_time", "=", "end_time", ",", "metric_name", "=", "metric_name", ",", "namespace", "=", "'AWS/DynamoDB'", ",", "statistics", "=", "[", "'Sum'", "]", ",", "dimensions", "=", "{", "'TableName'", ":", "table_name", "}", ",", "unit", "=", "'Count'", ")", "except", "BotoServerError", "as", "error", ":", "logger", ".", "error", "(", "'Unknown boto error. Status: \"{0}\". '", "'Reason: \"{1}\". Message: {2}'", ".", "format", "(", "error", ".", "status", ",", "error", ".", "reason", ",", "error", ".", "message", ")", ")", "raise" ]
Returns a metric list from the AWS CloudWatch service, may return None if no metric exists :type table_name: str :param table_name: Name of the DynamoDB table :type lookback_window_start: int :param lookback_window_start: How many minutes to look at :type lookback_period: int :type lookback_period: Length of the lookback period in minutes :type metric_name: str :param metric_name: Name of the metric to retrieve from CloudWatch :returns: list -- A list of time series data for the given metric, may be None if there was no data
[ "Returns", "a", "metric", "list", "from", "the", "AWS", "CloudWatch", "service", "may", "return", "None", "if", "no", "metric", "exists" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/statistics/table.py#L340-L378
18,175
sebdah/dynamic-dynamodb
dynamic_dynamodb/core/gsi.py
ensure_provisioning
def ensure_provisioning( table_name, table_key, gsi_name, gsi_key, num_consec_read_checks, num_consec_write_checks): """ Ensure that provisioning is correct for Global Secondary Indexes :type table_name: str :param table_name: Name of the DynamoDB table :type table_key: str :param table_key: Table configuration option key name :type gsi_name: str :param gsi_name: Name of the GSI :type gsi_key: str :param gsi_key: GSI configuration option key name :type num_consec_read_checks: int :param num_consec_read_checks: How many consecutive checks have we had :type num_consec_write_checks: int :param num_consec_write_checks: How many consecutive checks have we had :returns: (int, int) -- num_consec_read_checks, num_consec_write_checks """ if get_global_option('circuit_breaker_url') or get_gsi_option( table_key, gsi_key, 'circuit_breaker_url'): if circuit_breaker.is_open(table_name, table_key, gsi_name, gsi_key): logger.warning('Circuit breaker is OPEN!') return (0, 0) logger.info( '{0} - Will ensure provisioning for global secondary index {1}'.format( table_name, gsi_name)) # Handle throughput alarm checks __ensure_provisioning_alarm(table_name, table_key, gsi_name, gsi_key) try: read_update_needed, updated_read_units, num_consec_read_checks = \ __ensure_provisioning_reads( table_name, table_key, gsi_name, gsi_key, num_consec_read_checks) write_update_needed, updated_write_units, num_consec_write_checks = \ __ensure_provisioning_writes( table_name, table_key, gsi_name, gsi_key, num_consec_write_checks) if read_update_needed: num_consec_read_checks = 0 if write_update_needed: num_consec_write_checks = 0 # Handle throughput updates if read_update_needed or write_update_needed: logger.info( '{0} - GSI: {1} - Changing provisioning to {2:d} ' 'read units and {3:d} write units'.format( table_name, gsi_name, int(updated_read_units), int(updated_write_units))) __update_throughput( table_name, table_key, gsi_name, gsi_key, updated_read_units, updated_write_units) else: logger.info( '{0} - GSI: {1} - No need to change provisioning'.format( table_name, gsi_name)) except JSONResponseError: raise except BotoServerError: raise return num_consec_read_checks, num_consec_write_checks
python
def ensure_provisioning( table_name, table_key, gsi_name, gsi_key, num_consec_read_checks, num_consec_write_checks): """ Ensure that provisioning is correct for Global Secondary Indexes :type table_name: str :param table_name: Name of the DynamoDB table :type table_key: str :param table_key: Table configuration option key name :type gsi_name: str :param gsi_name: Name of the GSI :type gsi_key: str :param gsi_key: GSI configuration option key name :type num_consec_read_checks: int :param num_consec_read_checks: How many consecutive checks have we had :type num_consec_write_checks: int :param num_consec_write_checks: How many consecutive checks have we had :returns: (int, int) -- num_consec_read_checks, num_consec_write_checks """ if get_global_option('circuit_breaker_url') or get_gsi_option( table_key, gsi_key, 'circuit_breaker_url'): if circuit_breaker.is_open(table_name, table_key, gsi_name, gsi_key): logger.warning('Circuit breaker is OPEN!') return (0, 0) logger.info( '{0} - Will ensure provisioning for global secondary index {1}'.format( table_name, gsi_name)) # Handle throughput alarm checks __ensure_provisioning_alarm(table_name, table_key, gsi_name, gsi_key) try: read_update_needed, updated_read_units, num_consec_read_checks = \ __ensure_provisioning_reads( table_name, table_key, gsi_name, gsi_key, num_consec_read_checks) write_update_needed, updated_write_units, num_consec_write_checks = \ __ensure_provisioning_writes( table_name, table_key, gsi_name, gsi_key, num_consec_write_checks) if read_update_needed: num_consec_read_checks = 0 if write_update_needed: num_consec_write_checks = 0 # Handle throughput updates if read_update_needed or write_update_needed: logger.info( '{0} - GSI: {1} - Changing provisioning to {2:d} ' 'read units and {3:d} write units'.format( table_name, gsi_name, int(updated_read_units), int(updated_write_units))) __update_throughput( table_name, table_key, gsi_name, gsi_key, updated_read_units, updated_write_units) else: logger.info( '{0} - GSI: {1} - No need to change provisioning'.format( table_name, gsi_name)) except JSONResponseError: raise except BotoServerError: raise return num_consec_read_checks, num_consec_write_checks
[ "def", "ensure_provisioning", "(", "table_name", ",", "table_key", ",", "gsi_name", ",", "gsi_key", ",", "num_consec_read_checks", ",", "num_consec_write_checks", ")", ":", "if", "get_global_option", "(", "'circuit_breaker_url'", ")", "or", "get_gsi_option", "(", "table_key", ",", "gsi_key", ",", "'circuit_breaker_url'", ")", ":", "if", "circuit_breaker", ".", "is_open", "(", "table_name", ",", "table_key", ",", "gsi_name", ",", "gsi_key", ")", ":", "logger", ".", "warning", "(", "'Circuit breaker is OPEN!'", ")", "return", "(", "0", ",", "0", ")", "logger", ".", "info", "(", "'{0} - Will ensure provisioning for global secondary index {1}'", ".", "format", "(", "table_name", ",", "gsi_name", ")", ")", "# Handle throughput alarm checks", "__ensure_provisioning_alarm", "(", "table_name", ",", "table_key", ",", "gsi_name", ",", "gsi_key", ")", "try", ":", "read_update_needed", ",", "updated_read_units", ",", "num_consec_read_checks", "=", "__ensure_provisioning_reads", "(", "table_name", ",", "table_key", ",", "gsi_name", ",", "gsi_key", ",", "num_consec_read_checks", ")", "write_update_needed", ",", "updated_write_units", ",", "num_consec_write_checks", "=", "__ensure_provisioning_writes", "(", "table_name", ",", "table_key", ",", "gsi_name", ",", "gsi_key", ",", "num_consec_write_checks", ")", "if", "read_update_needed", ":", "num_consec_read_checks", "=", "0", "if", "write_update_needed", ":", "num_consec_write_checks", "=", "0", "# Handle throughput updates", "if", "read_update_needed", "or", "write_update_needed", ":", "logger", ".", "info", "(", "'{0} - GSI: {1} - Changing provisioning to {2:d} '", "'read units and {3:d} write units'", ".", "format", "(", "table_name", ",", "gsi_name", ",", "int", "(", "updated_read_units", ")", ",", "int", "(", "updated_write_units", ")", ")", ")", "__update_throughput", "(", "table_name", ",", "table_key", ",", "gsi_name", ",", "gsi_key", ",", "updated_read_units", ",", "updated_write_units", ")", "else", ":", "logger", ".", "info", "(", "'{0} - GSI: {1} - No need to change provisioning'", ".", "format", "(", "table_name", ",", "gsi_name", ")", ")", "except", "JSONResponseError", ":", "raise", "except", "BotoServerError", ":", "raise", "return", "num_consec_read_checks", ",", "num_consec_write_checks" ]
Ensure that provisioning is correct for Global Secondary Indexes :type table_name: str :param table_name: Name of the DynamoDB table :type table_key: str :param table_key: Table configuration option key name :type gsi_name: str :param gsi_name: Name of the GSI :type gsi_key: str :param gsi_key: GSI configuration option key name :type num_consec_read_checks: int :param num_consec_read_checks: How many consecutive checks have we had :type num_consec_write_checks: int :param num_consec_write_checks: How many consecutive checks have we had :returns: (int, int) -- num_consec_read_checks, num_consec_write_checks
[ "Ensure", "that", "provisioning", "is", "correct", "for", "Global", "Secondary", "Indexes" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/core/gsi.py#L13-L93
18,176
sebdah/dynamic-dynamodb
dynamic_dynamodb/core/gsi.py
__update_throughput
def __update_throughput( table_name, table_key, gsi_name, gsi_key, read_units, write_units): """ Update throughput on the GSI :type table_name: str :param table_name: Name of the DynamoDB table :type table_key: str :param table_key: Table configuration option key name :type gsi_name: str :param gsi_name: Name of the GSI :type gsi_key: str :param gsi_key: Configuration option key name :type read_units: int :param read_units: New read unit provisioning :type write_units: int :param write_units: New write unit provisioning """ try: current_ru = dynamodb.get_provisioned_gsi_read_units( table_name, gsi_name) current_wu = dynamodb.get_provisioned_gsi_write_units( table_name, gsi_name) except JSONResponseError: raise # Check table status try: gsi_status = dynamodb.get_gsi_status(table_name, gsi_name) except JSONResponseError: raise logger.debug('{0} - GSI: {1} - GSI status is {2}'.format( table_name, gsi_name, gsi_status)) if gsi_status != 'ACTIVE': logger.warning( '{0} - GSI: {1} - Not performing throughput changes when GSI ' 'status is {2}'.format(table_name, gsi_name, gsi_status)) return # If this setting is True, we will only scale down when # BOTH reads AND writes are low if get_gsi_option(table_key, gsi_key, 'always_decrease_rw_together'): read_units, write_units = __calculate_always_decrease_rw_values( table_name, gsi_name, read_units, current_ru, write_units, current_wu) if read_units == current_ru and write_units == current_wu: logger.info('{0} - GSI: {1} - No changes to perform'.format( table_name, gsi_name)) return dynamodb.update_gsi_provisioning( table_name, table_key, gsi_name, gsi_key, int(read_units), int(write_units))
python
def __update_throughput( table_name, table_key, gsi_name, gsi_key, read_units, write_units): """ Update throughput on the GSI :type table_name: str :param table_name: Name of the DynamoDB table :type table_key: str :param table_key: Table configuration option key name :type gsi_name: str :param gsi_name: Name of the GSI :type gsi_key: str :param gsi_key: Configuration option key name :type read_units: int :param read_units: New read unit provisioning :type write_units: int :param write_units: New write unit provisioning """ try: current_ru = dynamodb.get_provisioned_gsi_read_units( table_name, gsi_name) current_wu = dynamodb.get_provisioned_gsi_write_units( table_name, gsi_name) except JSONResponseError: raise # Check table status try: gsi_status = dynamodb.get_gsi_status(table_name, gsi_name) except JSONResponseError: raise logger.debug('{0} - GSI: {1} - GSI status is {2}'.format( table_name, gsi_name, gsi_status)) if gsi_status != 'ACTIVE': logger.warning( '{0} - GSI: {1} - Not performing throughput changes when GSI ' 'status is {2}'.format(table_name, gsi_name, gsi_status)) return # If this setting is True, we will only scale down when # BOTH reads AND writes are low if get_gsi_option(table_key, gsi_key, 'always_decrease_rw_together'): read_units, write_units = __calculate_always_decrease_rw_values( table_name, gsi_name, read_units, current_ru, write_units, current_wu) if read_units == current_ru and write_units == current_wu: logger.info('{0} - GSI: {1} - No changes to perform'.format( table_name, gsi_name)) return dynamodb.update_gsi_provisioning( table_name, table_key, gsi_name, gsi_key, int(read_units), int(write_units))
[ "def", "__update_throughput", "(", "table_name", ",", "table_key", ",", "gsi_name", ",", "gsi_key", ",", "read_units", ",", "write_units", ")", ":", "try", ":", "current_ru", "=", "dynamodb", ".", "get_provisioned_gsi_read_units", "(", "table_name", ",", "gsi_name", ")", "current_wu", "=", "dynamodb", ".", "get_provisioned_gsi_write_units", "(", "table_name", ",", "gsi_name", ")", "except", "JSONResponseError", ":", "raise", "# Check table status", "try", ":", "gsi_status", "=", "dynamodb", ".", "get_gsi_status", "(", "table_name", ",", "gsi_name", ")", "except", "JSONResponseError", ":", "raise", "logger", ".", "debug", "(", "'{0} - GSI: {1} - GSI status is {2}'", ".", "format", "(", "table_name", ",", "gsi_name", ",", "gsi_status", ")", ")", "if", "gsi_status", "!=", "'ACTIVE'", ":", "logger", ".", "warning", "(", "'{0} - GSI: {1} - Not performing throughput changes when GSI '", "'status is {2}'", ".", "format", "(", "table_name", ",", "gsi_name", ",", "gsi_status", ")", ")", "return", "# If this setting is True, we will only scale down when", "# BOTH reads AND writes are low", "if", "get_gsi_option", "(", "table_key", ",", "gsi_key", ",", "'always_decrease_rw_together'", ")", ":", "read_units", ",", "write_units", "=", "__calculate_always_decrease_rw_values", "(", "table_name", ",", "gsi_name", ",", "read_units", ",", "current_ru", ",", "write_units", ",", "current_wu", ")", "if", "read_units", "==", "current_ru", "and", "write_units", "==", "current_wu", ":", "logger", ".", "info", "(", "'{0} - GSI: {1} - No changes to perform'", ".", "format", "(", "table_name", ",", "gsi_name", ")", ")", "return", "dynamodb", ".", "update_gsi_provisioning", "(", "table_name", ",", "table_key", ",", "gsi_name", ",", "gsi_key", ",", "int", "(", "read_units", ")", ",", "int", "(", "write_units", ")", ")" ]
Update throughput on the GSI :type table_name: str :param table_name: Name of the DynamoDB table :type table_key: str :param table_key: Table configuration option key name :type gsi_name: str :param gsi_name: Name of the GSI :type gsi_key: str :param gsi_key: Configuration option key name :type read_units: int :param read_units: New read unit provisioning :type write_units: int :param write_units: New write unit provisioning
[ "Update", "throughput", "on", "the", "GSI" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/core/gsi.py#L1027-L1088
18,177
sebdah/dynamic-dynamodb
dynamic_dynamodb/core/circuit_breaker.py
is_open
def is_open(table_name=None, table_key=None, gsi_name=None, gsi_key=None): """ Checks whether the circuit breaker is open :param table_name: Name of the table being checked :param table_key: Configuration key for table :param gsi_name: Name of the GSI being checked :param gsi_key: Configuration key for the GSI :returns: bool -- True if the circuit is open """ logger.debug('Checking circuit breaker status') # Parse the URL to make sure it is OK pattern = re.compile( r'^(?P<scheme>http(s)?://)' r'((?P<username>.+):(?P<password>.+)@){0,1}' r'(?P<url>.*)$' ) url = timeout = None if gsi_name: url = get_gsi_option(table_key, gsi_key, 'circuit_breaker_url') timeout = get_gsi_option(table_key, gsi_key, 'circuit_breaker_timeout') elif table_name: url = get_table_option(table_key, 'circuit_breaker_url') timeout = get_table_option(table_key, 'circuit_breaker_timeout') if not url: url = get_global_option('circuit_breaker_url') timeout = get_global_option('circuit_breaker_timeout') match = pattern.match(url) if not match: logger.error('Malformatted URL: {0}'.format(url)) sys.exit(1) use_basic_auth = False if match.group('username') and match.group('password'): use_basic_auth = True # Make the actual URL to call auth = () if use_basic_auth: url = '{scheme}{url}'.format( scheme=match.group('scheme'), url=match.group('url')) auth = (match.group('username'), match.group('password')) headers = {} if table_name: headers["x-table-name"] = table_name if gsi_name: headers["x-gsi-name"] = gsi_name # Make the actual request try: response = requests.get( url, auth=auth, timeout=timeout / 1000.00, headers=headers) if int(response.status_code) >= 200 and int(response.status_code) < 300: logger.info('Circuit breaker is closed') return False else: logger.warning( 'Circuit breaker returned with status code {0:d}'.format( response.status_code)) except requests.exceptions.SSLError as error: logger.warning('Circuit breaker: {0}'.format(error)) except requests.exceptions.Timeout as error: logger.warning('Circuit breaker: {0}'.format(error)) except requests.exceptions.ConnectionError as error: logger.warning('Circuit breaker: {0}'.format(error)) except requests.exceptions.HTTPError as error: logger.warning('Circuit breaker: {0}'.format(error)) except requests.exceptions.TooManyRedirects as error: logger.warning('Circuit breaker: {0}'.format(error)) except Exception as error: logger.error('Unhandled exception: {0}'.format(error)) logger.error( 'Please file a bug at ' 'https://github.com/sebdah/dynamic-dynamodb/issues') return True
python
def is_open(table_name=None, table_key=None, gsi_name=None, gsi_key=None): """ Checks whether the circuit breaker is open :param table_name: Name of the table being checked :param table_key: Configuration key for table :param gsi_name: Name of the GSI being checked :param gsi_key: Configuration key for the GSI :returns: bool -- True if the circuit is open """ logger.debug('Checking circuit breaker status') # Parse the URL to make sure it is OK pattern = re.compile( r'^(?P<scheme>http(s)?://)' r'((?P<username>.+):(?P<password>.+)@){0,1}' r'(?P<url>.*)$' ) url = timeout = None if gsi_name: url = get_gsi_option(table_key, gsi_key, 'circuit_breaker_url') timeout = get_gsi_option(table_key, gsi_key, 'circuit_breaker_timeout') elif table_name: url = get_table_option(table_key, 'circuit_breaker_url') timeout = get_table_option(table_key, 'circuit_breaker_timeout') if not url: url = get_global_option('circuit_breaker_url') timeout = get_global_option('circuit_breaker_timeout') match = pattern.match(url) if not match: logger.error('Malformatted URL: {0}'.format(url)) sys.exit(1) use_basic_auth = False if match.group('username') and match.group('password'): use_basic_auth = True # Make the actual URL to call auth = () if use_basic_auth: url = '{scheme}{url}'.format( scheme=match.group('scheme'), url=match.group('url')) auth = (match.group('username'), match.group('password')) headers = {} if table_name: headers["x-table-name"] = table_name if gsi_name: headers["x-gsi-name"] = gsi_name # Make the actual request try: response = requests.get( url, auth=auth, timeout=timeout / 1000.00, headers=headers) if int(response.status_code) >= 200 and int(response.status_code) < 300: logger.info('Circuit breaker is closed') return False else: logger.warning( 'Circuit breaker returned with status code {0:d}'.format( response.status_code)) except requests.exceptions.SSLError as error: logger.warning('Circuit breaker: {0}'.format(error)) except requests.exceptions.Timeout as error: logger.warning('Circuit breaker: {0}'.format(error)) except requests.exceptions.ConnectionError as error: logger.warning('Circuit breaker: {0}'.format(error)) except requests.exceptions.HTTPError as error: logger.warning('Circuit breaker: {0}'.format(error)) except requests.exceptions.TooManyRedirects as error: logger.warning('Circuit breaker: {0}'.format(error)) except Exception as error: logger.error('Unhandled exception: {0}'.format(error)) logger.error( 'Please file a bug at ' 'https://github.com/sebdah/dynamic-dynamodb/issues') return True
[ "def", "is_open", "(", "table_name", "=", "None", ",", "table_key", "=", "None", ",", "gsi_name", "=", "None", ",", "gsi_key", "=", "None", ")", ":", "logger", ".", "debug", "(", "'Checking circuit breaker status'", ")", "# Parse the URL to make sure it is OK", "pattern", "=", "re", ".", "compile", "(", "r'^(?P<scheme>http(s)?://)'", "r'((?P<username>.+):(?P<password>.+)@){0,1}'", "r'(?P<url>.*)$'", ")", "url", "=", "timeout", "=", "None", "if", "gsi_name", ":", "url", "=", "get_gsi_option", "(", "table_key", ",", "gsi_key", ",", "'circuit_breaker_url'", ")", "timeout", "=", "get_gsi_option", "(", "table_key", ",", "gsi_key", ",", "'circuit_breaker_timeout'", ")", "elif", "table_name", ":", "url", "=", "get_table_option", "(", "table_key", ",", "'circuit_breaker_url'", ")", "timeout", "=", "get_table_option", "(", "table_key", ",", "'circuit_breaker_timeout'", ")", "if", "not", "url", ":", "url", "=", "get_global_option", "(", "'circuit_breaker_url'", ")", "timeout", "=", "get_global_option", "(", "'circuit_breaker_timeout'", ")", "match", "=", "pattern", ".", "match", "(", "url", ")", "if", "not", "match", ":", "logger", ".", "error", "(", "'Malformatted URL: {0}'", ".", "format", "(", "url", ")", ")", "sys", ".", "exit", "(", "1", ")", "use_basic_auth", "=", "False", "if", "match", ".", "group", "(", "'username'", ")", "and", "match", ".", "group", "(", "'password'", ")", ":", "use_basic_auth", "=", "True", "# Make the actual URL to call", "auth", "=", "(", ")", "if", "use_basic_auth", ":", "url", "=", "'{scheme}{url}'", ".", "format", "(", "scheme", "=", "match", ".", "group", "(", "'scheme'", ")", ",", "url", "=", "match", ".", "group", "(", "'url'", ")", ")", "auth", "=", "(", "match", ".", "group", "(", "'username'", ")", ",", "match", ".", "group", "(", "'password'", ")", ")", "headers", "=", "{", "}", "if", "table_name", ":", "headers", "[", "\"x-table-name\"", "]", "=", "table_name", "if", "gsi_name", ":", "headers", "[", "\"x-gsi-name\"", "]", "=", "gsi_name", "# Make the actual request", "try", ":", "response", "=", "requests", ".", "get", "(", "url", ",", "auth", "=", "auth", ",", "timeout", "=", "timeout", "/", "1000.00", ",", "headers", "=", "headers", ")", "if", "int", "(", "response", ".", "status_code", ")", ">=", "200", "and", "int", "(", "response", ".", "status_code", ")", "<", "300", ":", "logger", ".", "info", "(", "'Circuit breaker is closed'", ")", "return", "False", "else", ":", "logger", ".", "warning", "(", "'Circuit breaker returned with status code {0:d}'", ".", "format", "(", "response", ".", "status_code", ")", ")", "except", "requests", ".", "exceptions", ".", "SSLError", "as", "error", ":", "logger", ".", "warning", "(", "'Circuit breaker: {0}'", ".", "format", "(", "error", ")", ")", "except", "requests", ".", "exceptions", ".", "Timeout", "as", "error", ":", "logger", ".", "warning", "(", "'Circuit breaker: {0}'", ".", "format", "(", "error", ")", ")", "except", "requests", ".", "exceptions", ".", "ConnectionError", "as", "error", ":", "logger", ".", "warning", "(", "'Circuit breaker: {0}'", ".", "format", "(", "error", ")", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", "as", "error", ":", "logger", ".", "warning", "(", "'Circuit breaker: {0}'", ".", "format", "(", "error", ")", ")", "except", "requests", ".", "exceptions", ".", "TooManyRedirects", "as", "error", ":", "logger", ".", "warning", "(", "'Circuit breaker: {0}'", ".", "format", "(", "error", ")", ")", "except", "Exception", "as", "error", ":", "logger", ".", "error", "(", "'Unhandled exception: {0}'", ".", "format", "(", "error", ")", ")", "logger", ".", "error", "(", "'Please file a bug at '", "'https://github.com/sebdah/dynamic-dynamodb/issues'", ")", "return", "True" ]
Checks whether the circuit breaker is open :param table_name: Name of the table being checked :param table_key: Configuration key for table :param gsi_name: Name of the GSI being checked :param gsi_key: Configuration key for the GSI :returns: bool -- True if the circuit is open
[ "Checks", "whether", "the", "circuit", "breaker", "is", "open" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/core/circuit_breaker.py#L13-L97
18,178
sebdah/dynamic-dynamodb
dynamic_dynamodb/aws/cloudwatch.py
__get_connection_cloudwatch
def __get_connection_cloudwatch(): """ Ensure connection to CloudWatch """ region = get_global_option('region') try: if (get_global_option('aws_access_key_id') and get_global_option('aws_secret_access_key')): logger.debug( 'Authenticating to CloudWatch using ' 'credentials in configuration file') connection = cloudwatch.connect_to_region( region, aws_access_key_id=get_global_option('aws_access_key_id'), aws_secret_access_key=get_global_option( 'aws_secret_access_key')) else: logger.debug( 'Authenticating using boto\'s authentication handler') connection = cloudwatch.connect_to_region(region) except Exception as err: logger.error('Failed connecting to CloudWatch: {0}'.format(err)) logger.error( 'Please report an issue at: ' 'https://github.com/sebdah/dynamic-dynamodb/issues') raise logger.debug('Connected to CloudWatch in {0}'.format(region)) return connection
python
def __get_connection_cloudwatch(): """ Ensure connection to CloudWatch """ region = get_global_option('region') try: if (get_global_option('aws_access_key_id') and get_global_option('aws_secret_access_key')): logger.debug( 'Authenticating to CloudWatch using ' 'credentials in configuration file') connection = cloudwatch.connect_to_region( region, aws_access_key_id=get_global_option('aws_access_key_id'), aws_secret_access_key=get_global_option( 'aws_secret_access_key')) else: logger.debug( 'Authenticating using boto\'s authentication handler') connection = cloudwatch.connect_to_region(region) except Exception as err: logger.error('Failed connecting to CloudWatch: {0}'.format(err)) logger.error( 'Please report an issue at: ' 'https://github.com/sebdah/dynamic-dynamodb/issues') raise logger.debug('Connected to CloudWatch in {0}'.format(region)) return connection
[ "def", "__get_connection_cloudwatch", "(", ")", ":", "region", "=", "get_global_option", "(", "'region'", ")", "try", ":", "if", "(", "get_global_option", "(", "'aws_access_key_id'", ")", "and", "get_global_option", "(", "'aws_secret_access_key'", ")", ")", ":", "logger", ".", "debug", "(", "'Authenticating to CloudWatch using '", "'credentials in configuration file'", ")", "connection", "=", "cloudwatch", ".", "connect_to_region", "(", "region", ",", "aws_access_key_id", "=", "get_global_option", "(", "'aws_access_key_id'", ")", ",", "aws_secret_access_key", "=", "get_global_option", "(", "'aws_secret_access_key'", ")", ")", "else", ":", "logger", ".", "debug", "(", "'Authenticating using boto\\'s authentication handler'", ")", "connection", "=", "cloudwatch", ".", "connect_to_region", "(", "region", ")", "except", "Exception", "as", "err", ":", "logger", ".", "error", "(", "'Failed connecting to CloudWatch: {0}'", ".", "format", "(", "err", ")", ")", "logger", ".", "error", "(", "'Please report an issue at: '", "'https://github.com/sebdah/dynamic-dynamodb/issues'", ")", "raise", "logger", ".", "debug", "(", "'Connected to CloudWatch in {0}'", ".", "format", "(", "region", ")", ")", "return", "connection" ]
Ensure connection to CloudWatch
[ "Ensure", "connection", "to", "CloudWatch" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/aws/cloudwatch.py#L9-L36
18,179
sebdah/dynamic-dynamodb
dynamic_dynamodb/aws/dynamodb.py
get_tables_and_gsis
def get_tables_and_gsis(): """ Get a set of tables and gsis and their configuration keys :returns: set -- A set of tuples (table_name, table_conf_key) """ table_names = set() configured_tables = get_configured_tables() not_used_tables = set(configured_tables) # Add regexp table names for table_instance in list_tables(): for key_name in configured_tables: try: if re.match(key_name, table_instance.table_name): logger.debug("Table {0} match with config key {1}".format( table_instance.table_name, key_name)) # Notify users about regexps that match multiple tables if table_instance.table_name in [x[0] for x in table_names]: logger.warning( 'Table {0} matches more than one regexp in config, ' 'skipping this match: "{1}"'.format( table_instance.table_name, key_name)) else: table_names.add( ( table_instance.table_name, key_name )) not_used_tables.discard(key_name) else: logger.debug( "Table {0} did not match with config key {1}".format( table_instance.table_name, key_name)) except re.error: logger.error('Invalid regular expression: "{0}"'.format( key_name)) sys.exit(1) if not_used_tables: logger.warning( 'No tables matching the following configured ' 'tables found: {0}'.format(', '.join(not_used_tables))) return sorted(table_names)
python
def get_tables_and_gsis(): """ Get a set of tables and gsis and their configuration keys :returns: set -- A set of tuples (table_name, table_conf_key) """ table_names = set() configured_tables = get_configured_tables() not_used_tables = set(configured_tables) # Add regexp table names for table_instance in list_tables(): for key_name in configured_tables: try: if re.match(key_name, table_instance.table_name): logger.debug("Table {0} match with config key {1}".format( table_instance.table_name, key_name)) # Notify users about regexps that match multiple tables if table_instance.table_name in [x[0] for x in table_names]: logger.warning( 'Table {0} matches more than one regexp in config, ' 'skipping this match: "{1}"'.format( table_instance.table_name, key_name)) else: table_names.add( ( table_instance.table_name, key_name )) not_used_tables.discard(key_name) else: logger.debug( "Table {0} did not match with config key {1}".format( table_instance.table_name, key_name)) except re.error: logger.error('Invalid regular expression: "{0}"'.format( key_name)) sys.exit(1) if not_used_tables: logger.warning( 'No tables matching the following configured ' 'tables found: {0}'.format(', '.join(not_used_tables))) return sorted(table_names)
[ "def", "get_tables_and_gsis", "(", ")", ":", "table_names", "=", "set", "(", ")", "configured_tables", "=", "get_configured_tables", "(", ")", "not_used_tables", "=", "set", "(", "configured_tables", ")", "# Add regexp table names", "for", "table_instance", "in", "list_tables", "(", ")", ":", "for", "key_name", "in", "configured_tables", ":", "try", ":", "if", "re", ".", "match", "(", "key_name", ",", "table_instance", ".", "table_name", ")", ":", "logger", ".", "debug", "(", "\"Table {0} match with config key {1}\"", ".", "format", "(", "table_instance", ".", "table_name", ",", "key_name", ")", ")", "# Notify users about regexps that match multiple tables", "if", "table_instance", ".", "table_name", "in", "[", "x", "[", "0", "]", "for", "x", "in", "table_names", "]", ":", "logger", ".", "warning", "(", "'Table {0} matches more than one regexp in config, '", "'skipping this match: \"{1}\"'", ".", "format", "(", "table_instance", ".", "table_name", ",", "key_name", ")", ")", "else", ":", "table_names", ".", "add", "(", "(", "table_instance", ".", "table_name", ",", "key_name", ")", ")", "not_used_tables", ".", "discard", "(", "key_name", ")", "else", ":", "logger", ".", "debug", "(", "\"Table {0} did not match with config key {1}\"", ".", "format", "(", "table_instance", ".", "table_name", ",", "key_name", ")", ")", "except", "re", ".", "error", ":", "logger", ".", "error", "(", "'Invalid regular expression: \"{0}\"'", ".", "format", "(", "key_name", ")", ")", "sys", ".", "exit", "(", "1", ")", "if", "not_used_tables", ":", "logger", ".", "warning", "(", "'No tables matching the following configured '", "'tables found: {0}'", ".", "format", "(", "', '", ".", "join", "(", "not_used_tables", ")", ")", ")", "return", "sorted", "(", "table_names", ")" ]
Get a set of tables and gsis and their configuration keys :returns: set -- A set of tuples (table_name, table_conf_key)
[ "Get", "a", "set", "of", "tables", "and", "gsis", "and", "their", "configuration", "keys" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/aws/dynamodb.py#L21-L65
18,180
sebdah/dynamic-dynamodb
dynamic_dynamodb/aws/dynamodb.py
list_tables
def list_tables(): """ Return list of DynamoDB tables available from AWS :returns: list -- List of DynamoDB tables """ tables = [] try: table_list = DYNAMODB_CONNECTION.list_tables() while True: for table_name in table_list[u'TableNames']: tables.append(get_table(table_name)) if u'LastEvaluatedTableName' in table_list: table_list = DYNAMODB_CONNECTION.list_tables( table_list[u'LastEvaluatedTableName']) else: break except DynamoDBResponseError as error: dynamodb_error = error.body['__type'].rsplit('#', 1)[1] if dynamodb_error == 'ResourceNotFoundException': logger.error('No tables found') elif dynamodb_error == 'AccessDeniedException': logger.debug( 'Your AWS API keys lack access to listing tables. ' 'That is an issue if you are trying to use regular ' 'expressions in your table configuration.') elif dynamodb_error == 'UnrecognizedClientException': logger.error( 'Invalid security token. Are your AWS API keys correct?') else: logger.error( ( 'Unhandled exception: {0}: {1}. ' 'Please file a bug report at ' 'https://github.com/sebdah/dynamic-dynamodb/issues' ).format( dynamodb_error, error.body['message'])) except JSONResponseError as error: logger.error('Communication error: {0}'.format(error)) sys.exit(1) return tables
python
def list_tables(): """ Return list of DynamoDB tables available from AWS :returns: list -- List of DynamoDB tables """ tables = [] try: table_list = DYNAMODB_CONNECTION.list_tables() while True: for table_name in table_list[u'TableNames']: tables.append(get_table(table_name)) if u'LastEvaluatedTableName' in table_list: table_list = DYNAMODB_CONNECTION.list_tables( table_list[u'LastEvaluatedTableName']) else: break except DynamoDBResponseError as error: dynamodb_error = error.body['__type'].rsplit('#', 1)[1] if dynamodb_error == 'ResourceNotFoundException': logger.error('No tables found') elif dynamodb_error == 'AccessDeniedException': logger.debug( 'Your AWS API keys lack access to listing tables. ' 'That is an issue if you are trying to use regular ' 'expressions in your table configuration.') elif dynamodb_error == 'UnrecognizedClientException': logger.error( 'Invalid security token. Are your AWS API keys correct?') else: logger.error( ( 'Unhandled exception: {0}: {1}. ' 'Please file a bug report at ' 'https://github.com/sebdah/dynamic-dynamodb/issues' ).format( dynamodb_error, error.body['message'])) except JSONResponseError as error: logger.error('Communication error: {0}'.format(error)) sys.exit(1) return tables
[ "def", "list_tables", "(", ")", ":", "tables", "=", "[", "]", "try", ":", "table_list", "=", "DYNAMODB_CONNECTION", ".", "list_tables", "(", ")", "while", "True", ":", "for", "table_name", "in", "table_list", "[", "u'TableNames'", "]", ":", "tables", ".", "append", "(", "get_table", "(", "table_name", ")", ")", "if", "u'LastEvaluatedTableName'", "in", "table_list", ":", "table_list", "=", "DYNAMODB_CONNECTION", ".", "list_tables", "(", "table_list", "[", "u'LastEvaluatedTableName'", "]", ")", "else", ":", "break", "except", "DynamoDBResponseError", "as", "error", ":", "dynamodb_error", "=", "error", ".", "body", "[", "'__type'", "]", ".", "rsplit", "(", "'#'", ",", "1", ")", "[", "1", "]", "if", "dynamodb_error", "==", "'ResourceNotFoundException'", ":", "logger", ".", "error", "(", "'No tables found'", ")", "elif", "dynamodb_error", "==", "'AccessDeniedException'", ":", "logger", ".", "debug", "(", "'Your AWS API keys lack access to listing tables. '", "'That is an issue if you are trying to use regular '", "'expressions in your table configuration.'", ")", "elif", "dynamodb_error", "==", "'UnrecognizedClientException'", ":", "logger", ".", "error", "(", "'Invalid security token. Are your AWS API keys correct?'", ")", "else", ":", "logger", ".", "error", "(", "(", "'Unhandled exception: {0}: {1}. '", "'Please file a bug report at '", "'https://github.com/sebdah/dynamic-dynamodb/issues'", ")", ".", "format", "(", "dynamodb_error", ",", "error", ".", "body", "[", "'message'", "]", ")", ")", "except", "JSONResponseError", "as", "error", ":", "logger", ".", "error", "(", "'Communication error: {0}'", ".", "format", "(", "error", ")", ")", "sys", ".", "exit", "(", "1", ")", "return", "tables" ]
Return list of DynamoDB tables available from AWS :returns: list -- List of DynamoDB tables
[ "Return", "list", "of", "DynamoDB", "tables", "available", "from", "AWS" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/aws/dynamodb.py#L214-L260
18,181
sebdah/dynamic-dynamodb
dynamic_dynamodb/aws/dynamodb.py
table_gsis
def table_gsis(table_name): """ Returns a list of GSIs for the given table :type table_name: str :param table_name: Name of the DynamoDB table :returns: list -- List of GSI names """ try: desc = DYNAMODB_CONNECTION.describe_table(table_name)[u'Table'] except JSONResponseError: raise if u'GlobalSecondaryIndexes' in desc: return desc[u'GlobalSecondaryIndexes'] return []
python
def table_gsis(table_name): """ Returns a list of GSIs for the given table :type table_name: str :param table_name: Name of the DynamoDB table :returns: list -- List of GSI names """ try: desc = DYNAMODB_CONNECTION.describe_table(table_name)[u'Table'] except JSONResponseError: raise if u'GlobalSecondaryIndexes' in desc: return desc[u'GlobalSecondaryIndexes'] return []
[ "def", "table_gsis", "(", "table_name", ")", ":", "try", ":", "desc", "=", "DYNAMODB_CONNECTION", ".", "describe_table", "(", "table_name", ")", "[", "u'Table'", "]", "except", "JSONResponseError", ":", "raise", "if", "u'GlobalSecondaryIndexes'", "in", "desc", ":", "return", "desc", "[", "u'GlobalSecondaryIndexes'", "]", "return", "[", "]" ]
Returns a list of GSIs for the given table :type table_name: str :param table_name: Name of the DynamoDB table :returns: list -- List of GSI names
[ "Returns", "a", "list", "of", "GSIs", "for", "the", "given", "table" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/aws/dynamodb.py#L602-L617
18,182
sebdah/dynamic-dynamodb
dynamic_dynamodb/aws/dynamodb.py
__get_connection_dynamodb
def __get_connection_dynamodb(retries=3): """ Ensure connection to DynamoDB :type retries: int :param retries: Number of times to retry to connect to DynamoDB """ connected = False region = get_global_option('region') while not connected: if (get_global_option('aws_access_key_id') and get_global_option('aws_secret_access_key')): logger.debug( 'Authenticating to DynamoDB using ' 'credentials in configuration file') connection = dynamodb2.connect_to_region( region, aws_access_key_id=get_global_option('aws_access_key_id'), aws_secret_access_key=get_global_option( 'aws_secret_access_key')) else: logger.debug( 'Authenticating using boto\'s authentication handler') connection = dynamodb2.connect_to_region(region) if not connection: if retries == 0: logger.error('Failed to connect to DynamoDB. Giving up.') raise else: logger.error( 'Failed to connect to DynamoDB. Retrying in 5 seconds') retries -= 1 time.sleep(5) else: connected = True logger.debug('Connected to DynamoDB in {0}'.format(region)) return connection
python
def __get_connection_dynamodb(retries=3): """ Ensure connection to DynamoDB :type retries: int :param retries: Number of times to retry to connect to DynamoDB """ connected = False region = get_global_option('region') while not connected: if (get_global_option('aws_access_key_id') and get_global_option('aws_secret_access_key')): logger.debug( 'Authenticating to DynamoDB using ' 'credentials in configuration file') connection = dynamodb2.connect_to_region( region, aws_access_key_id=get_global_option('aws_access_key_id'), aws_secret_access_key=get_global_option( 'aws_secret_access_key')) else: logger.debug( 'Authenticating using boto\'s authentication handler') connection = dynamodb2.connect_to_region(region) if not connection: if retries == 0: logger.error('Failed to connect to DynamoDB. Giving up.') raise else: logger.error( 'Failed to connect to DynamoDB. Retrying in 5 seconds') retries -= 1 time.sleep(5) else: connected = True logger.debug('Connected to DynamoDB in {0}'.format(region)) return connection
[ "def", "__get_connection_dynamodb", "(", "retries", "=", "3", ")", ":", "connected", "=", "False", "region", "=", "get_global_option", "(", "'region'", ")", "while", "not", "connected", ":", "if", "(", "get_global_option", "(", "'aws_access_key_id'", ")", "and", "get_global_option", "(", "'aws_secret_access_key'", ")", ")", ":", "logger", ".", "debug", "(", "'Authenticating to DynamoDB using '", "'credentials in configuration file'", ")", "connection", "=", "dynamodb2", ".", "connect_to_region", "(", "region", ",", "aws_access_key_id", "=", "get_global_option", "(", "'aws_access_key_id'", ")", ",", "aws_secret_access_key", "=", "get_global_option", "(", "'aws_secret_access_key'", ")", ")", "else", ":", "logger", ".", "debug", "(", "'Authenticating using boto\\'s authentication handler'", ")", "connection", "=", "dynamodb2", ".", "connect_to_region", "(", "region", ")", "if", "not", "connection", ":", "if", "retries", "==", "0", ":", "logger", ".", "error", "(", "'Failed to connect to DynamoDB. Giving up.'", ")", "raise", "else", ":", "logger", ".", "error", "(", "'Failed to connect to DynamoDB. Retrying in 5 seconds'", ")", "retries", "-=", "1", "time", ".", "sleep", "(", "5", ")", "else", ":", "connected", "=", "True", "logger", ".", "debug", "(", "'Connected to DynamoDB in {0}'", ".", "format", "(", "region", ")", ")", "return", "connection" ]
Ensure connection to DynamoDB :type retries: int :param retries: Number of times to retry to connect to DynamoDB
[ "Ensure", "connection", "to", "DynamoDB" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/aws/dynamodb.py#L620-L658
18,183
sebdah/dynamic-dynamodb
dynamic_dynamodb/aws/dynamodb.py
__is_gsi_maintenance_window
def __is_gsi_maintenance_window(table_name, gsi_name, maintenance_windows): """ Checks that the current time is within the maintenance window :type table_name: str :param table_name: Name of the DynamoDB table :type gsi_name: str :param gsi_name: Name of the GSI :type maintenance_windows: str :param maintenance_windows: Example: '00:00-01:00,10:00-11:00' :returns: bool -- True if within maintenance window """ # Example string '00:00-01:00,10:00-11:00' maintenance_window_list = [] for window in maintenance_windows.split(','): try: start, end = window.split('-', 1) except ValueError: logger.error( '{0} - GSI: {1} - ' 'Malformatted maintenance window'.format(table_name, gsi_name)) return False maintenance_window_list.append((start, end)) now = datetime.datetime.utcnow().strftime('%H%M') for maintenance_window in maintenance_window_list: start = ''.join(maintenance_window[0].split(':')) end = ''.join(maintenance_window[1].split(':')) if now >= start and now <= end: return True return False
python
def __is_gsi_maintenance_window(table_name, gsi_name, maintenance_windows): """ Checks that the current time is within the maintenance window :type table_name: str :param table_name: Name of the DynamoDB table :type gsi_name: str :param gsi_name: Name of the GSI :type maintenance_windows: str :param maintenance_windows: Example: '00:00-01:00,10:00-11:00' :returns: bool -- True if within maintenance window """ # Example string '00:00-01:00,10:00-11:00' maintenance_window_list = [] for window in maintenance_windows.split(','): try: start, end = window.split('-', 1) except ValueError: logger.error( '{0} - GSI: {1} - ' 'Malformatted maintenance window'.format(table_name, gsi_name)) return False maintenance_window_list.append((start, end)) now = datetime.datetime.utcnow().strftime('%H%M') for maintenance_window in maintenance_window_list: start = ''.join(maintenance_window[0].split(':')) end = ''.join(maintenance_window[1].split(':')) if now >= start and now <= end: return True return False
[ "def", "__is_gsi_maintenance_window", "(", "table_name", ",", "gsi_name", ",", "maintenance_windows", ")", ":", "# Example string '00:00-01:00,10:00-11:00'", "maintenance_window_list", "=", "[", "]", "for", "window", "in", "maintenance_windows", ".", "split", "(", "','", ")", ":", "try", ":", "start", ",", "end", "=", "window", ".", "split", "(", "'-'", ",", "1", ")", "except", "ValueError", ":", "logger", ".", "error", "(", "'{0} - GSI: {1} - '", "'Malformatted maintenance window'", ".", "format", "(", "table_name", ",", "gsi_name", ")", ")", "return", "False", "maintenance_window_list", ".", "append", "(", "(", "start", ",", "end", ")", ")", "now", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "'%H%M'", ")", "for", "maintenance_window", "in", "maintenance_window_list", ":", "start", "=", "''", ".", "join", "(", "maintenance_window", "[", "0", "]", ".", "split", "(", "':'", ")", ")", "end", "=", "''", ".", "join", "(", "maintenance_window", "[", "1", "]", ".", "split", "(", "':'", ")", ")", "if", "now", ">=", "start", "and", "now", "<=", "end", ":", "return", "True", "return", "False" ]
Checks that the current time is within the maintenance window :type table_name: str :param table_name: Name of the DynamoDB table :type gsi_name: str :param gsi_name: Name of the GSI :type maintenance_windows: str :param maintenance_windows: Example: '00:00-01:00,10:00-11:00' :returns: bool -- True if within maintenance window
[ "Checks", "that", "the", "current", "time", "is", "within", "the", "maintenance", "window" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/aws/dynamodb.py#L661-L692
18,184
sebdah/dynamic-dynamodb
dynamic_dynamodb/aws/sns.py
publish_gsi_notification
def publish_gsi_notification( table_key, gsi_key, message, message_types, subject=None): """ Publish a notification for a specific GSI :type table_key: str :param table_key: Table configuration option key name :type gsi_key: str :param gsi_key: Table configuration option key name :type message: str :param message: Message to send via SNS :type message_types: list :param message_types: List with types: - scale-up - scale-down - high-throughput-alarm - low-throughput-alarm :type subject: str :param subject: Subject to use for e-mail notifications :returns: None """ topic = get_gsi_option(table_key, gsi_key, 'sns_topic_arn') if not topic: return for message_type in message_types: if (message_type in get_gsi_option(table_key, gsi_key, 'sns_message_types')): __publish(topic, message, subject) return
python
def publish_gsi_notification( table_key, gsi_key, message, message_types, subject=None): """ Publish a notification for a specific GSI :type table_key: str :param table_key: Table configuration option key name :type gsi_key: str :param gsi_key: Table configuration option key name :type message: str :param message: Message to send via SNS :type message_types: list :param message_types: List with types: - scale-up - scale-down - high-throughput-alarm - low-throughput-alarm :type subject: str :param subject: Subject to use for e-mail notifications :returns: None """ topic = get_gsi_option(table_key, gsi_key, 'sns_topic_arn') if not topic: return for message_type in message_types: if (message_type in get_gsi_option(table_key, gsi_key, 'sns_message_types')): __publish(topic, message, subject) return
[ "def", "publish_gsi_notification", "(", "table_key", ",", "gsi_key", ",", "message", ",", "message_types", ",", "subject", "=", "None", ")", ":", "topic", "=", "get_gsi_option", "(", "table_key", ",", "gsi_key", ",", "'sns_topic_arn'", ")", "if", "not", "topic", ":", "return", "for", "message_type", "in", "message_types", ":", "if", "(", "message_type", "in", "get_gsi_option", "(", "table_key", ",", "gsi_key", ",", "'sns_message_types'", ")", ")", ":", "__publish", "(", "topic", ",", "message", ",", "subject", ")", "return" ]
Publish a notification for a specific GSI :type table_key: str :param table_key: Table configuration option key name :type gsi_key: str :param gsi_key: Table configuration option key name :type message: str :param message: Message to send via SNS :type message_types: list :param message_types: List with types: - scale-up - scale-down - high-throughput-alarm - low-throughput-alarm :type subject: str :param subject: Subject to use for e-mail notifications :returns: None
[ "Publish", "a", "notification", "for", "a", "specific", "GSI" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/aws/sns.py#L11-L40
18,185
sebdah/dynamic-dynamodb
dynamic_dynamodb/aws/sns.py
publish_table_notification
def publish_table_notification(table_key, message, message_types, subject=None): """ Publish a notification for a specific table :type table_key: str :param table_key: Table configuration option key name :type message: str :param message: Message to send via SNS :type message_types: list :param message_types: List with types: - scale-up - scale-down - high-throughput-alarm - low-throughput-alarm :type subject: str :param subject: Subject to use for e-mail notifications :returns: None """ topic = get_table_option(table_key, 'sns_topic_arn') if not topic: return for message_type in message_types: if message_type in get_table_option(table_key, 'sns_message_types'): __publish(topic, message, subject) return
python
def publish_table_notification(table_key, message, message_types, subject=None): """ Publish a notification for a specific table :type table_key: str :param table_key: Table configuration option key name :type message: str :param message: Message to send via SNS :type message_types: list :param message_types: List with types: - scale-up - scale-down - high-throughput-alarm - low-throughput-alarm :type subject: str :param subject: Subject to use for e-mail notifications :returns: None """ topic = get_table_option(table_key, 'sns_topic_arn') if not topic: return for message_type in message_types: if message_type in get_table_option(table_key, 'sns_message_types'): __publish(topic, message, subject) return
[ "def", "publish_table_notification", "(", "table_key", ",", "message", ",", "message_types", ",", "subject", "=", "None", ")", ":", "topic", "=", "get_table_option", "(", "table_key", ",", "'sns_topic_arn'", ")", "if", "not", "topic", ":", "return", "for", "message_type", "in", "message_types", ":", "if", "message_type", "in", "get_table_option", "(", "table_key", ",", "'sns_message_types'", ")", ":", "__publish", "(", "topic", ",", "message", ",", "subject", ")", "return" ]
Publish a notification for a specific table :type table_key: str :param table_key: Table configuration option key name :type message: str :param message: Message to send via SNS :type message_types: list :param message_types: List with types: - scale-up - scale-down - high-throughput-alarm - low-throughput-alarm :type subject: str :param subject: Subject to use for e-mail notifications :returns: None
[ "Publish", "a", "notification", "for", "a", "specific", "table" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/aws/sns.py#L43-L68
18,186
sebdah/dynamic-dynamodb
dynamic_dynamodb/aws/sns.py
__publish
def __publish(topic, message, subject=None): """ Publish a message to a SNS topic :type topic: str :param topic: SNS topic to publish the message to :type message: str :param message: Message to send via SNS :type subject: str :param subject: Subject to use for e-mail notifications :returns: None """ try: SNS_CONNECTION.publish(topic=topic, message=message, subject=subject) logger.info('Sent SNS notification to {0}'.format(topic)) except BotoServerError as error: logger.error('Problem sending SNS notification: {0}'.format( error.message)) return
python
def __publish(topic, message, subject=None): """ Publish a message to a SNS topic :type topic: str :param topic: SNS topic to publish the message to :type message: str :param message: Message to send via SNS :type subject: str :param subject: Subject to use for e-mail notifications :returns: None """ try: SNS_CONNECTION.publish(topic=topic, message=message, subject=subject) logger.info('Sent SNS notification to {0}'.format(topic)) except BotoServerError as error: logger.error('Problem sending SNS notification: {0}'.format( error.message)) return
[ "def", "__publish", "(", "topic", ",", "message", ",", "subject", "=", "None", ")", ":", "try", ":", "SNS_CONNECTION", ".", "publish", "(", "topic", "=", "topic", ",", "message", "=", "message", ",", "subject", "=", "subject", ")", "logger", ".", "info", "(", "'Sent SNS notification to {0}'", ".", "format", "(", "topic", ")", ")", "except", "BotoServerError", "as", "error", ":", "logger", ".", "error", "(", "'Problem sending SNS notification: {0}'", ".", "format", "(", "error", ".", "message", ")", ")", "return" ]
Publish a message to a SNS topic :type topic: str :param topic: SNS topic to publish the message to :type message: str :param message: Message to send via SNS :type subject: str :param subject: Subject to use for e-mail notifications :returns: None
[ "Publish", "a", "message", "to", "a", "SNS", "topic" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/aws/sns.py#L71-L89
18,187
sebdah/dynamic-dynamodb
dynamic_dynamodb/aws/sns.py
__get_connection_SNS
def __get_connection_SNS(): """ Ensure connection to SNS """ region = get_global_option('region') try: if (get_global_option('aws_access_key_id') and get_global_option('aws_secret_access_key')): logger.debug( 'Authenticating to SNS using ' 'credentials in configuration file') connection = sns.connect_to_region( region, aws_access_key_id=get_global_option( 'aws_access_key_id'), aws_secret_access_key=get_global_option( 'aws_secret_access_key')) else: logger.debug( 'Authenticating using boto\'s authentication handler') connection = sns.connect_to_region(region) except Exception as err: logger.error('Failed connecting to SNS: {0}'.format(err)) logger.error( 'Please report an issue at: ' 'https://github.com/sebdah/dynamic-dynamodb/issues') raise logger.debug('Connected to SNS in {0}'.format(region)) return connection
python
def __get_connection_SNS(): """ Ensure connection to SNS """ region = get_global_option('region') try: if (get_global_option('aws_access_key_id') and get_global_option('aws_secret_access_key')): logger.debug( 'Authenticating to SNS using ' 'credentials in configuration file') connection = sns.connect_to_region( region, aws_access_key_id=get_global_option( 'aws_access_key_id'), aws_secret_access_key=get_global_option( 'aws_secret_access_key')) else: logger.debug( 'Authenticating using boto\'s authentication handler') connection = sns.connect_to_region(region) except Exception as err: logger.error('Failed connecting to SNS: {0}'.format(err)) logger.error( 'Please report an issue at: ' 'https://github.com/sebdah/dynamic-dynamodb/issues') raise logger.debug('Connected to SNS in {0}'.format(region)) return connection
[ "def", "__get_connection_SNS", "(", ")", ":", "region", "=", "get_global_option", "(", "'region'", ")", "try", ":", "if", "(", "get_global_option", "(", "'aws_access_key_id'", ")", "and", "get_global_option", "(", "'aws_secret_access_key'", ")", ")", ":", "logger", ".", "debug", "(", "'Authenticating to SNS using '", "'credentials in configuration file'", ")", "connection", "=", "sns", ".", "connect_to_region", "(", "region", ",", "aws_access_key_id", "=", "get_global_option", "(", "'aws_access_key_id'", ")", ",", "aws_secret_access_key", "=", "get_global_option", "(", "'aws_secret_access_key'", ")", ")", "else", ":", "logger", ".", "debug", "(", "'Authenticating using boto\\'s authentication handler'", ")", "connection", "=", "sns", ".", "connect_to_region", "(", "region", ")", "except", "Exception", "as", "err", ":", "logger", ".", "error", "(", "'Failed connecting to SNS: {0}'", ".", "format", "(", "err", ")", ")", "logger", ".", "error", "(", "'Please report an issue at: '", "'https://github.com/sebdah/dynamic-dynamodb/issues'", ")", "raise", "logger", ".", "debug", "(", "'Connected to SNS in {0}'", ".", "format", "(", "region", ")", ")", "return", "connection" ]
Ensure connection to SNS
[ "Ensure", "connection", "to", "SNS" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/aws/sns.py#L92-L121
18,188
sebdah/dynamic-dynamodb
dynamic_dynamodb/core/table.py
__calculate_always_decrease_rw_values
def __calculate_always_decrease_rw_values( table_name, read_units, provisioned_reads, write_units, provisioned_writes): """ Calculate values for always-decrease-rw-together This will only return reads and writes decreases if both reads and writes are lower than the current provisioning :type table_name: str :param table_name: Name of the DynamoDB table :type read_units: int :param read_units: New read unit provisioning :type provisioned_reads: int :param provisioned_reads: Currently provisioned reads :type write_units: int :param write_units: New write unit provisioning :type provisioned_writes: int :param provisioned_writes: Currently provisioned writes :returns: (int, int) -- (reads, writes) """ if read_units <= provisioned_reads and write_units <= provisioned_writes: return (read_units, write_units) if read_units < provisioned_reads: logger.info( '{0} - Reads could be decreased, but we are waiting for ' 'writes to get lower than the threshold before ' 'scaling down'.format(table_name)) read_units = provisioned_reads elif write_units < provisioned_writes: logger.info( '{0} - Writes could be decreased, but we are waiting for ' 'reads to get lower than the threshold before ' 'scaling down'.format(table_name)) write_units = provisioned_writes return (read_units, write_units)
python
def __calculate_always_decrease_rw_values( table_name, read_units, provisioned_reads, write_units, provisioned_writes): """ Calculate values for always-decrease-rw-together This will only return reads and writes decreases if both reads and writes are lower than the current provisioning :type table_name: str :param table_name: Name of the DynamoDB table :type read_units: int :param read_units: New read unit provisioning :type provisioned_reads: int :param provisioned_reads: Currently provisioned reads :type write_units: int :param write_units: New write unit provisioning :type provisioned_writes: int :param provisioned_writes: Currently provisioned writes :returns: (int, int) -- (reads, writes) """ if read_units <= provisioned_reads and write_units <= provisioned_writes: return (read_units, write_units) if read_units < provisioned_reads: logger.info( '{0} - Reads could be decreased, but we are waiting for ' 'writes to get lower than the threshold before ' 'scaling down'.format(table_name)) read_units = provisioned_reads elif write_units < provisioned_writes: logger.info( '{0} - Writes could be decreased, but we are waiting for ' 'reads to get lower than the threshold before ' 'scaling down'.format(table_name)) write_units = provisioned_writes return (read_units, write_units)
[ "def", "__calculate_always_decrease_rw_values", "(", "table_name", ",", "read_units", ",", "provisioned_reads", ",", "write_units", ",", "provisioned_writes", ")", ":", "if", "read_units", "<=", "provisioned_reads", "and", "write_units", "<=", "provisioned_writes", ":", "return", "(", "read_units", ",", "write_units", ")", "if", "read_units", "<", "provisioned_reads", ":", "logger", ".", "info", "(", "'{0} - Reads could be decreased, but we are waiting for '", "'writes to get lower than the threshold before '", "'scaling down'", ".", "format", "(", "table_name", ")", ")", "read_units", "=", "provisioned_reads", "elif", "write_units", "<", "provisioned_writes", ":", "logger", ".", "info", "(", "'{0} - Writes could be decreased, but we are waiting for '", "'reads to get lower than the threshold before '", "'scaling down'", ".", "format", "(", "table_name", ")", ")", "write_units", "=", "provisioned_writes", "return", "(", "read_units", ",", "write_units", ")" ]
Calculate values for always-decrease-rw-together This will only return reads and writes decreases if both reads and writes are lower than the current provisioning :type table_name: str :param table_name: Name of the DynamoDB table :type read_units: int :param read_units: New read unit provisioning :type provisioned_reads: int :param provisioned_reads: Currently provisioned reads :type write_units: int :param write_units: New write unit provisioning :type provisioned_writes: int :param provisioned_writes: Currently provisioned writes :returns: (int, int) -- (reads, writes)
[ "Calculate", "values", "for", "always", "-", "decrease", "-", "rw", "-", "together" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/core/table.py#L81-L121
18,189
sebdah/dynamic-dynamodb
dynamic_dynamodb/core/table.py
__update_throughput
def __update_throughput(table_name, key_name, read_units, write_units): """ Update throughput on the DynamoDB table :type table_name: str :param table_name: Name of the DynamoDB table :type key_name: str :param key_name: Configuration option key name :type read_units: int :param read_units: New read unit provisioning :type write_units: int :param write_units: New write unit provisioning """ try: current_ru = dynamodb.get_provisioned_table_read_units(table_name) current_wu = dynamodb.get_provisioned_table_write_units(table_name) except JSONResponseError: raise # Check table status try: table_status = dynamodb.get_table_status(table_name) except JSONResponseError: raise logger.debug('{0} - Table status is {1}'.format(table_name, table_status)) if table_status != 'ACTIVE': logger.warning( '{0} - Not performing throughput changes when table ' 'is {1}'.format(table_name, table_status)) return # If this setting is True, we will only scale down when # BOTH reads AND writes are low if get_table_option(key_name, 'always_decrease_rw_together'): read_units, write_units = __calculate_always_decrease_rw_values( table_name, read_units, current_ru, write_units, current_wu) if read_units == current_ru and write_units == current_wu: logger.info('{0} - No changes to perform'.format(table_name)) return dynamodb.update_table_provisioning( table_name, key_name, int(read_units), int(write_units))
python
def __update_throughput(table_name, key_name, read_units, write_units): """ Update throughput on the DynamoDB table :type table_name: str :param table_name: Name of the DynamoDB table :type key_name: str :param key_name: Configuration option key name :type read_units: int :param read_units: New read unit provisioning :type write_units: int :param write_units: New write unit provisioning """ try: current_ru = dynamodb.get_provisioned_table_read_units(table_name) current_wu = dynamodb.get_provisioned_table_write_units(table_name) except JSONResponseError: raise # Check table status try: table_status = dynamodb.get_table_status(table_name) except JSONResponseError: raise logger.debug('{0} - Table status is {1}'.format(table_name, table_status)) if table_status != 'ACTIVE': logger.warning( '{0} - Not performing throughput changes when table ' 'is {1}'.format(table_name, table_status)) return # If this setting is True, we will only scale down when # BOTH reads AND writes are low if get_table_option(key_name, 'always_decrease_rw_together'): read_units, write_units = __calculate_always_decrease_rw_values( table_name, read_units, current_ru, write_units, current_wu) if read_units == current_ru and write_units == current_wu: logger.info('{0} - No changes to perform'.format(table_name)) return dynamodb.update_table_provisioning( table_name, key_name, int(read_units), int(write_units))
[ "def", "__update_throughput", "(", "table_name", ",", "key_name", ",", "read_units", ",", "write_units", ")", ":", "try", ":", "current_ru", "=", "dynamodb", ".", "get_provisioned_table_read_units", "(", "table_name", ")", "current_wu", "=", "dynamodb", ".", "get_provisioned_table_write_units", "(", "table_name", ")", "except", "JSONResponseError", ":", "raise", "# Check table status", "try", ":", "table_status", "=", "dynamodb", ".", "get_table_status", "(", "table_name", ")", "except", "JSONResponseError", ":", "raise", "logger", ".", "debug", "(", "'{0} - Table status is {1}'", ".", "format", "(", "table_name", ",", "table_status", ")", ")", "if", "table_status", "!=", "'ACTIVE'", ":", "logger", ".", "warning", "(", "'{0} - Not performing throughput changes when table '", "'is {1}'", ".", "format", "(", "table_name", ",", "table_status", ")", ")", "return", "# If this setting is True, we will only scale down when", "# BOTH reads AND writes are low", "if", "get_table_option", "(", "key_name", ",", "'always_decrease_rw_together'", ")", ":", "read_units", ",", "write_units", "=", "__calculate_always_decrease_rw_values", "(", "table_name", ",", "read_units", ",", "current_ru", ",", "write_units", ",", "current_wu", ")", "if", "read_units", "==", "current_ru", "and", "write_units", "==", "current_wu", ":", "logger", ".", "info", "(", "'{0} - No changes to perform'", ".", "format", "(", "table_name", ")", ")", "return", "dynamodb", ".", "update_table_provisioning", "(", "table_name", ",", "key_name", ",", "int", "(", "read_units", ")", ",", "int", "(", "write_units", ")", ")" ]
Update throughput on the DynamoDB table :type table_name: str :param table_name: Name of the DynamoDB table :type key_name: str :param key_name: Configuration option key name :type read_units: int :param read_units: New read unit provisioning :type write_units: int :param write_units: New write unit provisioning
[ "Update", "throughput", "on", "the", "DynamoDB", "table" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/core/table.py#L897-L945
18,190
sebdah/dynamic-dynamodb
dynamic_dynamodb/config/__init__.py
get_configuration
def get_configuration(): """ Get the configuration from command line and config files """ # This is the dict we will return configuration = { 'global': {}, 'logging': {}, 'tables': ordereddict() } # Read the command line options cmd_line_options = command_line_parser.parse() # If a configuration file is specified, read that as well conf_file_options = None if 'config' in cmd_line_options: conf_file_options = config_file_parser.parse( cmd_line_options['config']) # Extract global config configuration['global'] = __get_global_options( cmd_line_options, conf_file_options) # Extract logging config configuration['logging'] = __get_logging_options( cmd_line_options, conf_file_options) # Extract table configuration # If the --table cmd line option is set, it indicates that only table # options from the command line should be used if 'table_name' in cmd_line_options: configuration['tables'] = __get_cmd_table_options(cmd_line_options) else: configuration['tables'] = __get_config_table_options(conf_file_options) # Ensure some basic rules __check_gsi_rules(configuration) __check_logging_rules(configuration) __check_table_rules(configuration) return configuration
python
def get_configuration(): """ Get the configuration from command line and config files """ # This is the dict we will return configuration = { 'global': {}, 'logging': {}, 'tables': ordereddict() } # Read the command line options cmd_line_options = command_line_parser.parse() # If a configuration file is specified, read that as well conf_file_options = None if 'config' in cmd_line_options: conf_file_options = config_file_parser.parse( cmd_line_options['config']) # Extract global config configuration['global'] = __get_global_options( cmd_line_options, conf_file_options) # Extract logging config configuration['logging'] = __get_logging_options( cmd_line_options, conf_file_options) # Extract table configuration # If the --table cmd line option is set, it indicates that only table # options from the command line should be used if 'table_name' in cmd_line_options: configuration['tables'] = __get_cmd_table_options(cmd_line_options) else: configuration['tables'] = __get_config_table_options(conf_file_options) # Ensure some basic rules __check_gsi_rules(configuration) __check_logging_rules(configuration) __check_table_rules(configuration) return configuration
[ "def", "get_configuration", "(", ")", ":", "# This is the dict we will return", "configuration", "=", "{", "'global'", ":", "{", "}", ",", "'logging'", ":", "{", "}", ",", "'tables'", ":", "ordereddict", "(", ")", "}", "# Read the command line options", "cmd_line_options", "=", "command_line_parser", ".", "parse", "(", ")", "# If a configuration file is specified, read that as well", "conf_file_options", "=", "None", "if", "'config'", "in", "cmd_line_options", ":", "conf_file_options", "=", "config_file_parser", ".", "parse", "(", "cmd_line_options", "[", "'config'", "]", ")", "# Extract global config", "configuration", "[", "'global'", "]", "=", "__get_global_options", "(", "cmd_line_options", ",", "conf_file_options", ")", "# Extract logging config", "configuration", "[", "'logging'", "]", "=", "__get_logging_options", "(", "cmd_line_options", ",", "conf_file_options", ")", "# Extract table configuration", "# If the --table cmd line option is set, it indicates that only table", "# options from the command line should be used", "if", "'table_name'", "in", "cmd_line_options", ":", "configuration", "[", "'tables'", "]", "=", "__get_cmd_table_options", "(", "cmd_line_options", ")", "else", ":", "configuration", "[", "'tables'", "]", "=", "__get_config_table_options", "(", "conf_file_options", ")", "# Ensure some basic rules", "__check_gsi_rules", "(", "configuration", ")", "__check_logging_rules", "(", "configuration", ")", "__check_table_rules", "(", "configuration", ")", "return", "configuration" ]
Get the configuration from command line and config files
[ "Get", "the", "configuration", "from", "command", "line", "and", "config", "files" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/config/__init__.py#L162-L203
18,191
sebdah/dynamic-dynamodb
dynamic_dynamodb/config/__init__.py
__get_cmd_table_options
def __get_cmd_table_options(cmd_line_options): """ Get all table options from the command line :type cmd_line_options: dict :param cmd_line_options: Dictionary with all command line options :returns: dict -- E.g. {'table_name': {}} """ table_name = cmd_line_options['table_name'] options = {table_name: {}} for option in DEFAULT_OPTIONS['table'].keys(): options[table_name][option] = DEFAULT_OPTIONS['table'][option] if option in cmd_line_options: options[table_name][option] = cmd_line_options[option] return options
python
def __get_cmd_table_options(cmd_line_options): """ Get all table options from the command line :type cmd_line_options: dict :param cmd_line_options: Dictionary with all command line options :returns: dict -- E.g. {'table_name': {}} """ table_name = cmd_line_options['table_name'] options = {table_name: {}} for option in DEFAULT_OPTIONS['table'].keys(): options[table_name][option] = DEFAULT_OPTIONS['table'][option] if option in cmd_line_options: options[table_name][option] = cmd_line_options[option] return options
[ "def", "__get_cmd_table_options", "(", "cmd_line_options", ")", ":", "table_name", "=", "cmd_line_options", "[", "'table_name'", "]", "options", "=", "{", "table_name", ":", "{", "}", "}", "for", "option", "in", "DEFAULT_OPTIONS", "[", "'table'", "]", ".", "keys", "(", ")", ":", "options", "[", "table_name", "]", "[", "option", "]", "=", "DEFAULT_OPTIONS", "[", "'table'", "]", "[", "option", "]", "if", "option", "in", "cmd_line_options", ":", "options", "[", "table_name", "]", "[", "option", "]", "=", "cmd_line_options", "[", "option", "]", "return", "options" ]
Get all table options from the command line :type cmd_line_options: dict :param cmd_line_options: Dictionary with all command line options :returns: dict -- E.g. {'table_name': {}}
[ "Get", "all", "table", "options", "from", "the", "command", "line" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/config/__init__.py#L206-L222
18,192
sebdah/dynamic-dynamodb
dynamic_dynamodb/config/__init__.py
__get_config_table_options
def __get_config_table_options(conf_file_options): """ Get all table options from the config file :type conf_file_options: ordereddict :param conf_file_options: Dictionary with all config file options :returns: ordereddict -- E.g. {'table_name': {}} """ options = ordereddict() if not conf_file_options: return options for table_name in conf_file_options['tables']: options[table_name] = {} # Regular table options for option in DEFAULT_OPTIONS['table'].keys(): options[table_name][option] = DEFAULT_OPTIONS['table'][option] if option not in conf_file_options['tables'][table_name]: continue if option == 'sns_message_types': try: raw_list = conf_file_options['tables'][table_name][option] options[table_name][option] = \ [i.strip() for i in raw_list.split(',')] except: print( 'Error parsing the "sns-message-types" ' 'option: {0}'.format( conf_file_options['tables'][table_name][option])) else: options[table_name][option] = \ conf_file_options['tables'][table_name][option] # GSI specific options if 'gsis' in conf_file_options['tables'][table_name]: for gsi_name in conf_file_options['tables'][table_name]['gsis']: for option in DEFAULT_OPTIONS['gsi'].keys(): opt = DEFAULT_OPTIONS['gsi'][option] if 'gsis' not in options[table_name]: options[table_name]['gsis'] = {} if gsi_name not in options[table_name]['gsis']: options[table_name]['gsis'][gsi_name] = {} if (option not in conf_file_options[ 'tables'][table_name]['gsis'][gsi_name]): options[table_name]['gsis'][gsi_name][option] = opt continue if option == 'sns_message_types': try: raw_list = conf_file_options[ 'tables'][table_name]['gsis'][gsi_name][option] opt = [i.strip() for i in raw_list.split(',')] except: print( 'Error parsing the "sns-message-types" ' 'option: {0}'.format( conf_file_options[ 'tables'][table_name][ 'gsis'][gsi_name][option])) else: opt = conf_file_options[ 'tables'][table_name]['gsis'][gsi_name][option] options[table_name]['gsis'][gsi_name][option] = opt return options
python
def __get_config_table_options(conf_file_options): """ Get all table options from the config file :type conf_file_options: ordereddict :param conf_file_options: Dictionary with all config file options :returns: ordereddict -- E.g. {'table_name': {}} """ options = ordereddict() if not conf_file_options: return options for table_name in conf_file_options['tables']: options[table_name] = {} # Regular table options for option in DEFAULT_OPTIONS['table'].keys(): options[table_name][option] = DEFAULT_OPTIONS['table'][option] if option not in conf_file_options['tables'][table_name]: continue if option == 'sns_message_types': try: raw_list = conf_file_options['tables'][table_name][option] options[table_name][option] = \ [i.strip() for i in raw_list.split(',')] except: print( 'Error parsing the "sns-message-types" ' 'option: {0}'.format( conf_file_options['tables'][table_name][option])) else: options[table_name][option] = \ conf_file_options['tables'][table_name][option] # GSI specific options if 'gsis' in conf_file_options['tables'][table_name]: for gsi_name in conf_file_options['tables'][table_name]['gsis']: for option in DEFAULT_OPTIONS['gsi'].keys(): opt = DEFAULT_OPTIONS['gsi'][option] if 'gsis' not in options[table_name]: options[table_name]['gsis'] = {} if gsi_name not in options[table_name]['gsis']: options[table_name]['gsis'][gsi_name] = {} if (option not in conf_file_options[ 'tables'][table_name]['gsis'][gsi_name]): options[table_name]['gsis'][gsi_name][option] = opt continue if option == 'sns_message_types': try: raw_list = conf_file_options[ 'tables'][table_name]['gsis'][gsi_name][option] opt = [i.strip() for i in raw_list.split(',')] except: print( 'Error parsing the "sns-message-types" ' 'option: {0}'.format( conf_file_options[ 'tables'][table_name][ 'gsis'][gsi_name][option])) else: opt = conf_file_options[ 'tables'][table_name]['gsis'][gsi_name][option] options[table_name]['gsis'][gsi_name][option] = opt return options
[ "def", "__get_config_table_options", "(", "conf_file_options", ")", ":", "options", "=", "ordereddict", "(", ")", "if", "not", "conf_file_options", ":", "return", "options", "for", "table_name", "in", "conf_file_options", "[", "'tables'", "]", ":", "options", "[", "table_name", "]", "=", "{", "}", "# Regular table options", "for", "option", "in", "DEFAULT_OPTIONS", "[", "'table'", "]", ".", "keys", "(", ")", ":", "options", "[", "table_name", "]", "[", "option", "]", "=", "DEFAULT_OPTIONS", "[", "'table'", "]", "[", "option", "]", "if", "option", "not", "in", "conf_file_options", "[", "'tables'", "]", "[", "table_name", "]", ":", "continue", "if", "option", "==", "'sns_message_types'", ":", "try", ":", "raw_list", "=", "conf_file_options", "[", "'tables'", "]", "[", "table_name", "]", "[", "option", "]", "options", "[", "table_name", "]", "[", "option", "]", "=", "[", "i", ".", "strip", "(", ")", "for", "i", "in", "raw_list", ".", "split", "(", "','", ")", "]", "except", ":", "print", "(", "'Error parsing the \"sns-message-types\" '", "'option: {0}'", ".", "format", "(", "conf_file_options", "[", "'tables'", "]", "[", "table_name", "]", "[", "option", "]", ")", ")", "else", ":", "options", "[", "table_name", "]", "[", "option", "]", "=", "conf_file_options", "[", "'tables'", "]", "[", "table_name", "]", "[", "option", "]", "# GSI specific options", "if", "'gsis'", "in", "conf_file_options", "[", "'tables'", "]", "[", "table_name", "]", ":", "for", "gsi_name", "in", "conf_file_options", "[", "'tables'", "]", "[", "table_name", "]", "[", "'gsis'", "]", ":", "for", "option", "in", "DEFAULT_OPTIONS", "[", "'gsi'", "]", ".", "keys", "(", ")", ":", "opt", "=", "DEFAULT_OPTIONS", "[", "'gsi'", "]", "[", "option", "]", "if", "'gsis'", "not", "in", "options", "[", "table_name", "]", ":", "options", "[", "table_name", "]", "[", "'gsis'", "]", "=", "{", "}", "if", "gsi_name", "not", "in", "options", "[", "table_name", "]", "[", "'gsis'", "]", ":", "options", "[", "table_name", "]", "[", "'gsis'", "]", "[", "gsi_name", "]", "=", "{", "}", "if", "(", "option", "not", "in", "conf_file_options", "[", "'tables'", "]", "[", "table_name", "]", "[", "'gsis'", "]", "[", "gsi_name", "]", ")", ":", "options", "[", "table_name", "]", "[", "'gsis'", "]", "[", "gsi_name", "]", "[", "option", "]", "=", "opt", "continue", "if", "option", "==", "'sns_message_types'", ":", "try", ":", "raw_list", "=", "conf_file_options", "[", "'tables'", "]", "[", "table_name", "]", "[", "'gsis'", "]", "[", "gsi_name", "]", "[", "option", "]", "opt", "=", "[", "i", ".", "strip", "(", ")", "for", "i", "in", "raw_list", ".", "split", "(", "','", ")", "]", "except", ":", "print", "(", "'Error parsing the \"sns-message-types\" '", "'option: {0}'", ".", "format", "(", "conf_file_options", "[", "'tables'", "]", "[", "table_name", "]", "[", "'gsis'", "]", "[", "gsi_name", "]", "[", "option", "]", ")", ")", "else", ":", "opt", "=", "conf_file_options", "[", "'tables'", "]", "[", "table_name", "]", "[", "'gsis'", "]", "[", "gsi_name", "]", "[", "option", "]", "options", "[", "table_name", "]", "[", "'gsis'", "]", "[", "gsi_name", "]", "[", "option", "]", "=", "opt", "return", "options" ]
Get all table options from the config file :type conf_file_options: ordereddict :param conf_file_options: Dictionary with all config file options :returns: ordereddict -- E.g. {'table_name': {}}
[ "Get", "all", "table", "options", "from", "the", "config", "file" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/config/__init__.py#L225-L296
18,193
sebdah/dynamic-dynamodb
dynamic_dynamodb/config/__init__.py
__get_global_options
def __get_global_options(cmd_line_options, conf_file_options=None): """ Get all global options :type cmd_line_options: dict :param cmd_line_options: Dictionary with all command line options :type conf_file_options: dict :param conf_file_options: Dictionary with all config file options :returns: dict """ options = {} for option in DEFAULT_OPTIONS['global'].keys(): options[option] = DEFAULT_OPTIONS['global'][option] if conf_file_options and option in conf_file_options: options[option] = conf_file_options[option] if cmd_line_options and option in cmd_line_options: options[option] = cmd_line_options[option] return options
python
def __get_global_options(cmd_line_options, conf_file_options=None): """ Get all global options :type cmd_line_options: dict :param cmd_line_options: Dictionary with all command line options :type conf_file_options: dict :param conf_file_options: Dictionary with all config file options :returns: dict """ options = {} for option in DEFAULT_OPTIONS['global'].keys(): options[option] = DEFAULT_OPTIONS['global'][option] if conf_file_options and option in conf_file_options: options[option] = conf_file_options[option] if cmd_line_options and option in cmd_line_options: options[option] = cmd_line_options[option] return options
[ "def", "__get_global_options", "(", "cmd_line_options", ",", "conf_file_options", "=", "None", ")", ":", "options", "=", "{", "}", "for", "option", "in", "DEFAULT_OPTIONS", "[", "'global'", "]", ".", "keys", "(", ")", ":", "options", "[", "option", "]", "=", "DEFAULT_OPTIONS", "[", "'global'", "]", "[", "option", "]", "if", "conf_file_options", "and", "option", "in", "conf_file_options", ":", "options", "[", "option", "]", "=", "conf_file_options", "[", "option", "]", "if", "cmd_line_options", "and", "option", "in", "cmd_line_options", ":", "options", "[", "option", "]", "=", "cmd_line_options", "[", "option", "]", "return", "options" ]
Get all global options :type cmd_line_options: dict :param cmd_line_options: Dictionary with all command line options :type conf_file_options: dict :param conf_file_options: Dictionary with all config file options :returns: dict
[ "Get", "all", "global", "options" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/config/__init__.py#L299-L319
18,194
sebdah/dynamic-dynamodb
dynamic_dynamodb/config/__init__.py
__get_logging_options
def __get_logging_options(cmd_line_options, conf_file_options=None): """ Get all logging options :type cmd_line_options: dict :param cmd_line_options: Dictionary with all command line options :type conf_file_options: dict :param conf_file_options: Dictionary with all config file options :returns: dict """ options = {} for option in DEFAULT_OPTIONS['logging'].keys(): options[option] = DEFAULT_OPTIONS['logging'][option] if conf_file_options and option in conf_file_options: options[option] = conf_file_options[option] if cmd_line_options and option in cmd_line_options: options[option] = cmd_line_options[option] return options
python
def __get_logging_options(cmd_line_options, conf_file_options=None): """ Get all logging options :type cmd_line_options: dict :param cmd_line_options: Dictionary with all command line options :type conf_file_options: dict :param conf_file_options: Dictionary with all config file options :returns: dict """ options = {} for option in DEFAULT_OPTIONS['logging'].keys(): options[option] = DEFAULT_OPTIONS['logging'][option] if conf_file_options and option in conf_file_options: options[option] = conf_file_options[option] if cmd_line_options and option in cmd_line_options: options[option] = cmd_line_options[option] return options
[ "def", "__get_logging_options", "(", "cmd_line_options", ",", "conf_file_options", "=", "None", ")", ":", "options", "=", "{", "}", "for", "option", "in", "DEFAULT_OPTIONS", "[", "'logging'", "]", ".", "keys", "(", ")", ":", "options", "[", "option", "]", "=", "DEFAULT_OPTIONS", "[", "'logging'", "]", "[", "option", "]", "if", "conf_file_options", "and", "option", "in", "conf_file_options", ":", "options", "[", "option", "]", "=", "conf_file_options", "[", "option", "]", "if", "cmd_line_options", "and", "option", "in", "cmd_line_options", ":", "options", "[", "option", "]", "=", "cmd_line_options", "[", "option", "]", "return", "options" ]
Get all logging options :type cmd_line_options: dict :param cmd_line_options: Dictionary with all command line options :type conf_file_options: dict :param conf_file_options: Dictionary with all config file options :returns: dict
[ "Get", "all", "logging", "options" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/config/__init__.py#L322-L342
18,195
sebdah/dynamic-dynamodb
dynamic_dynamodb/config/__init__.py
__check_logging_rules
def __check_logging_rules(configuration): """ Check that the logging values are proper """ valid_log_levels = [ 'debug', 'info', 'warning', 'error' ] if configuration['logging']['log_level'].lower() not in valid_log_levels: print('Log level must be one of {0}'.format( ', '.join(valid_log_levels))) sys.exit(1)
python
def __check_logging_rules(configuration): """ Check that the logging values are proper """ valid_log_levels = [ 'debug', 'info', 'warning', 'error' ] if configuration['logging']['log_level'].lower() not in valid_log_levels: print('Log level must be one of {0}'.format( ', '.join(valid_log_levels))) sys.exit(1)
[ "def", "__check_logging_rules", "(", "configuration", ")", ":", "valid_log_levels", "=", "[", "'debug'", ",", "'info'", ",", "'warning'", ",", "'error'", "]", "if", "configuration", "[", "'logging'", "]", "[", "'log_level'", "]", ".", "lower", "(", ")", "not", "in", "valid_log_levels", ":", "print", "(", "'Log level must be one of {0}'", ".", "format", "(", "', '", ".", "join", "(", "valid_log_levels", ")", ")", ")", "sys", ".", "exit", "(", "1", ")" ]
Check that the logging values are proper
[ "Check", "that", "the", "logging", "values", "are", "proper" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/config/__init__.py#L505-L516
18,196
sebdah/dynamic-dynamodb
dynamic_dynamodb/calculators.py
is_consumed_over_proposed
def is_consumed_over_proposed( current_provisioning, proposed_provisioning, consumed_units_percent): """ Determines if the currently consumed capacity is over the proposed capacity for this table :type current_provisioning: int :param current_provisioning: The current provisioning :type proposed_provisioning: int :param proposed_provisioning: New provisioning :type consumed_units_percent: float :param consumed_units_percent: Percent of consumed units :returns: bool - if consumed is over max """ consumption_based_current_provisioning = \ int(math.ceil(current_provisioning*(consumed_units_percent/100))) return consumption_based_current_provisioning > proposed_provisioning
python
def is_consumed_over_proposed( current_provisioning, proposed_provisioning, consumed_units_percent): """ Determines if the currently consumed capacity is over the proposed capacity for this table :type current_provisioning: int :param current_provisioning: The current provisioning :type proposed_provisioning: int :param proposed_provisioning: New provisioning :type consumed_units_percent: float :param consumed_units_percent: Percent of consumed units :returns: bool - if consumed is over max """ consumption_based_current_provisioning = \ int(math.ceil(current_provisioning*(consumed_units_percent/100))) return consumption_based_current_provisioning > proposed_provisioning
[ "def", "is_consumed_over_proposed", "(", "current_provisioning", ",", "proposed_provisioning", ",", "consumed_units_percent", ")", ":", "consumption_based_current_provisioning", "=", "int", "(", "math", ".", "ceil", "(", "current_provisioning", "*", "(", "consumed_units_percent", "/", "100", ")", ")", ")", "return", "consumption_based_current_provisioning", ">", "proposed_provisioning" ]
Determines if the currently consumed capacity is over the proposed capacity for this table :type current_provisioning: int :param current_provisioning: The current provisioning :type proposed_provisioning: int :param proposed_provisioning: New provisioning :type consumed_units_percent: float :param consumed_units_percent: Percent of consumed units :returns: bool - if consumed is over max
[ "Determines", "if", "the", "currently", "consumed", "capacity", "is", "over", "the", "proposed", "capacity", "for", "this", "table" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/calculators.py#L342-L358
18,197
sebdah/dynamic-dynamodb
dynamic_dynamodb/calculators.py
__get_min_reads
def __get_min_reads(current_provisioning, min_provisioned_reads, log_tag): """ Get the minimum number of reads to current_provisioning :type current_provisioning: int :param current_provisioning: Current provisioned reads :type min_provisioned_reads: int :param min_provisioned_reads: Configured min provisioned reads :type log_tag: str :param log_tag: Prefix for the log :returns: int -- Minimum number of reads """ # Fallback value to ensure that we always have at least 1 read reads = 1 if min_provisioned_reads: reads = int(min_provisioned_reads) if reads > int(current_provisioning * 2): reads = int(current_provisioning * 2) logger.debug( '{0} - ' 'Cannot reach min-provisioned-reads as max scale up ' 'is 100% of current provisioning'.format(log_tag)) logger.debug( '{0} - Setting min provisioned reads to {1}'.format( log_tag, min_provisioned_reads)) return reads
python
def __get_min_reads(current_provisioning, min_provisioned_reads, log_tag): """ Get the minimum number of reads to current_provisioning :type current_provisioning: int :param current_provisioning: Current provisioned reads :type min_provisioned_reads: int :param min_provisioned_reads: Configured min provisioned reads :type log_tag: str :param log_tag: Prefix for the log :returns: int -- Minimum number of reads """ # Fallback value to ensure that we always have at least 1 read reads = 1 if min_provisioned_reads: reads = int(min_provisioned_reads) if reads > int(current_provisioning * 2): reads = int(current_provisioning * 2) logger.debug( '{0} - ' 'Cannot reach min-provisioned-reads as max scale up ' 'is 100% of current provisioning'.format(log_tag)) logger.debug( '{0} - Setting min provisioned reads to {1}'.format( log_tag, min_provisioned_reads)) return reads
[ "def", "__get_min_reads", "(", "current_provisioning", ",", "min_provisioned_reads", ",", "log_tag", ")", ":", "# Fallback value to ensure that we always have at least 1 read", "reads", "=", "1", "if", "min_provisioned_reads", ":", "reads", "=", "int", "(", "min_provisioned_reads", ")", "if", "reads", ">", "int", "(", "current_provisioning", "*", "2", ")", ":", "reads", "=", "int", "(", "current_provisioning", "*", "2", ")", "logger", ".", "debug", "(", "'{0} - '", "'Cannot reach min-provisioned-reads as max scale up '", "'is 100% of current provisioning'", ".", "format", "(", "log_tag", ")", ")", "logger", ".", "debug", "(", "'{0} - Setting min provisioned reads to {1}'", ".", "format", "(", "log_tag", ",", "min_provisioned_reads", ")", ")", "return", "reads" ]
Get the minimum number of reads to current_provisioning :type current_provisioning: int :param current_provisioning: Current provisioned reads :type min_provisioned_reads: int :param min_provisioned_reads: Configured min provisioned reads :type log_tag: str :param log_tag: Prefix for the log :returns: int -- Minimum number of reads
[ "Get", "the", "minimum", "number", "of", "reads", "to", "current_provisioning" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/calculators.py#L361-L389
18,198
sebdah/dynamic-dynamodb
dynamic_dynamodb/calculators.py
__get_min_writes
def __get_min_writes(current_provisioning, min_provisioned_writes, log_tag): """ Get the minimum number of writes to current_provisioning :type current_provisioning: int :param current_provisioning: Current provisioned writes :type min_provisioned_writes: int :param min_provisioned_writes: Configured min provisioned writes :type log_tag: str :param log_tag: Prefix for the log :returns: int -- Minimum number of writes """ # Fallback value to ensure that we always have at least 1 read writes = 1 if min_provisioned_writes: writes = int(min_provisioned_writes) if writes > int(current_provisioning * 2): writes = int(current_provisioning * 2) logger.debug( '{0} - ' 'Cannot reach min-provisioned-writes as max scale up ' 'is 100% of current provisioning'.format(log_tag)) logger.debug( '{0} - Setting min provisioned writes to {1}'.format( log_tag, min_provisioned_writes)) return writes
python
def __get_min_writes(current_provisioning, min_provisioned_writes, log_tag): """ Get the minimum number of writes to current_provisioning :type current_provisioning: int :param current_provisioning: Current provisioned writes :type min_provisioned_writes: int :param min_provisioned_writes: Configured min provisioned writes :type log_tag: str :param log_tag: Prefix for the log :returns: int -- Minimum number of writes """ # Fallback value to ensure that we always have at least 1 read writes = 1 if min_provisioned_writes: writes = int(min_provisioned_writes) if writes > int(current_provisioning * 2): writes = int(current_provisioning * 2) logger.debug( '{0} - ' 'Cannot reach min-provisioned-writes as max scale up ' 'is 100% of current provisioning'.format(log_tag)) logger.debug( '{0} - Setting min provisioned writes to {1}'.format( log_tag, min_provisioned_writes)) return writes
[ "def", "__get_min_writes", "(", "current_provisioning", ",", "min_provisioned_writes", ",", "log_tag", ")", ":", "# Fallback value to ensure that we always have at least 1 read", "writes", "=", "1", "if", "min_provisioned_writes", ":", "writes", "=", "int", "(", "min_provisioned_writes", ")", "if", "writes", ">", "int", "(", "current_provisioning", "*", "2", ")", ":", "writes", "=", "int", "(", "current_provisioning", "*", "2", ")", "logger", ".", "debug", "(", "'{0} - '", "'Cannot reach min-provisioned-writes as max scale up '", "'is 100% of current provisioning'", ".", "format", "(", "log_tag", ")", ")", "logger", ".", "debug", "(", "'{0} - Setting min provisioned writes to {1}'", ".", "format", "(", "log_tag", ",", "min_provisioned_writes", ")", ")", "return", "writes" ]
Get the minimum number of writes to current_provisioning :type current_provisioning: int :param current_provisioning: Current provisioned writes :type min_provisioned_writes: int :param min_provisioned_writes: Configured min provisioned writes :type log_tag: str :param log_tag: Prefix for the log :returns: int -- Minimum number of writes
[ "Get", "the", "minimum", "number", "of", "writes", "to", "current_provisioning" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/calculators.py#L392-L420
18,199
sebdah/dynamic-dynamodb
dynamic_dynamodb/daemon.py
Daemon.restart
def restart(self, *args, **kwargs): """ Restart the daemon """ self.stop() try: self.start(*args, **kwargs) except IOError: raise
python
def restart(self, *args, **kwargs): """ Restart the daemon """ self.stop() try: self.start(*args, **kwargs) except IOError: raise
[ "def", "restart", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "stop", "(", ")", "try", ":", "self", ".", "start", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "IOError", ":", "raise" ]
Restart the daemon
[ "Restart", "the", "daemon" ]
bfd0ca806b1c3301e724696de90ef0f973410493
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/daemon.py#L132-L138