id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
21,900
rndusr/torf
torf/_torrent.py
Torrent.name
def name(self): """ Name of the torrent Default to last item in :attr:`path` or ``None`` if :attr:`path` is ``None``. Setting this property sets or removes ``name`` in :attr:`metainfo`\ ``['info']``. """ if 'name' not in self.metainfo['info'] and self.path is not None: self.metainfo['info']['name'] = os.path.basename(self.path) return self.metainfo['info'].get('name', None)
python
def name(self): if 'name' not in self.metainfo['info'] and self.path is not None: self.metainfo['info']['name'] = os.path.basename(self.path) return self.metainfo['info'].get('name', None)
[ "def", "name", "(", "self", ")", ":", "if", "'name'", "not", "in", "self", ".", "metainfo", "[", "'info'", "]", "and", "self", ".", "path", "is", "not", "None", ":", "self", ".", "metainfo", "[", "'info'", "]", "[", "'name'", "]", "=", "os", ".",...
Name of the torrent Default to last item in :attr:`path` or ``None`` if :attr:`path` is ``None``. Setting this property sets or removes ``name`` in :attr:`metainfo`\ ``['info']``.
[ "Name", "of", "the", "torrent" ]
df0363232daacd3f8c91aafddaa0623b8c28cbd2
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L323-L335
21,901
rndusr/torf
torf/_torrent.py
Torrent.trackers
def trackers(self): """ List of tiers of announce URLs or ``None`` for no trackers A tier is either a single announce URL (:class:`str`) or an :class:`~collections.abc.Iterable` (e.g. :class:`list`) of announce URLs. Setting this property sets or removes ``announce`` and ``announce-list`` in :attr:`metainfo`. ``announce`` is set to the first tracker of the first tier. :raises URLError: if any of the announce URLs is invalid """ announce_list = self.metainfo.get('announce-list', None) if not announce_list: announce = self.metainfo.get('announce', None) if announce: return [[announce]] else: return announce_list
python
def trackers(self): announce_list = self.metainfo.get('announce-list', None) if not announce_list: announce = self.metainfo.get('announce', None) if announce: return [[announce]] else: return announce_list
[ "def", "trackers", "(", "self", ")", ":", "announce_list", "=", "self", ".", "metainfo", ".", "get", "(", "'announce-list'", ",", "None", ")", "if", "not", "announce_list", ":", "announce", "=", "self", ".", "metainfo", ".", "get", "(", "'announce'", ","...
List of tiers of announce URLs or ``None`` for no trackers A tier is either a single announce URL (:class:`str`) or an :class:`~collections.abc.Iterable` (e.g. :class:`list`) of announce URLs. Setting this property sets or removes ``announce`` and ``announce-list`` in :attr:`metainfo`. ``announce`` is set to the first tracker of the first tier. :raises URLError: if any of the announce URLs is invalid
[ "List", "of", "tiers", "of", "announce", "URLs", "or", "None", "for", "no", "trackers" ]
df0363232daacd3f8c91aafddaa0623b8c28cbd2
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L345-L365
21,902
rndusr/torf
torf/_torrent.py
Torrent.infohash
def infohash(self): """SHA1 info hash""" self.validate() info = self.convert()[b'info'] return sha1(bencode(info)).hexdigest()
python
def infohash(self): self.validate() info = self.convert()[b'info'] return sha1(bencode(info)).hexdigest()
[ "def", "infohash", "(", "self", ")", ":", "self", ".", "validate", "(", ")", "info", "=", "self", ".", "convert", "(", ")", "[", "b'info'", "]", "return", "sha1", "(", "bencode", "(", "info", ")", ")", ".", "hexdigest", "(", ")" ]
SHA1 info hash
[ "SHA1", "info", "hash" ]
df0363232daacd3f8c91aafddaa0623b8c28cbd2
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L548-L552
21,903
rndusr/torf
torf/_torrent.py
Torrent.infohash_base32
def infohash_base32(self): """Base32 encoded SHA1 info hash""" self.validate() info = self.convert()[b'info'] return b32encode(sha1(bencode(info)).digest())
python
def infohash_base32(self): self.validate() info = self.convert()[b'info'] return b32encode(sha1(bencode(info)).digest())
[ "def", "infohash_base32", "(", "self", ")", ":", "self", ".", "validate", "(", ")", "info", "=", "self", ".", "convert", "(", ")", "[", "b'info'", "]", "return", "b32encode", "(", "sha1", "(", "bencode", "(", "info", ")", ")", ".", "digest", "(", "...
Base32 encoded SHA1 info hash
[ "Base32", "encoded", "SHA1", "info", "hash" ]
df0363232daacd3f8c91aafddaa0623b8c28cbd2
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L555-L559
21,904
rndusr/torf
torf/_torrent.py
Torrent.generate
def generate(self, callback=None, interval=0): """ Hash pieces and report progress to `callback` This method sets ``pieces`` in :attr:`metainfo`\ ``['info']`` when all pieces are hashed successfully. :param callable callback: Callable with signature ``(torrent, filepath, pieces_done, pieces_total)``; if `callback` returns anything else than None, hashing is canceled :param float interval: Minimum number of seconds between calls to `callback` (if 0, `callback` is called once per piece) :raises PathEmptyError: if :attr:`path` contains only empty files/directories :raises PathNotFoundError: if :attr:`path` does not exist :raises ReadError: if :attr:`path` or any file beneath it is not readable :return: ``True`` if all pieces were successfully hashed, ``False`` otherwise """ if self.path is None: raise RuntimeError('generate() called with no path specified') elif self.size <= 0: raise error.PathEmptyError(self.path) elif not os.path.exists(self.path): raise error.PathNotFoundError(self.path) if callback is not None: cancel = lambda *status: callback(*status) is not None else: cancel = lambda *status: False if os.path.isfile(self.path): pieces = self._set_pieces_singlefile() elif os.path.isdir(self.path): pieces = self._set_pieces_multifile() # Iterate over hashed pieces and send status information last_cb_call = 0 for filepath,pieces_done,pieces_total in pieces: now = time.time() if now - last_cb_call >= interval or \ pieces_done >= pieces_total: last_cb_call = now if cancel(self, filepath, pieces_done, pieces_total): return False return True
python
def generate(self, callback=None, interval=0): if self.path is None: raise RuntimeError('generate() called with no path specified') elif self.size <= 0: raise error.PathEmptyError(self.path) elif not os.path.exists(self.path): raise error.PathNotFoundError(self.path) if callback is not None: cancel = lambda *status: callback(*status) is not None else: cancel = lambda *status: False if os.path.isfile(self.path): pieces = self._set_pieces_singlefile() elif os.path.isdir(self.path): pieces = self._set_pieces_multifile() # Iterate over hashed pieces and send status information last_cb_call = 0 for filepath,pieces_done,pieces_total in pieces: now = time.time() if now - last_cb_call >= interval or \ pieces_done >= pieces_total: last_cb_call = now if cancel(self, filepath, pieces_done, pieces_total): return False return True
[ "def", "generate", "(", "self", ",", "callback", "=", "None", ",", "interval", "=", "0", ")", ":", "if", "self", ".", "path", "is", "None", ":", "raise", "RuntimeError", "(", "'generate() called with no path specified'", ")", "elif", "self", ".", "size", "...
Hash pieces and report progress to `callback` This method sets ``pieces`` in :attr:`metainfo`\ ``['info']`` when all pieces are hashed successfully. :param callable callback: Callable with signature ``(torrent, filepath, pieces_done, pieces_total)``; if `callback` returns anything else than None, hashing is canceled :param float interval: Minimum number of seconds between calls to `callback` (if 0, `callback` is called once per piece) :raises PathEmptyError: if :attr:`path` contains only empty files/directories :raises PathNotFoundError: if :attr:`path` does not exist :raises ReadError: if :attr:`path` or any file beneath it is not readable :return: ``True`` if all pieces were successfully hashed, ``False`` otherwise
[ "Hash", "pieces", "and", "report", "progress", "to", "callback" ]
df0363232daacd3f8c91aafddaa0623b8c28cbd2
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L593-L641
21,905
rndusr/torf
torf/_torrent.py
Torrent.magnet
def magnet(self, name=True, size=True, trackers=True, tracker=False, validate=True): """ BTIH Magnet URI :param bool name: Whether to include the name :param bool size: Whether to include the size :param bool trackers: Whether to include all trackers :param bool tracker: Whether to include only the first tracker of the first tier (overrides `trackers`) :param bool validate: Whether to run :meth:`validate` first """ if validate: self.validate() parts = [f'xt=urn:btih:{self.infohash}'] if name: parts.append(f'dn={utils.urlquote(self.name)}') if size: parts.append(f'xl={self.size}') if self.trackers is not None: if tracker: parts.append(f'tr={utils.urlquote(self.trackers[0][0])}') elif trackers: for tier in self.trackers: for url in tier: parts.append(f'tr={utils.urlquote(url)}') return 'magnet:?' + '&'.join(parts)
python
def magnet(self, name=True, size=True, trackers=True, tracker=False, validate=True): if validate: self.validate() parts = [f'xt=urn:btih:{self.infohash}'] if name: parts.append(f'dn={utils.urlquote(self.name)}') if size: parts.append(f'xl={self.size}') if self.trackers is not None: if tracker: parts.append(f'tr={utils.urlquote(self.trackers[0][0])}') elif trackers: for tier in self.trackers: for url in tier: parts.append(f'tr={utils.urlquote(url)}') return 'magnet:?' + '&'.join(parts)
[ "def", "magnet", "(", "self", ",", "name", "=", "True", ",", "size", "=", "True", ",", "trackers", "=", "True", ",", "tracker", "=", "False", ",", "validate", "=", "True", ")", ":", "if", "validate", ":", "self", ".", "validate", "(", ")", "parts",...
BTIH Magnet URI :param bool name: Whether to include the name :param bool size: Whether to include the size :param bool trackers: Whether to include all trackers :param bool tracker: Whether to include only the first tracker of the first tier (overrides `trackers`) :param bool validate: Whether to run :meth:`validate` first
[ "BTIH", "Magnet", "URI" ]
df0363232daacd3f8c91aafddaa0623b8c28cbd2
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L867-L895
21,906
rndusr/torf
torf/_torrent.py
Torrent.read_stream
def read_stream(cls, stream, validate=True): """ Read torrent metainfo from file-like object :param stream: Readable file-like object (e.g. :class:`io.BytesIO`) :param bool validate: Whether to run :meth:`validate` on the new Torrent object :raises ReadError: if reading from `stream` fails :raises ParseError: if `stream` does not produce a valid bencoded byte string :raises MetainfoError: if `validate` is `True` and the read metainfo is invalid :return: New Torrent object """ try: content = stream.read(cls.MAX_TORRENT_FILE_SIZE) except OSError as e: raise error.ReadError(e.errno) else: try: metainfo_enc = bdecode(content) except BTFailure as e: raise error.ParseError() if validate: if b'info' not in metainfo_enc: raise error.MetainfoError("Missing 'info'") elif not isinstance(metainfo_enc[b'info'], abc.Mapping): raise error.MetainfoError("'info' is not a dictionary") elif b'pieces' not in metainfo_enc[b'info']: raise error.MetainfoError("Missing 'pieces' in ['info']") # Extract 'pieces' from metainfo because it's the only byte string # that isn't supposed to be decoded to unicode. if b'info' in metainfo_enc and b'pieces' in metainfo_enc[b'info']: pieces = metainfo_enc[b'info'].pop(b'pieces') metainfo = utils.decode_dict(metainfo_enc) metainfo['info']['pieces'] = pieces else: metainfo = utils.decode_dict(metainfo_enc) torrent = cls() torrent._metainfo = metainfo # Convert some values from official types to something nicer # (e.g. int -> datetime) for attr in ('creation_date', 'private'): setattr(torrent, attr, getattr(torrent, attr)) # Auto-set 'include_md5' info = torrent.metainfo['info'] torrent.include_md5 = ('length' in info and 'md5sum' in info) or \ ('files' in info and all('md5sum' in fileinfo for fileinfo in info['files'])) if validate: torrent.validate() return torrent
python
def read_stream(cls, stream, validate=True): try: content = stream.read(cls.MAX_TORRENT_FILE_SIZE) except OSError as e: raise error.ReadError(e.errno) else: try: metainfo_enc = bdecode(content) except BTFailure as e: raise error.ParseError() if validate: if b'info' not in metainfo_enc: raise error.MetainfoError("Missing 'info'") elif not isinstance(metainfo_enc[b'info'], abc.Mapping): raise error.MetainfoError("'info' is not a dictionary") elif b'pieces' not in metainfo_enc[b'info']: raise error.MetainfoError("Missing 'pieces' in ['info']") # Extract 'pieces' from metainfo because it's the only byte string # that isn't supposed to be decoded to unicode. if b'info' in metainfo_enc and b'pieces' in metainfo_enc[b'info']: pieces = metainfo_enc[b'info'].pop(b'pieces') metainfo = utils.decode_dict(metainfo_enc) metainfo['info']['pieces'] = pieces else: metainfo = utils.decode_dict(metainfo_enc) torrent = cls() torrent._metainfo = metainfo # Convert some values from official types to something nicer # (e.g. int -> datetime) for attr in ('creation_date', 'private'): setattr(torrent, attr, getattr(torrent, attr)) # Auto-set 'include_md5' info = torrent.metainfo['info'] torrent.include_md5 = ('length' in info and 'md5sum' in info) or \ ('files' in info and all('md5sum' in fileinfo for fileinfo in info['files'])) if validate: torrent.validate() return torrent
[ "def", "read_stream", "(", "cls", ",", "stream", ",", "validate", "=", "True", ")", ":", "try", ":", "content", "=", "stream", ".", "read", "(", "cls", ".", "MAX_TORRENT_FILE_SIZE", ")", "except", "OSError", "as", "e", ":", "raise", "error", ".", "Read...
Read torrent metainfo from file-like object :param stream: Readable file-like object (e.g. :class:`io.BytesIO`) :param bool validate: Whether to run :meth:`validate` on the new Torrent object :raises ReadError: if reading from `stream` fails :raises ParseError: if `stream` does not produce a valid bencoded byte string :raises MetainfoError: if `validate` is `True` and the read metainfo is invalid :return: New Torrent object
[ "Read", "torrent", "metainfo", "from", "file", "-", "like", "object" ]
df0363232daacd3f8c91aafddaa0623b8c28cbd2
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L903-L963
21,907
rndusr/torf
torf/_torrent.py
Torrent.read
def read(cls, filepath, validate=True): """ Read torrent metainfo from file :param filepath: Path of the torrent file :param bool validate: Whether to run :meth:`validate` on the new Torrent object :raises ReadError: if reading from `filepath` fails :raises ParseError: if `filepath` does not contain a valid bencoded byte string :raises MetainfoError: if `validate` is `True` and the read metainfo is invalid :return: New Torrent object """ try: with open(filepath, 'rb') as fh: return cls.read_stream(fh) except (OSError, error.ReadError) as e: raise error.ReadError(e.errno, filepath) except error.ParseError: raise error.ParseError(filepath)
python
def read(cls, filepath, validate=True): try: with open(filepath, 'rb') as fh: return cls.read_stream(fh) except (OSError, error.ReadError) as e: raise error.ReadError(e.errno, filepath) except error.ParseError: raise error.ParseError(filepath)
[ "def", "read", "(", "cls", ",", "filepath", ",", "validate", "=", "True", ")", ":", "try", ":", "with", "open", "(", "filepath", ",", "'rb'", ")", "as", "fh", ":", "return", "cls", ".", "read_stream", "(", "fh", ")", "except", "(", "OSError", ",", ...
Read torrent metainfo from file :param filepath: Path of the torrent file :param bool validate: Whether to run :meth:`validate` on the new Torrent object :raises ReadError: if reading from `filepath` fails :raises ParseError: if `filepath` does not contain a valid bencoded byte string :raises MetainfoError: if `validate` is `True` and the read metainfo is invalid :return: New Torrent object
[ "Read", "torrent", "metainfo", "from", "file" ]
df0363232daacd3f8c91aafddaa0623b8c28cbd2
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L966-L988
21,908
rndusr/torf
torf/_torrent.py
Torrent.copy
def copy(self): """ Return a new object with the same metainfo Internally, this simply copies the internal metainfo dictionary with :func:`copy.deepcopy` and gives it to the new instance. """ from copy import deepcopy cp = type(self)() cp._metainfo = deepcopy(self._metainfo) return cp
python
def copy(self): from copy import deepcopy cp = type(self)() cp._metainfo = deepcopy(self._metainfo) return cp
[ "def", "copy", "(", "self", ")", ":", "from", "copy", "import", "deepcopy", "cp", "=", "type", "(", "self", ")", "(", ")", "cp", ".", "_metainfo", "=", "deepcopy", "(", "self", ".", "_metainfo", ")", "return", "cp" ]
Return a new object with the same metainfo Internally, this simply copies the internal metainfo dictionary with :func:`copy.deepcopy` and gives it to the new instance.
[ "Return", "a", "new", "object", "with", "the", "same", "metainfo" ]
df0363232daacd3f8c91aafddaa0623b8c28cbd2
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L990-L1000
21,909
rndusr/torf
torf/_utils.py
validated_url
def validated_url(url): """Return url if valid, raise URLError otherwise""" try: u = urlparse(url) u.port # Trigger 'invalid port' exception except Exception: raise error.URLError(url) else: if not u.scheme or not u.netloc: raise error.URLError(url) return url
python
def validated_url(url): try: u = urlparse(url) u.port # Trigger 'invalid port' exception except Exception: raise error.URLError(url) else: if not u.scheme or not u.netloc: raise error.URLError(url) return url
[ "def", "validated_url", "(", "url", ")", ":", "try", ":", "u", "=", "urlparse", "(", "url", ")", "u", ".", "port", "# Trigger 'invalid port' exception", "except", "Exception", ":", "raise", "error", ".", "URLError", "(", "url", ")", "else", ":", "if", "n...
Return url if valid, raise URLError otherwise
[ "Return", "url", "if", "valid", "raise", "URLError", "otherwise" ]
df0363232daacd3f8c91aafddaa0623b8c28cbd2
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_utils.py#L38-L48
21,910
rndusr/torf
torf/_utils.py
read_chunks
def read_chunks(filepath, chunk_size): """Generator that yields chunks from file""" try: with open(filepath, 'rb') as f: while True: chunk = f.read(chunk_size) if chunk: yield chunk else: break # EOF except OSError as e: raise error.ReadError(e.errno, filepath)
python
def read_chunks(filepath, chunk_size): try: with open(filepath, 'rb') as f: while True: chunk = f.read(chunk_size) if chunk: yield chunk else: break # EOF except OSError as e: raise error.ReadError(e.errno, filepath)
[ "def", "read_chunks", "(", "filepath", ",", "chunk_size", ")", ":", "try", ":", "with", "open", "(", "filepath", ",", "'rb'", ")", "as", "f", ":", "while", "True", ":", "chunk", "=", "f", ".", "read", "(", "chunk_size", ")", "if", "chunk", ":", "yi...
Generator that yields chunks from file
[ "Generator", "that", "yields", "chunks", "from", "file" ]
df0363232daacd3f8c91aafddaa0623b8c28cbd2
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_utils.py#L51-L62
21,911
rndusr/torf
torf/_utils.py
calc_piece_size
def calc_piece_size(total_size, max_pieces, min_piece_size, max_piece_size): """Calculate piece size""" ps = 1 << max(0, math.ceil(math.log(total_size / max_pieces, 2))) if ps < min_piece_size: ps = min_piece_size if ps > max_piece_size: ps = max_piece_size return ps
python
def calc_piece_size(total_size, max_pieces, min_piece_size, max_piece_size): ps = 1 << max(0, math.ceil(math.log(total_size / max_pieces, 2))) if ps < min_piece_size: ps = min_piece_size if ps > max_piece_size: ps = max_piece_size return ps
[ "def", "calc_piece_size", "(", "total_size", ",", "max_pieces", ",", "min_piece_size", ",", "max_piece_size", ")", ":", "ps", "=", "1", "<<", "max", "(", "0", ",", "math", ".", "ceil", "(", "math", ".", "log", "(", "total_size", "/", "max_pieces", ",", ...
Calculate piece size
[ "Calculate", "piece", "size" ]
df0363232daacd3f8c91aafddaa0623b8c28cbd2
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_utils.py#L65-L72
21,912
rndusr/torf
torf/_utils.py
is_power_of_2
def is_power_of_2(num): """Return whether `num` is a power of two""" log = math.log2(num) return int(log) == float(log)
python
def is_power_of_2(num): log = math.log2(num) return int(log) == float(log)
[ "def", "is_power_of_2", "(", "num", ")", ":", "log", "=", "math", ".", "log2", "(", "num", ")", "return", "int", "(", "log", ")", "==", "float", "(", "log", ")" ]
Return whether `num` is a power of two
[ "Return", "whether", "num", "is", "a", "power", "of", "two" ]
df0363232daacd3f8c91aafddaa0623b8c28cbd2
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_utils.py#L75-L78
21,913
rndusr/torf
torf/_utils.py
is_hidden
def is_hidden(path): """Whether file or directory is hidden""" for name in path.split(os.sep): if name != '.' and name != '..' and name and name[0] == '.': return True return False
python
def is_hidden(path): for name in path.split(os.sep): if name != '.' and name != '..' and name and name[0] == '.': return True return False
[ "def", "is_hidden", "(", "path", ")", ":", "for", "name", "in", "path", ".", "split", "(", "os", ".", "sep", ")", ":", "if", "name", "!=", "'.'", "and", "name", "!=", "'..'", "and", "name", "and", "name", "[", "0", "]", "==", "'.'", ":", "retur...
Whether file or directory is hidden
[ "Whether", "file", "or", "directory", "is", "hidden" ]
df0363232daacd3f8c91aafddaa0623b8c28cbd2
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_utils.py#L81-L86
21,914
rndusr/torf
torf/_utils.py
filepaths
def filepaths(path, exclude=(), hidden=True, empty=True): """ Return list of absolute, sorted file paths path: Path to file or directory exclude: List of file name patterns to exclude hidden: Whether to include hidden files empty: Whether to include empty files Raise PathNotFoundError if path doesn't exist. """ if not os.path.exists(path): raise error.PathNotFoundError(path) elif not os.access(path, os.R_OK, effective_ids=os.access in os.supports_effective_ids): raise error.ReadError(errno.EACCES, path) if os.path.isfile(path): return [path] else: filepaths = [] for dirpath, dirnames, filenames in os.walk(path): # Ignore hidden directory if not hidden and is_hidden(dirpath): continue for filename in filenames: # Ignore hidden file if not hidden and is_hidden(filename): continue filepath = os.path.join(dirpath, filename) # Ignore excluded file if any(is_match(filepath, pattern) for pattern in exclude): continue else: # Ignore empty file if empty or os.path.getsize(os.path.realpath(filepath)) > 0: filepaths.append(filepath) return sorted(filepaths, key=lambda fp: fp.casefold())
python
def filepaths(path, exclude=(), hidden=True, empty=True): if not os.path.exists(path): raise error.PathNotFoundError(path) elif not os.access(path, os.R_OK, effective_ids=os.access in os.supports_effective_ids): raise error.ReadError(errno.EACCES, path) if os.path.isfile(path): return [path] else: filepaths = [] for dirpath, dirnames, filenames in os.walk(path): # Ignore hidden directory if not hidden and is_hidden(dirpath): continue for filename in filenames: # Ignore hidden file if not hidden and is_hidden(filename): continue filepath = os.path.join(dirpath, filename) # Ignore excluded file if any(is_match(filepath, pattern) for pattern in exclude): continue else: # Ignore empty file if empty or os.path.getsize(os.path.realpath(filepath)) > 0: filepaths.append(filepath) return sorted(filepaths, key=lambda fp: fp.casefold())
[ "def", "filepaths", "(", "path", ",", "exclude", "=", "(", ")", ",", "hidden", "=", "True", ",", "empty", "=", "True", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "error", ".", "PathNotFoundError", "(", ...
Return list of absolute, sorted file paths path: Path to file or directory exclude: List of file name patterns to exclude hidden: Whether to include hidden files empty: Whether to include empty files Raise PathNotFoundError if path doesn't exist.
[ "Return", "list", "of", "absolute", "sorted", "file", "paths" ]
df0363232daacd3f8c91aafddaa0623b8c28cbd2
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_utils.py#L96-L136
21,915
rndusr/torf
torf/_utils.py
assert_type
def assert_type(lst_or_dct, keys, exp_types, must_exist=True, check=None): """ Raise MetainfoError is not of a particular type lst_or_dct: list or dict instance keys: Sequence of keys so that `lst_or_dct[key[0]][key[1]]...` resolves to a value exp_types: Sequence of types that the value specified by `keys` must be an instance of must_exist: Whether to raise MetainfoError if `keys` does not resolve to a value check: Callable that gets the value specified by `keys` and returns True if it OK, False otherwise """ keys = list(keys) keychain = [] while len(keys[:-1]) > 0: key = keys.pop(0) try: lst_or_dct = lst_or_dct[key] except (KeyError, IndexError): break keychain.append(key) keychain_str = ''.join(f'[{key!r}]' for key in keychain) key = keys.pop(0) if not key_exists_in_list_or_dict(key, lst_or_dct): if not must_exist: return raise error.MetainfoError(f"Missing {key!r} in {keychain_str}") elif not isinstance(lst_or_dct[key], exp_types): exp_types_str = ' or '.join(t.__name__ for t in exp_types) type_str = type(lst_or_dct[key]).__name__ raise error.MetainfoError(f"{keychain_str}[{key!r}] must be {exp_types_str}, " f"not {type_str}: {lst_or_dct[key]!r}") elif check is not None and not check(lst_or_dct[key]): raise error.MetainfoError(f"{keychain_str}[{key!r}] is invalid: {lst_or_dct[key]!r}")
python
def assert_type(lst_or_dct, keys, exp_types, must_exist=True, check=None): keys = list(keys) keychain = [] while len(keys[:-1]) > 0: key = keys.pop(0) try: lst_or_dct = lst_or_dct[key] except (KeyError, IndexError): break keychain.append(key) keychain_str = ''.join(f'[{key!r}]' for key in keychain) key = keys.pop(0) if not key_exists_in_list_or_dict(key, lst_or_dct): if not must_exist: return raise error.MetainfoError(f"Missing {key!r} in {keychain_str}") elif not isinstance(lst_or_dct[key], exp_types): exp_types_str = ' or '.join(t.__name__ for t in exp_types) type_str = type(lst_or_dct[key]).__name__ raise error.MetainfoError(f"{keychain_str}[{key!r}] must be {exp_types_str}, " f"not {type_str}: {lst_or_dct[key]!r}") elif check is not None and not check(lst_or_dct[key]): raise error.MetainfoError(f"{keychain_str}[{key!r}] is invalid: {lst_or_dct[key]!r}")
[ "def", "assert_type", "(", "lst_or_dct", ",", "keys", ",", "exp_types", ",", "must_exist", "=", "True", ",", "check", "=", "None", ")", ":", "keys", "=", "list", "(", "keys", ")", "keychain", "=", "[", "]", "while", "len", "(", "keys", "[", ":", "-...
Raise MetainfoError is not of a particular type lst_or_dct: list or dict instance keys: Sequence of keys so that `lst_or_dct[key[0]][key[1]]...` resolves to a value exp_types: Sequence of types that the value specified by `keys` must be an instance of must_exist: Whether to raise MetainfoError if `keys` does not resolve to a value check: Callable that gets the value specified by `keys` and returns True if it OK, False otherwise
[ "Raise", "MetainfoError", "is", "not", "of", "a", "particular", "type" ]
df0363232daacd3f8c91aafddaa0623b8c28cbd2
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_utils.py#L149-L188
21,916
reincubate/ricloud
ricloud/utils.py
error_message_and_exit
def error_message_and_exit(message, error_result): """Prints error messages in blue, the failed task result and quits.""" if message: error_message(message) puts(json.dumps(error_result, indent=2)) sys.exit(1)
python
def error_message_and_exit(message, error_result): if message: error_message(message) puts(json.dumps(error_result, indent=2)) sys.exit(1)
[ "def", "error_message_and_exit", "(", "message", ",", "error_result", ")", ":", "if", "message", ":", "error_message", "(", "message", ")", "puts", "(", "json", ".", "dumps", "(", "error_result", ",", "indent", "=", "2", ")", ")", "sys", ".", "exit", "("...
Prints error messages in blue, the failed task result and quits.
[ "Prints", "error", "messages", "in", "blue", "the", "failed", "task", "result", "and", "quits", "." ]
e46bce4529fbdca34a4190c18c7219e937e2b697
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/utils.py#L82-L87
21,917
reincubate/ricloud
ricloud/utils.py
print_prompt_values
def print_prompt_values(values, message=None, sub_attr=None): """Prints prompt title and choices with a bit of formatting.""" if message: prompt_message(message) for index, entry in enumerate(values): if sub_attr: line = '{:2d}: {}'.format(index, getattr(utf8(entry), sub_attr)) else: line = '{:2d}: {}'.format(index, utf8(entry)) with indent(3): print_message(line)
python
def print_prompt_values(values, message=None, sub_attr=None): if message: prompt_message(message) for index, entry in enumerate(values): if sub_attr: line = '{:2d}: {}'.format(index, getattr(utf8(entry), sub_attr)) else: line = '{:2d}: {}'.format(index, utf8(entry)) with indent(3): print_message(line)
[ "def", "print_prompt_values", "(", "values", ",", "message", "=", "None", ",", "sub_attr", "=", "None", ")", ":", "if", "message", ":", "prompt_message", "(", "message", ")", "for", "index", ",", "entry", "in", "enumerate", "(", "values", ")", ":", "if",...
Prints prompt title and choices with a bit of formatting.
[ "Prints", "prompt", "title", "and", "choices", "with", "a", "bit", "of", "formatting", "." ]
e46bce4529fbdca34a4190c18c7219e937e2b697
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/utils.py#L90-L102
21,918
reincubate/ricloud
ricloud/utils.py
prompt_for_input
def prompt_for_input(message, input_type=None): """Prints prompt instruction and does basic input parsing.""" while True: output = prompt.query(message) if input_type: try: output = input_type(output) except ValueError: error_message('Invalid input type') continue break return output
python
def prompt_for_input(message, input_type=None): while True: output = prompt.query(message) if input_type: try: output = input_type(output) except ValueError: error_message('Invalid input type') continue break return output
[ "def", "prompt_for_input", "(", "message", ",", "input_type", "=", "None", ")", ":", "while", "True", ":", "output", "=", "prompt", ".", "query", "(", "message", ")", "if", "input_type", ":", "try", ":", "output", "=", "input_type", "(", "output", ")", ...
Prints prompt instruction and does basic input parsing.
[ "Prints", "prompt", "instruction", "and", "does", "basic", "input", "parsing", "." ]
e46bce4529fbdca34a4190c18c7219e937e2b697
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/utils.py#L105-L119
21,919
reincubate/ricloud
ricloud/utils.py
prompt_for_choice
def prompt_for_choice(values, message, input_type=int, output_type=None): """Prints prompt with a list of choices to choose from.""" output = None while not output: index = prompt_for_input(message, input_type=input_type) try: output = utf8(values[index]) except IndexError: error_message('Selection out of range') continue if output_type: output = output_type(output) return output
python
def prompt_for_choice(values, message, input_type=int, output_type=None): output = None while not output: index = prompt_for_input(message, input_type=input_type) try: output = utf8(values[index]) except IndexError: error_message('Selection out of range') continue if output_type: output = output_type(output) return output
[ "def", "prompt_for_choice", "(", "values", ",", "message", ",", "input_type", "=", "int", ",", "output_type", "=", "None", ")", ":", "output", "=", "None", "while", "not", "output", ":", "index", "=", "prompt_for_input", "(", "message", ",", "input_type", ...
Prints prompt with a list of choices to choose from.
[ "Prints", "prompt", "with", "a", "list", "of", "choices", "to", "choose", "from", "." ]
e46bce4529fbdca34a4190c18c7219e937e2b697
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/utils.py#L122-L137
21,920
reincubate/ricloud
ricloud/object_store.py
ObjectStore._retrieve_result
def _retrieve_result(endpoints, token_header): """Prepare the request list and execute them concurrently.""" request_list = [ (url, token_header) for (task_id, url) in endpoints ] responses = concurrent_get(request_list) # Quick sanity check assert len(endpoints) == len(responses) responses_dic = { task_id: r.content for (task_id, _), r in zip(endpoints, responses) } return responses_dic
python
def _retrieve_result(endpoints, token_header): request_list = [ (url, token_header) for (task_id, url) in endpoints ] responses = concurrent_get(request_list) # Quick sanity check assert len(endpoints) == len(responses) responses_dic = { task_id: r.content for (task_id, _), r in zip(endpoints, responses) } return responses_dic
[ "def", "_retrieve_result", "(", "endpoints", ",", "token_header", ")", ":", "request_list", "=", "[", "(", "url", ",", "token_header", ")", "for", "(", "task_id", ",", "url", ")", "in", "endpoints", "]", "responses", "=", "concurrent_get", "(", "request_list...
Prepare the request list and execute them concurrently.
[ "Prepare", "the", "request", "list", "and", "execute", "them", "concurrently", "." ]
e46bce4529fbdca34a4190c18c7219e937e2b697
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/object_store.py#L62-L78
21,921
reincubate/ricloud
ricloud/asmaster_api.py
AsmasterApi._build_endpoint
def _build_endpoint(self, endpoint_name): """Generate an enpoint url from a setting name. Args: endpoint_name(str): setting name for the enpoint to build Returns: (str) url enpoint """ endpoint_relative = settings.get('asmaster_endpoints', endpoint_name) return '%s%s' % (self.host, endpoint_relative)
python
def _build_endpoint(self, endpoint_name): endpoint_relative = settings.get('asmaster_endpoints', endpoint_name) return '%s%s' % (self.host, endpoint_relative)
[ "def", "_build_endpoint", "(", "self", ",", "endpoint_name", ")", ":", "endpoint_relative", "=", "settings", ".", "get", "(", "'asmaster_endpoints'", ",", "endpoint_name", ")", "return", "'%s%s'", "%", "(", "self", ".", "host", ",", "endpoint_relative", ")" ]
Generate an enpoint url from a setting name. Args: endpoint_name(str): setting name for the enpoint to build Returns: (str) url enpoint
[ "Generate", "an", "enpoint", "url", "from", "a", "setting", "name", "." ]
e46bce4529fbdca34a4190c18c7219e937e2b697
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/asmaster_api.py#L33-L43
21,922
reincubate/ricloud
ricloud/asmaster_api.py
AsmasterApi._set_allowed_services_and_actions
def _set_allowed_services_and_actions(self, services): """Expect services to be a list of service dictionaries, each with `name` and `actions` keys.""" for service in services: self.services[service['name']] = {} for action in service['actions']: name = action.pop('name') self.services[service['name']][name] = action
python
def _set_allowed_services_and_actions(self, services): for service in services: self.services[service['name']] = {} for action in service['actions']: name = action.pop('name') self.services[service['name']][name] = action
[ "def", "_set_allowed_services_and_actions", "(", "self", ",", "services", ")", ":", "for", "service", "in", "services", ":", "self", ".", "services", "[", "service", "[", "'name'", "]", "]", "=", "{", "}", "for", "action", "in", "service", "[", "'actions'"...
Expect services to be a list of service dictionaries, each with `name` and `actions` keys.
[ "Expect", "services", "to", "be", "a", "list", "of", "service", "dictionaries", "each", "with", "name", "and", "actions", "keys", "." ]
e46bce4529fbdca34a4190c18c7219e937e2b697
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/asmaster_api.py#L59-L66
21,923
reincubate/ricloud
ricloud/asmaster_api.py
AsmasterApi.list_subscriptions
def list_subscriptions(self, service): """Asks for a list of all subscribed accounts and devices, along with their statuses.""" data = { 'service': service, } return self._perform_post_request(self.list_subscriptions_endpoint, data, self.token_header)
python
def list_subscriptions(self, service): data = { 'service': service, } return self._perform_post_request(self.list_subscriptions_endpoint, data, self.token_header)
[ "def", "list_subscriptions", "(", "self", ",", "service", ")", ":", "data", "=", "{", "'service'", ":", "service", ",", "}", "return", "self", ".", "_perform_post_request", "(", "self", ".", "list_subscriptions_endpoint", ",", "data", ",", "self", ".", "toke...
Asks for a list of all subscribed accounts and devices, along with their statuses.
[ "Asks", "for", "a", "list", "of", "all", "subscribed", "accounts", "and", "devices", "along", "with", "their", "statuses", "." ]
e46bce4529fbdca34a4190c18c7219e937e2b697
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/asmaster_api.py#L84-L89
21,924
reincubate/ricloud
ricloud/asmaster_api.py
AsmasterApi.subscribe_account
def subscribe_account(self, username, password, service): """Subscribe an account for a service. """ data = { 'service': service, 'username': username, 'password': password, } return self._perform_post_request(self.subscribe_account_endpoint, data, self.token_header)
python
def subscribe_account(self, username, password, service): data = { 'service': service, 'username': username, 'password': password, } return self._perform_post_request(self.subscribe_account_endpoint, data, self.token_header)
[ "def", "subscribe_account", "(", "self", ",", "username", ",", "password", ",", "service", ")", ":", "data", "=", "{", "'service'", ":", "service", ",", "'username'", ":", "username", ",", "'password'", ":", "password", ",", "}", "return", "self", ".", "...
Subscribe an account for a service.
[ "Subscribe", "an", "account", "for", "a", "service", "." ]
e46bce4529fbdca34a4190c18c7219e937e2b697
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/asmaster_api.py#L91-L100
21,925
reincubate/ricloud
ricloud/asmaster_listener.py
AsmasterDownloadFileHandler.file_id_to_file_name
def file_id_to_file_name(file_id): """Sometimes file ids are not the file names on the device, but are instead generated by the API. These are not guaranteed to be valid file names so need hashing. """ if len(file_id) == 40 and re.match("^[a-f0-9]+$", file_id): return file_id # prefix with "re_" to avoid name collision with real fileids return "re_{}".format(hashlib.sha1(file_id).hexdigest())
python
def file_id_to_file_name(file_id): if len(file_id) == 40 and re.match("^[a-f0-9]+$", file_id): return file_id # prefix with "re_" to avoid name collision with real fileids return "re_{}".format(hashlib.sha1(file_id).hexdigest())
[ "def", "file_id_to_file_name", "(", "file_id", ")", ":", "if", "len", "(", "file_id", ")", "==", "40", "and", "re", ".", "match", "(", "\"^[a-f0-9]+$\"", ",", "file_id", ")", ":", "return", "file_id", "# prefix with \"re_\" to avoid name collision with real fileids"...
Sometimes file ids are not the file names on the device, but are instead generated by the API. These are not guaranteed to be valid file names so need hashing.
[ "Sometimes", "file", "ids", "are", "not", "the", "file", "names", "on", "the", "device", "but", "are", "instead", "generated", "by", "the", "API", ".", "These", "are", "not", "guaranteed", "to", "be", "valid", "file", "names", "so", "need", "hashing", "....
e46bce4529fbdca34a4190c18c7219e937e2b697
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/asmaster_listener.py#L216-L223
21,926
reincubate/ricloud
ricloud/clients/base.py
sync
def sync(func): """Decorator to make a task synchronous.""" sync_timeout = 3600 # Match standard synchronous timeout. def wraps(*args, **kwargs): task = func(*args, **kwargs) task.wait_for_result(timeout=sync_timeout) result = json.loads(task.result) return result return wraps
python
def sync(func): sync_timeout = 3600 # Match standard synchronous timeout. def wraps(*args, **kwargs): task = func(*args, **kwargs) task.wait_for_result(timeout=sync_timeout) result = json.loads(task.result) return result return wraps
[ "def", "sync", "(", "func", ")", ":", "sync_timeout", "=", "3600", "# Match standard synchronous timeout.", "def", "wraps", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "task", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "task"...
Decorator to make a task synchronous.
[ "Decorator", "to", "make", "a", "task", "synchronous", "." ]
e46bce4529fbdca34a4190c18c7219e937e2b697
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/clients/base.py#L4-L14
21,927
reincubate/ricloud
ricloud/samples/live_sample.py
SampleLiveICloudApplication.fetch_data
def fetch_data(self): """Prompt for a data type choice and execute the `fetch_data` task. The results are saved to a file in json format. """ choices = self.available_data choices.insert(0, 'All') selected_data_type = utils.select_item( choices, 'Please select what data to fetch:', 'Available data:', ) if selected_data_type == 'All': selected_data_type = ','.join(self.available_data) utils.pending_message('Performing fetch data task...') fetch_data_task = self.client.data( account=self.account, data=selected_data_type, ) # Wait here for result as rest of sample app relies on it. fetch_data_task.wait_for_result(timeout=self.timeout) fetch_data_result = json.loads(fetch_data_task.result) # Write the result to file. task_id = fetch_data_task.uuid filepath = utils.get_or_create_filepath('%s.json' % task_id) with open(filepath, 'w') as out: json.dump(fetch_data_result, out, indent=2) utils.info_message('Fetch data successful. Output file: %s.json' % task_id) return fetch_data_result
python
def fetch_data(self): choices = self.available_data choices.insert(0, 'All') selected_data_type = utils.select_item( choices, 'Please select what data to fetch:', 'Available data:', ) if selected_data_type == 'All': selected_data_type = ','.join(self.available_data) utils.pending_message('Performing fetch data task...') fetch_data_task = self.client.data( account=self.account, data=selected_data_type, ) # Wait here for result as rest of sample app relies on it. fetch_data_task.wait_for_result(timeout=self.timeout) fetch_data_result = json.loads(fetch_data_task.result) # Write the result to file. task_id = fetch_data_task.uuid filepath = utils.get_or_create_filepath('%s.json' % task_id) with open(filepath, 'w') as out: json.dump(fetch_data_result, out, indent=2) utils.info_message('Fetch data successful. Output file: %s.json' % task_id) return fetch_data_result
[ "def", "fetch_data", "(", "self", ")", ":", "choices", "=", "self", ".", "available_data", "choices", ".", "insert", "(", "0", ",", "'All'", ")", "selected_data_type", "=", "utils", ".", "select_item", "(", "choices", ",", "'Please select what data to fetch:'", ...
Prompt for a data type choice and execute the `fetch_data` task. The results are saved to a file in json format.
[ "Prompt", "for", "a", "data", "type", "choice", "and", "execute", "the", "fetch_data", "task", ".", "The", "results", "are", "saved", "to", "a", "file", "in", "json", "format", "." ]
e46bce4529fbdca34a4190c18c7219e937e2b697
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/samples/live_sample.py#L22-L58
21,928
reincubate/ricloud
ricloud/samples/icloud_sample.py
SampleICloudApplication.log_in
def log_in(self): """Perform the `log_in` task to setup the API session for future data requests.""" if not self.password: # Password wasn't give, ask for it now self.password = getpass.getpass('Password: ') utils.pending_message('Performing login...') login_result = self.client.login( account=self.account, password=self.password ) if 'error' in login_result: self.handle_failed_login(login_result) utils.info_message('Login successful')
python
def log_in(self): if not self.password: # Password wasn't give, ask for it now self.password = getpass.getpass('Password: ') utils.pending_message('Performing login...') login_result = self.client.login( account=self.account, password=self.password ) if 'error' in login_result: self.handle_failed_login(login_result) utils.info_message('Login successful')
[ "def", "log_in", "(", "self", ")", ":", "if", "not", "self", ".", "password", ":", "# Password wasn't give, ask for it now", "self", ".", "password", "=", "getpass", ".", "getpass", "(", "'Password: '", ")", "utils", ".", "pending_message", "(", "'Performing log...
Perform the `log_in` task to setup the API session for future data requests.
[ "Perform", "the", "log_in", "task", "to", "setup", "the", "API", "session", "for", "future", "data", "requests", "." ]
e46bce4529fbdca34a4190c18c7219e937e2b697
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/samples/icloud_sample.py#L43-L59
21,929
reincubate/ricloud
ricloud/samples/icloud_sample.py
SampleICloudApplication.get_devices
def get_devices(self): """Execute the `get_devices` task and store the results in `self.devices`.""" utils.pending_message('Fetching device list...') get_devices_task = self.client.devices( account=self.account ) # We wait for device list info as this sample relies on it next. get_devices_task.wait_for_result(timeout=self.timeout) get_devices_result = json.loads(get_devices_task.result) self.devices = get_devices_result['devices'] utils.info_message('Get devices successful')
python
def get_devices(self): utils.pending_message('Fetching device list...') get_devices_task = self.client.devices( account=self.account ) # We wait for device list info as this sample relies on it next. get_devices_task.wait_for_result(timeout=self.timeout) get_devices_result = json.loads(get_devices_task.result) self.devices = get_devices_result['devices'] utils.info_message('Get devices successful')
[ "def", "get_devices", "(", "self", ")", ":", "utils", ".", "pending_message", "(", "'Fetching device list...'", ")", "get_devices_task", "=", "self", ".", "client", ".", "devices", "(", "account", "=", "self", ".", "account", ")", "# We wait for device list info a...
Execute the `get_devices` task and store the results in `self.devices`.
[ "Execute", "the", "get_devices", "task", "and", "store", "the", "results", "in", "self", ".", "devices", "." ]
e46bce4529fbdca34a4190c18c7219e937e2b697
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/samples/icloud_sample.py#L113-L127
21,930
reincubate/ricloud
ricloud/samples/icloud_sample.py
SampleICloudApplication.download_files
def download_files(self, files): """This method uses the `download_file` task to retrieve binary files such as attachments, images and videos. Notice that this method does not wait for the tasks it creates to return a result synchronously. """ utils.pending_message( "Downloading {nfiles} file{plural}...".format( nfiles=len(files), plural='s' if len(files) > 1 else '' )) for file in files: if 'file_id' not in file: continue def build_callback(file): """Callback to save a download file result to a file on disk.""" def file_callback(task): device_name = self.devices[self.device_id]['device_name'] path_chunks = file['file_path'].split('/') directory = os.path.join('files', device_name, *path_chunks[:-1]) filepath = utils.get_or_create_filepath(file['filename'], directory) with open(filepath, 'wb') as out: out.write(task.result) if settings.getboolean('logging', 'time_profile'): filepath = utils.append_profile_info(filepath, task.timer) with indent(4): utils.print_message(filepath) return file_callback self.client.download_file( account=self.account, device=self.device_id, file=file['file_id'], callback=build_callback(file) )
python
def download_files(self, files): utils.pending_message( "Downloading {nfiles} file{plural}...".format( nfiles=len(files), plural='s' if len(files) > 1 else '' )) for file in files: if 'file_id' not in file: continue def build_callback(file): """Callback to save a download file result to a file on disk.""" def file_callback(task): device_name = self.devices[self.device_id]['device_name'] path_chunks = file['file_path'].split('/') directory = os.path.join('files', device_name, *path_chunks[:-1]) filepath = utils.get_or_create_filepath(file['filename'], directory) with open(filepath, 'wb') as out: out.write(task.result) if settings.getboolean('logging', 'time_profile'): filepath = utils.append_profile_info(filepath, task.timer) with indent(4): utils.print_message(filepath) return file_callback self.client.download_file( account=self.account, device=self.device_id, file=file['file_id'], callback=build_callback(file) )
[ "def", "download_files", "(", "self", ",", "files", ")", ":", "utils", ".", "pending_message", "(", "\"Downloading {nfiles} file{plural}...\"", ".", "format", "(", "nfiles", "=", "len", "(", "files", ")", ",", "plural", "=", "'s'", "if", "len", "(", "files",...
This method uses the `download_file` task to retrieve binary files such as attachments, images and videos. Notice that this method does not wait for the tasks it creates to return a result synchronously.
[ "This", "method", "uses", "the", "download_file", "task", "to", "retrieve", "binary", "files", "such", "as", "attachments", "images", "and", "videos", "." ]
e46bce4529fbdca34a4190c18c7219e937e2b697
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/samples/icloud_sample.py#L183-L226
21,931
reincubate/ricloud
ricloud/api.py
Api.register_account
def register_account(self, username, service): """Register an account against a service. The account that we're querying must be referenced during any future task requests - so we know which account to link the task too. """ data = { 'service': service, 'username': username, } return self._perform_post_request(self.register_account_endpoint, data, self.token_header)
python
def register_account(self, username, service): data = { 'service': service, 'username': username, } return self._perform_post_request(self.register_account_endpoint, data, self.token_header)
[ "def", "register_account", "(", "self", ",", "username", ",", "service", ")", ":", "data", "=", "{", "'service'", ":", "service", ",", "'username'", ":", "username", ",", "}", "return", "self", ".", "_perform_post_request", "(", "self", ".", "register_accoun...
Register an account against a service. The account that we're querying must be referenced during any future task requests - so we know which account to link the task too.
[ "Register", "an", "account", "against", "a", "service", ".", "The", "account", "that", "we", "re", "querying", "must", "be", "referenced", "during", "any", "future", "task", "requests", "-", "so", "we", "know", "which", "account", "to", "link", "the", "tas...
e46bce4529fbdca34a4190c18c7219e937e2b697
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/api.py#L79-L90
21,932
reincubate/ricloud
ricloud/api.py
Api.perform_task
def perform_task(self, service, task_name, account, payload, callback=None): """Submit a task to the API. The task is executed asyncronously, and a Task object is returned. """ data = { 'service': service, 'action': task_name, 'account': account, } data.update(payload) response = self._perform_post_request(self.submit_endpoint, data, self.token_header) task = Task(uuid=response['task_id'], callback=callback) self._pending_tasks[task.uuid] = task return task
python
def perform_task(self, service, task_name, account, payload, callback=None): data = { 'service': service, 'action': task_name, 'account': account, } data.update(payload) response = self._perform_post_request(self.submit_endpoint, data, self.token_header) task = Task(uuid=response['task_id'], callback=callback) self._pending_tasks[task.uuid] = task return task
[ "def", "perform_task", "(", "self", ",", "service", ",", "task_name", ",", "account", ",", "payload", ",", "callback", "=", "None", ")", ":", "data", "=", "{", "'service'", ":", "service", ",", "'action'", ":", "task_name", ",", "'account'", ":", "accoun...
Submit a task to the API. The task is executed asyncronously, and a Task object is returned.
[ "Submit", "a", "task", "to", "the", "API", ".", "The", "task", "is", "executed", "asyncronously", "and", "a", "Task", "object", "is", "returned", "." ]
e46bce4529fbdca34a4190c18c7219e937e2b697
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/api.py#L92-L108
21,933
reincubate/ricloud
ricloud/api.py
Api.task_status
def task_status(self, task_id): """Find the status of a task.""" data = { 'task_ids': task_id, } return self._perform_post_request(self.task_status_endpoint, data, self.token_header)
python
def task_status(self, task_id): data = { 'task_ids': task_id, } return self._perform_post_request(self.task_status_endpoint, data, self.token_header)
[ "def", "task_status", "(", "self", ",", "task_id", ")", ":", "data", "=", "{", "'task_ids'", ":", "task_id", ",", "}", "return", "self", ".", "_perform_post_request", "(", "self", ".", "task_status_endpoint", ",", "data", ",", "self", ".", "token_header", ...
Find the status of a task.
[ "Find", "the", "status", "of", "a", "task", "." ]
e46bce4529fbdca34a4190c18c7219e937e2b697
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/api.py#L110-L115
21,934
reincubate/ricloud
ricloud/api.py
Api.result_consumed
def result_consumed(self, task_id): """Report the result as successfully consumed.""" logger.debug('Sending result consumed message.') data = { 'task_ids': task_id, } return self._perform_post_request(self.results_consumed_endpoint, data, self.token_header)
python
def result_consumed(self, task_id): logger.debug('Sending result consumed message.') data = { 'task_ids': task_id, } return self._perform_post_request(self.results_consumed_endpoint, data, self.token_header)
[ "def", "result_consumed", "(", "self", ",", "task_id", ")", ":", "logger", ".", "debug", "(", "'Sending result consumed message.'", ")", "data", "=", "{", "'task_ids'", ":", "task_id", ",", "}", "return", "self", ".", "_perform_post_request", "(", "self", ".",...
Report the result as successfully consumed.
[ "Report", "the", "result", "as", "successfully", "consumed", "." ]
e46bce4529fbdca34a4190c18c7219e937e2b697
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/api.py#L117-L123
21,935
nitmir/django-cas-server
cas_server/models.py
NewVersionWarning.send_mails
def send_mails(cls): """ For each new django-cas-server version, if the current instance is not up to date send one mail to ``settings.ADMINS``. """ if settings.CAS_NEW_VERSION_EMAIL_WARNING and settings.ADMINS: try: obj = cls.objects.get() except cls.DoesNotExist: obj = NewVersionWarning.objects.create(version=VERSION) LAST_VERSION = utils.last_version() if LAST_VERSION is not None and LAST_VERSION != obj.version: if utils.decode_version(VERSION) < utils.decode_version(LAST_VERSION): try: send_mail( ( '%sA new version of django-cas-server is available' ) % settings.EMAIL_SUBJECT_PREFIX, u''' A new version of the django-cas-server is available. Your version: %s New version: %s Upgrade using: * pip install -U django-cas-server * fetching the last release on https://github.com/nitmir/django-cas-server/ or on https://pypi.org/project/django-cas-server/ After upgrade, do not forget to run: * ./manage.py migrate * ./manage.py collectstatic and to reload your wsgi server (apache2, uwsgi, gunicord, etc…) --\u0020 django-cas-server '''.strip() % (VERSION, LAST_VERSION), settings.SERVER_EMAIL, ["%s <%s>" % admin for admin in settings.ADMINS], fail_silently=False, ) obj.version = LAST_VERSION obj.save() except smtplib.SMTPException as error: # pragma: no cover (should not happen) logger.error("Unable to send new version mail: %s" % error)
python
def send_mails(cls): if settings.CAS_NEW_VERSION_EMAIL_WARNING and settings.ADMINS: try: obj = cls.objects.get() except cls.DoesNotExist: obj = NewVersionWarning.objects.create(version=VERSION) LAST_VERSION = utils.last_version() if LAST_VERSION is not None and LAST_VERSION != obj.version: if utils.decode_version(VERSION) < utils.decode_version(LAST_VERSION): try: send_mail( ( '%sA new version of django-cas-server is available' ) % settings.EMAIL_SUBJECT_PREFIX, u''' A new version of the django-cas-server is available. Your version: %s New version: %s Upgrade using: * pip install -U django-cas-server * fetching the last release on https://github.com/nitmir/django-cas-server/ or on https://pypi.org/project/django-cas-server/ After upgrade, do not forget to run: * ./manage.py migrate * ./manage.py collectstatic and to reload your wsgi server (apache2, uwsgi, gunicord, etc…) --\u0020 django-cas-server '''.strip() % (VERSION, LAST_VERSION), settings.SERVER_EMAIL, ["%s <%s>" % admin for admin in settings.ADMINS], fail_silently=False, ) obj.version = LAST_VERSION obj.save() except smtplib.SMTPException as error: # pragma: no cover (should not happen) logger.error("Unable to send new version mail: %s" % error)
[ "def", "send_mails", "(", "cls", ")", ":", "if", "settings", ".", "CAS_NEW_VERSION_EMAIL_WARNING", "and", "settings", ".", "ADMINS", ":", "try", ":", "obj", "=", "cls", ".", "objects", ".", "get", "(", ")", "except", "cls", ".", "DoesNotExist", ":", "obj...
For each new django-cas-server version, if the current instance is not up to date send one mail to ``settings.ADMINS``.
[ "For", "each", "new", "django", "-", "cas", "-", "server", "version", "if", "the", "current", "instance", "is", "not", "up", "to", "date", "send", "one", "mail", "to", "settings", ".", "ADMINS", "." ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/models.py#L1072-L1117
21,936
nitmir/django-cas-server
cas_server/cas.py
CASClientBase.get_proxy_url
def get_proxy_url(self, pgt): """Returns proxy url, given the proxy granting ticket""" params = urllib_parse.urlencode({'pgt': pgt, 'targetService': self.service_url}) return "%s/proxy?%s" % (self.server_url, params)
python
def get_proxy_url(self, pgt): params = urllib_parse.urlencode({'pgt': pgt, 'targetService': self.service_url}) return "%s/proxy?%s" % (self.server_url, params)
[ "def", "get_proxy_url", "(", "self", ",", "pgt", ")", ":", "params", "=", "urllib_parse", ".", "urlencode", "(", "{", "'pgt'", ":", "pgt", ",", "'targetService'", ":", "self", ".", "service_url", "}", ")", "return", "\"%s/proxy?%s\"", "%", "(", "self", "...
Returns proxy url, given the proxy granting ticket
[ "Returns", "proxy", "url", "given", "the", "proxy", "granting", "ticket" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/cas.py#L112-L115
21,937
nitmir/django-cas-server
cas_server/auth.py
LdapAuthUser.get_conn
def get_conn(cls): """Return a connection object to the ldap database""" conn = cls._conn if conn is None or conn.closed: conn = ldap3.Connection( settings.CAS_LDAP_SERVER, settings.CAS_LDAP_USER, settings.CAS_LDAP_PASSWORD, client_strategy="RESTARTABLE", auto_bind=True ) cls._conn = conn return conn
python
def get_conn(cls): conn = cls._conn if conn is None or conn.closed: conn = ldap3.Connection( settings.CAS_LDAP_SERVER, settings.CAS_LDAP_USER, settings.CAS_LDAP_PASSWORD, client_strategy="RESTARTABLE", auto_bind=True ) cls._conn = conn return conn
[ "def", "get_conn", "(", "cls", ")", ":", "conn", "=", "cls", ".", "_conn", "if", "conn", "is", "None", "or", "conn", ".", "closed", ":", "conn", "=", "ldap3", ".", "Connection", "(", "settings", ".", "CAS_LDAP_SERVER", ",", "settings", ".", "CAS_LDAP_U...
Return a connection object to the ldap database
[ "Return", "a", "connection", "object", "to", "the", "ldap", "database" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/auth.py#L272-L284
21,938
nitmir/django-cas-server
cas_server/utils.py
json_encode
def json_encode(obj): """Encode a python object to json""" try: return json_encode.encoder.encode(obj) except AttributeError: json_encode.encoder = DjangoJSONEncoder(default=six.text_type) return json_encode(obj)
python
def json_encode(obj): try: return json_encode.encoder.encode(obj) except AttributeError: json_encode.encoder = DjangoJSONEncoder(default=six.text_type) return json_encode(obj)
[ "def", "json_encode", "(", "obj", ")", ":", "try", ":", "return", "json_encode", ".", "encoder", ".", "encode", "(", "obj", ")", "except", "AttributeError", ":", "json_encode", ".", "encoder", "=", "DjangoJSONEncoder", "(", "default", "=", "six", ".", "tex...
Encode a python object to json
[ "Encode", "a", "python", "object", "to", "json" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L50-L56
21,939
nitmir/django-cas-server
cas_server/utils.py
context
def context(params): """ Function that add somes variable to the context before template rendering :param dict params: The context dictionary used to render templates. :return: The ``params`` dictionary with the key ``settings`` set to :obj:`django.conf.settings`. :rtype: dict """ params["settings"] = settings params["message_levels"] = DEFAULT_MESSAGE_LEVELS if settings.CAS_NEW_VERSION_HTML_WARNING: LAST_VERSION = last_version() params["VERSION"] = VERSION params["LAST_VERSION"] = LAST_VERSION if LAST_VERSION is not None: params["upgrade_available"] = decode_version(VERSION) < decode_version(LAST_VERSION) else: params["upgrade_available"] = False if settings.CAS_INFO_MESSAGES_ORDER: params["CAS_INFO_RENDER"] = [] for msg_name in settings.CAS_INFO_MESSAGES_ORDER: if msg_name in settings.CAS_INFO_MESSAGES: if not isinstance(settings.CAS_INFO_MESSAGES[msg_name], dict): continue msg = settings.CAS_INFO_MESSAGES[msg_name].copy() if "message" in msg: msg["name"] = msg_name # use info as default infox type msg["type"] = msg.get("type", "info") # make box discardable by default msg["discardable"] = msg.get("discardable", True) msg_hash = ( six.text_type(msg["message"]).encode("utf-8") + msg["type"].encode("utf-8") ) # hash depend of the rendering language msg["hash"] = hashlib.md5(msg_hash).hexdigest() params["CAS_INFO_RENDER"].append(msg) return params
python
def context(params): params["settings"] = settings params["message_levels"] = DEFAULT_MESSAGE_LEVELS if settings.CAS_NEW_VERSION_HTML_WARNING: LAST_VERSION = last_version() params["VERSION"] = VERSION params["LAST_VERSION"] = LAST_VERSION if LAST_VERSION is not None: params["upgrade_available"] = decode_version(VERSION) < decode_version(LAST_VERSION) else: params["upgrade_available"] = False if settings.CAS_INFO_MESSAGES_ORDER: params["CAS_INFO_RENDER"] = [] for msg_name in settings.CAS_INFO_MESSAGES_ORDER: if msg_name in settings.CAS_INFO_MESSAGES: if not isinstance(settings.CAS_INFO_MESSAGES[msg_name], dict): continue msg = settings.CAS_INFO_MESSAGES[msg_name].copy() if "message" in msg: msg["name"] = msg_name # use info as default infox type msg["type"] = msg.get("type", "info") # make box discardable by default msg["discardable"] = msg.get("discardable", True) msg_hash = ( six.text_type(msg["message"]).encode("utf-8") + msg["type"].encode("utf-8") ) # hash depend of the rendering language msg["hash"] = hashlib.md5(msg_hash).hexdigest() params["CAS_INFO_RENDER"].append(msg) return params
[ "def", "context", "(", "params", ")", ":", "params", "[", "\"settings\"", "]", "=", "settings", "params", "[", "\"message_levels\"", "]", "=", "DEFAULT_MESSAGE_LEVELS", "if", "settings", ".", "CAS_NEW_VERSION_HTML_WARNING", ":", "LAST_VERSION", "=", "last_version", ...
Function that add somes variable to the context before template rendering :param dict params: The context dictionary used to render templates. :return: The ``params`` dictionary with the key ``settings`` set to :obj:`django.conf.settings`. :rtype: dict
[ "Function", "that", "add", "somes", "variable", "to", "the", "context", "before", "template", "rendering" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L59-L100
21,940
nitmir/django-cas-server
cas_server/utils.py
json_response
def json_response(request, data): """ Wrapper dumping `data` to a json and sending it to the user with an HttpResponse :param django.http.HttpRequest request: The request object used to generate this response. :param dict data: The python dictionnary to return as a json :return: The content of ``data`` serialized in json :rtype: django.http.HttpResponse """ data["messages"] = [] for msg in messages.get_messages(request): data["messages"].append({'message': msg.message, 'level': msg.level_tag}) return HttpResponse(json.dumps(data), content_type="application/json")
python
def json_response(request, data): data["messages"] = [] for msg in messages.get_messages(request): data["messages"].append({'message': msg.message, 'level': msg.level_tag}) return HttpResponse(json.dumps(data), content_type="application/json")
[ "def", "json_response", "(", "request", ",", "data", ")", ":", "data", "[", "\"messages\"", "]", "=", "[", "]", "for", "msg", "in", "messages", ".", "get_messages", "(", "request", ")", ":", "data", "[", "\"messages\"", "]", ".", "append", "(", "{", ...
Wrapper dumping `data` to a json and sending it to the user with an HttpResponse :param django.http.HttpRequest request: The request object used to generate this response. :param dict data: The python dictionnary to return as a json :return: The content of ``data`` serialized in json :rtype: django.http.HttpResponse
[ "Wrapper", "dumping", "data", "to", "a", "json", "and", "sending", "it", "to", "the", "user", "with", "an", "HttpResponse" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L103-L115
21,941
nitmir/django-cas-server
cas_server/utils.py
import_attr
def import_attr(path): """ transform a python dotted path to the attr :param path: A dotted path to a python object or a python object :type path: :obj:`unicode` or :obj:`str` or anything :return: The python object pointed by the dotted path or the python object unchanged """ # if we got a str, decode it to unicode (normally it should only contain ascii) if isinstance(path, six.binary_type): path = path.decode("utf-8") # if path is not an unicode, return it unchanged (may be it is already the attribute to import) if not isinstance(path, six.text_type): return path if u"." not in path: ValueError("%r should be of the form `module.attr` and we just got `attr`" % path) module, attr = path.rsplit(u'.', 1) try: return getattr(import_module(module), attr) except ImportError: raise ImportError("Module %r not found" % module) except AttributeError: raise AttributeError("Module %r has not attribut %r" % (module, attr))
python
def import_attr(path): # if we got a str, decode it to unicode (normally it should only contain ascii) if isinstance(path, six.binary_type): path = path.decode("utf-8") # if path is not an unicode, return it unchanged (may be it is already the attribute to import) if not isinstance(path, six.text_type): return path if u"." not in path: ValueError("%r should be of the form `module.attr` and we just got `attr`" % path) module, attr = path.rsplit(u'.', 1) try: return getattr(import_module(module), attr) except ImportError: raise ImportError("Module %r not found" % module) except AttributeError: raise AttributeError("Module %r has not attribut %r" % (module, attr))
[ "def", "import_attr", "(", "path", ")", ":", "# if we got a str, decode it to unicode (normally it should only contain ascii)", "if", "isinstance", "(", "path", ",", "six", ".", "binary_type", ")", ":", "path", "=", "path", ".", "decode", "(", "\"utf-8\"", ")", "# i...
transform a python dotted path to the attr :param path: A dotted path to a python object or a python object :type path: :obj:`unicode` or :obj:`str` or anything :return: The python object pointed by the dotted path or the python object unchanged
[ "transform", "a", "python", "dotted", "path", "to", "the", "attr" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L118-L140
21,942
nitmir/django-cas-server
cas_server/utils.py
redirect_params
def redirect_params(url_name, params=None): """ Redirect to ``url_name`` with ``params`` as querystring :param unicode url_name: a URL pattern name :param params: Some parameter to append to the reversed URL :type params: :obj:`dict` or :obj:`NoneType<types.NoneType>` :return: A redirection to the URL with name ``url_name`` with ``params`` as querystring. :rtype: django.http.HttpResponseRedirect """ url = reverse(url_name) params = urlencode(params if params else {}) return HttpResponseRedirect(url + "?%s" % params)
python
def redirect_params(url_name, params=None): url = reverse(url_name) params = urlencode(params if params else {}) return HttpResponseRedirect(url + "?%s" % params)
[ "def", "redirect_params", "(", "url_name", ",", "params", "=", "None", ")", ":", "url", "=", "reverse", "(", "url_name", ")", "params", "=", "urlencode", "(", "params", "if", "params", "else", "{", "}", ")", "return", "HttpResponseRedirect", "(", "url", ...
Redirect to ``url_name`` with ``params`` as querystring :param unicode url_name: a URL pattern name :param params: Some parameter to append to the reversed URL :type params: :obj:`dict` or :obj:`NoneType<types.NoneType>` :return: A redirection to the URL with name ``url_name`` with ``params`` as querystring. :rtype: django.http.HttpResponseRedirect
[ "Redirect", "to", "url_name", "with", "params", "as", "querystring" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L143-L155
21,943
nitmir/django-cas-server
cas_server/utils.py
reverse_params
def reverse_params(url_name, params=None, **kwargs): """ compute the reverse url of ``url_name`` and add to it parameters from ``params`` as querystring :param unicode url_name: a URL pattern name :param params: Some parameter to append to the reversed URL :type params: :obj:`dict` or :obj:`NoneType<types.NoneType>` :param **kwargs: additional parameters needed to compure the reverse URL :return: The computed reverse URL of ``url_name`` with possible querystring from ``params`` :rtype: unicode """ url = reverse(url_name, **kwargs) params = urlencode(params if params else {}) if params: return u"%s?%s" % (url, params) else: return url
python
def reverse_params(url_name, params=None, **kwargs): url = reverse(url_name, **kwargs) params = urlencode(params if params else {}) if params: return u"%s?%s" % (url, params) else: return url
[ "def", "reverse_params", "(", "url_name", ",", "params", "=", "None", ",", "*", "*", "kwargs", ")", ":", "url", "=", "reverse", "(", "url_name", ",", "*", "*", "kwargs", ")", "params", "=", "urlencode", "(", "params", "if", "params", "else", "{", "}"...
compute the reverse url of ``url_name`` and add to it parameters from ``params`` as querystring :param unicode url_name: a URL pattern name :param params: Some parameter to append to the reversed URL :type params: :obj:`dict` or :obj:`NoneType<types.NoneType>` :param **kwargs: additional parameters needed to compure the reverse URL :return: The computed reverse URL of ``url_name`` with possible querystring from ``params`` :rtype: unicode
[ "compute", "the", "reverse", "url", "of", "url_name", "and", "add", "to", "it", "parameters", "from", "params", "as", "querystring" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L158-L175
21,944
nitmir/django-cas-server
cas_server/utils.py
set_cookie
def set_cookie(response, key, value, max_age): """ Set the cookie ``key`` on ``response`` with value ``value`` valid for ``max_age`` secondes :param django.http.HttpResponse response: a django response where to set the cookie :param unicode key: the cookie key :param unicode value: the cookie value :param int max_age: the maximum validity age of the cookie """ expires = datetime.strftime( datetime.utcnow() + timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT" ) response.set_cookie( key, value, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN, secure=settings.SESSION_COOKIE_SECURE or None )
python
def set_cookie(response, key, value, max_age): expires = datetime.strftime( datetime.utcnow() + timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT" ) response.set_cookie( key, value, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN, secure=settings.SESSION_COOKIE_SECURE or None )
[ "def", "set_cookie", "(", "response", ",", "key", ",", "value", ",", "max_age", ")", ":", "expires", "=", "datetime", ".", "strftime", "(", "datetime", ".", "utcnow", "(", ")", "+", "timedelta", "(", "seconds", "=", "max_age", ")", ",", "\"%a, %d-%b-%Y %...
Set the cookie ``key`` on ``response`` with value ``value`` valid for ``max_age`` secondes :param django.http.HttpResponse response: a django response where to set the cookie :param unicode key: the cookie key :param unicode value: the cookie value :param int max_age: the maximum validity age of the cookie
[ "Set", "the", "cookie", "key", "on", "response", "with", "value", "value", "valid", "for", "max_age", "secondes" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L197-L217
21,945
nitmir/django-cas-server
cas_server/utils.py
get_current_url
def get_current_url(request, ignore_params=None): """ Giving a django request, return the current http url, possibly ignoring some GET parameters :param django.http.HttpRequest request: The current request object. :param set ignore_params: An optional set of GET parameters to ignore :return: The URL of the current page, possibly omitting some parameters from ``ignore_params`` in the querystring. :rtype: unicode """ if ignore_params is None: ignore_params = set() protocol = u'https' if request.is_secure() else u"http" service_url = u"%s://%s%s" % (protocol, request.get_host(), request.path) if request.GET: params = copy_params(request.GET, ignore_params) if params: service_url += u"?%s" % urlencode(params) return service_url
python
def get_current_url(request, ignore_params=None): if ignore_params is None: ignore_params = set() protocol = u'https' if request.is_secure() else u"http" service_url = u"%s://%s%s" % (protocol, request.get_host(), request.path) if request.GET: params = copy_params(request.GET, ignore_params) if params: service_url += u"?%s" % urlencode(params) return service_url
[ "def", "get_current_url", "(", "request", ",", "ignore_params", "=", "None", ")", ":", "if", "ignore_params", "is", "None", ":", "ignore_params", "=", "set", "(", ")", "protocol", "=", "u'https'", "if", "request", ".", "is_secure", "(", ")", "else", "u\"ht...
Giving a django request, return the current http url, possibly ignoring some GET parameters :param django.http.HttpRequest request: The current request object. :param set ignore_params: An optional set of GET parameters to ignore :return: The URL of the current page, possibly omitting some parameters from ``ignore_params`` in the querystring. :rtype: unicode
[ "Giving", "a", "django", "request", "return", "the", "current", "http", "url", "possibly", "ignoring", "some", "GET", "parameters" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L220-L238
21,946
nitmir/django-cas-server
cas_server/utils.py
update_url
def update_url(url, params): """ update parameters using ``params`` in the ``url`` query string :param url: An URL possibily with a querystring :type url: :obj:`unicode` or :obj:`str` :param dict params: A dictionary of parameters for updating the url querystring :return: The URL with an updated querystring :rtype: unicode """ if not isinstance(url, bytes): url = url.encode('utf-8') for key, value in list(params.items()): if not isinstance(key, bytes): del params[key] key = key.encode('utf-8') if not isinstance(value, bytes): value = value.encode('utf-8') params[key] = value url_parts = list(urlparse(url)) query = dict(parse_qsl(url_parts[4])) query.update(params) # make the params order deterministic query = list(query.items()) query.sort() url_query = urlencode(query) if not isinstance(url_query, bytes): # pragma: no cover in python3 urlencode return an unicode url_query = url_query.encode("utf-8") url_parts[4] = url_query return urlunparse(url_parts).decode('utf-8')
python
def update_url(url, params): if not isinstance(url, bytes): url = url.encode('utf-8') for key, value in list(params.items()): if not isinstance(key, bytes): del params[key] key = key.encode('utf-8') if not isinstance(value, bytes): value = value.encode('utf-8') params[key] = value url_parts = list(urlparse(url)) query = dict(parse_qsl(url_parts[4])) query.update(params) # make the params order deterministic query = list(query.items()) query.sort() url_query = urlencode(query) if not isinstance(url_query, bytes): # pragma: no cover in python3 urlencode return an unicode url_query = url_query.encode("utf-8") url_parts[4] = url_query return urlunparse(url_parts).decode('utf-8')
[ "def", "update_url", "(", "url", ",", "params", ")", ":", "if", "not", "isinstance", "(", "url", ",", "bytes", ")", ":", "url", "=", "url", ".", "encode", "(", "'utf-8'", ")", "for", "key", ",", "value", "in", "list", "(", "params", ".", "items", ...
update parameters using ``params`` in the ``url`` query string :param url: An URL possibily with a querystring :type url: :obj:`unicode` or :obj:`str` :param dict params: A dictionary of parameters for updating the url querystring :return: The URL with an updated querystring :rtype: unicode
[ "update", "parameters", "using", "params", "in", "the", "url", "query", "string" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L241-L270
21,947
nitmir/django-cas-server
cas_server/utils.py
unpack_nested_exception
def unpack_nested_exception(error): """ If exception are stacked, return the first one :param error: A python exception with possible exception embeded within :return: A python exception with no exception embeded within """ i = 0 while True: if error.args[i:]: if isinstance(error.args[i], Exception): error = error.args[i] i = 0 else: i += 1 else: break return error
python
def unpack_nested_exception(error): i = 0 while True: if error.args[i:]: if isinstance(error.args[i], Exception): error = error.args[i] i = 0 else: i += 1 else: break return error
[ "def", "unpack_nested_exception", "(", "error", ")", ":", "i", "=", "0", "while", "True", ":", "if", "error", ".", "args", "[", "i", ":", "]", ":", "if", "isinstance", "(", "error", ".", "args", "[", "i", "]", ",", "Exception", ")", ":", "error", ...
If exception are stacked, return the first one :param error: A python exception with possible exception embeded within :return: A python exception with no exception embeded within
[ "If", "exception", "are", "stacked", "return", "the", "first", "one" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L273-L290
21,948
nitmir/django-cas-server
cas_server/utils.py
_gen_ticket
def _gen_ticket(prefix=None, lg=settings.CAS_TICKET_LEN): """ Generate a ticket with prefix ``prefix`` and length ``lg`` :param unicode prefix: An optional prefix (probably ST, PT, PGT or PGTIOU) :param int lg: The length of the generated ticket (with the prefix) :return: A randomlly generated ticket of length ``lg`` :rtype: unicode """ random_part = u''.join( random.choice( string.ascii_letters + string.digits ) for _ in range(lg - len(prefix or "") - 1) ) if prefix is not None: return u'%s-%s' % (prefix, random_part) else: return random_part
python
def _gen_ticket(prefix=None, lg=settings.CAS_TICKET_LEN): random_part = u''.join( random.choice( string.ascii_letters + string.digits ) for _ in range(lg - len(prefix or "") - 1) ) if prefix is not None: return u'%s-%s' % (prefix, random_part) else: return random_part
[ "def", "_gen_ticket", "(", "prefix", "=", "None", ",", "lg", "=", "settings", ".", "CAS_TICKET_LEN", ")", ":", "random_part", "=", "u''", ".", "join", "(", "random", ".", "choice", "(", "string", ".", "ascii_letters", "+", "string", ".", "digits", ")", ...
Generate a ticket with prefix ``prefix`` and length ``lg`` :param unicode prefix: An optional prefix (probably ST, PT, PGT or PGTIOU) :param int lg: The length of the generated ticket (with the prefix) :return: A randomlly generated ticket of length ``lg`` :rtype: unicode
[ "Generate", "a", "ticket", "with", "prefix", "prefix", "and", "length", "lg" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L293-L310
21,949
nitmir/django-cas-server
cas_server/utils.py
crypt_salt_is_valid
def crypt_salt_is_valid(salt): """ Validate a salt as crypt salt :param str salt: a password salt :return: ``True`` if ``salt`` is a valid crypt salt on this system, ``False`` otherwise :rtype: bool """ if len(salt) < 2: return False else: if salt[0] == '$': if salt[1] == '$': return False else: if '$' not in salt[1:]: return False else: hashed = crypt.crypt("", salt) if not hashed or '$' not in hashed[1:]: return False else: return True else: return True
python
def crypt_salt_is_valid(salt): if len(salt) < 2: return False else: if salt[0] == '$': if salt[1] == '$': return False else: if '$' not in salt[1:]: return False else: hashed = crypt.crypt("", salt) if not hashed or '$' not in hashed[1:]: return False else: return True else: return True
[ "def", "crypt_salt_is_valid", "(", "salt", ")", ":", "if", "len", "(", "salt", ")", "<", "2", ":", "return", "False", "else", ":", "if", "salt", "[", "0", "]", "==", "'$'", ":", "if", "salt", "[", "1", "]", "==", "'$'", ":", "return", "False", ...
Validate a salt as crypt salt :param str salt: a password salt :return: ``True`` if ``salt`` is a valid crypt salt on this system, ``False`` otherwise :rtype: bool
[ "Validate", "a", "salt", "as", "crypt", "salt" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L393-L417
21,950
nitmir/django-cas-server
cas_server/utils.py
check_password
def check_password(method, password, hashed_password, charset): """ Check that ``password`` match `hashed_password` using ``method``, assuming the encoding is ``charset``. :param str method: on of ``"crypt"``, ``"ldap"``, ``"hex_md5"``, ``"hex_sha1"``, ``"hex_sha224"``, ``"hex_sha256"``, ``"hex_sha384"``, ``"hex_sha512"``, ``"plain"`` :param password: The user inputed password :type password: :obj:`str` or :obj:`unicode` :param hashed_password: The hashed password as stored in the database :type hashed_password: :obj:`str` or :obj:`unicode` :param str charset: The used char encoding (also used internally, so it must be valid for the charset used by ``password`` when it was initially ) :return: True if ``password`` match ``hashed_password`` using ``method``, ``False`` otherwise :rtype: bool """ if not isinstance(password, six.binary_type): password = password.encode(charset) if not isinstance(hashed_password, six.binary_type): hashed_password = hashed_password.encode(charset) if method == "plain": return password == hashed_password elif method == "crypt": if hashed_password.startswith(b'$'): salt = b'$'.join(hashed_password.split(b'$', 3)[:-1]) elif hashed_password.startswith(b'_'): # pragma: no cover old BSD format not supported salt = hashed_password[:9] else: salt = hashed_password[:2] if six.PY3: password = password.decode(charset) salt = salt.decode(charset) hashed_password = hashed_password.decode(charset) if not crypt_salt_is_valid(salt): raise ValueError("System crypt implementation do not support the salt %r" % salt) crypted_password = crypt.crypt(password, salt) return crypted_password == hashed_password elif method == "ldap": scheme = LdapHashUserPassword.get_scheme(hashed_password) salt = LdapHashUserPassword.get_salt(hashed_password) return LdapHashUserPassword.hash(scheme, password, salt, charset=charset) == hashed_password elif ( method.startswith("hex_") and method[4:] in {"md5", "sha1", "sha224", "sha256", "sha384", "sha512"} ): return getattr( hashlib, method[4:] )(password).hexdigest().encode("ascii") == hashed_password.lower() else: raise ValueError("Unknown password method check %r" % method)
python
def check_password(method, password, hashed_password, charset): if not isinstance(password, six.binary_type): password = password.encode(charset) if not isinstance(hashed_password, six.binary_type): hashed_password = hashed_password.encode(charset) if method == "plain": return password == hashed_password elif method == "crypt": if hashed_password.startswith(b'$'): salt = b'$'.join(hashed_password.split(b'$', 3)[:-1]) elif hashed_password.startswith(b'_'): # pragma: no cover old BSD format not supported salt = hashed_password[:9] else: salt = hashed_password[:2] if six.PY3: password = password.decode(charset) salt = salt.decode(charset) hashed_password = hashed_password.decode(charset) if not crypt_salt_is_valid(salt): raise ValueError("System crypt implementation do not support the salt %r" % salt) crypted_password = crypt.crypt(password, salt) return crypted_password == hashed_password elif method == "ldap": scheme = LdapHashUserPassword.get_scheme(hashed_password) salt = LdapHashUserPassword.get_salt(hashed_password) return LdapHashUserPassword.hash(scheme, password, salt, charset=charset) == hashed_password elif ( method.startswith("hex_") and method[4:] in {"md5", "sha1", "sha224", "sha256", "sha384", "sha512"} ): return getattr( hashlib, method[4:] )(password).hexdigest().encode("ascii") == hashed_password.lower() else: raise ValueError("Unknown password method check %r" % method)
[ "def", "check_password", "(", "method", ",", "password", ",", "hashed_password", ",", "charset", ")", ":", "if", "not", "isinstance", "(", "password", ",", "six", ".", "binary_type", ")", ":", "password", "=", "password", ".", "encode", "(", "charset", ")"...
Check that ``password`` match `hashed_password` using ``method``, assuming the encoding is ``charset``. :param str method: on of ``"crypt"``, ``"ldap"``, ``"hex_md5"``, ``"hex_sha1"``, ``"hex_sha224"``, ``"hex_sha256"``, ``"hex_sha384"``, ``"hex_sha512"``, ``"plain"`` :param password: The user inputed password :type password: :obj:`str` or :obj:`unicode` :param hashed_password: The hashed password as stored in the database :type hashed_password: :obj:`str` or :obj:`unicode` :param str charset: The used char encoding (also used internally, so it must be valid for the charset used by ``password`` when it was initially ) :return: True if ``password`` match ``hashed_password`` using ``method``, ``False`` otherwise :rtype: bool
[ "Check", "that", "password", "match", "hashed_password", "using", "method", "assuming", "the", "encoding", "is", "charset", "." ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L607-L658
21,951
nitmir/django-cas-server
cas_server/utils.py
last_version
def last_version(): """ Fetch the last version from pypi and return it. On successful fetch from pypi, the response is cached 24h, on error, it is cached 10 min. :return: the last django-cas-server version :rtype: unicode """ try: last_update, version, success = last_version._cache except AttributeError: last_update = 0 version = None success = False cache_delta = 24 * 3600 if success else 600 if (time.time() - last_update) < cache_delta: return version else: try: req = requests.get(settings.CAS_NEW_VERSION_JSON_URL) data = json.loads(req.text) version = data["info"]["version"] last_version._cache = (time.time(), version, True) return version except ( KeyError, ValueError, requests.exceptions.RequestException ) as error: # pragma: no cover (should not happen unless pypi is not available) logger.error( "Unable to fetch %s: %s" % (settings.CAS_NEW_VERSION_JSON_URL, error) ) last_version._cache = (time.time(), version, False)
python
def last_version(): try: last_update, version, success = last_version._cache except AttributeError: last_update = 0 version = None success = False cache_delta = 24 * 3600 if success else 600 if (time.time() - last_update) < cache_delta: return version else: try: req = requests.get(settings.CAS_NEW_VERSION_JSON_URL) data = json.loads(req.text) version = data["info"]["version"] last_version._cache = (time.time(), version, True) return version except ( KeyError, ValueError, requests.exceptions.RequestException ) as error: # pragma: no cover (should not happen unless pypi is not available) logger.error( "Unable to fetch %s: %s" % (settings.CAS_NEW_VERSION_JSON_URL, error) ) last_version._cache = (time.time(), version, False)
[ "def", "last_version", "(", ")", ":", "try", ":", "last_update", ",", "version", ",", "success", "=", "last_version", ".", "_cache", "except", "AttributeError", ":", "last_update", "=", "0", "version", "=", "None", "success", "=", "False", "cache_delta", "="...
Fetch the last version from pypi and return it. On successful fetch from pypi, the response is cached 24h, on error, it is cached 10 min. :return: the last django-cas-server version :rtype: unicode
[ "Fetch", "the", "last", "version", "from", "pypi", "and", "return", "it", ".", "On", "successful", "fetch", "from", "pypi", "the", "response", "is", "cached", "24h", "on", "error", "it", "is", "cached", "10", "min", "." ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L673-L705
21,952
nitmir/django-cas-server
cas_server/utils.py
regexpr_validator
def regexpr_validator(value): """ Test that ``value`` is a valid regular expression :param unicode value: A regular expression to test :raises ValidationError: if ``value`` is not a valid regular expression """ try: re.compile(value) except re.error: raise ValidationError( _('"%(value)s" is not a valid regular expression'), params={'value': value} )
python
def regexpr_validator(value): try: re.compile(value) except re.error: raise ValidationError( _('"%(value)s" is not a valid regular expression'), params={'value': value} )
[ "def", "regexpr_validator", "(", "value", ")", ":", "try", ":", "re", ".", "compile", "(", "value", ")", "except", "re", ".", "error", ":", "raise", "ValidationError", "(", "_", "(", "'\"%(value)s\" is not a valid regular expression'", ")", ",", "params", "=",...
Test that ``value`` is a valid regular expression :param unicode value: A regular expression to test :raises ValidationError: if ``value`` is not a valid regular expression
[ "Test", "that", "value", "is", "a", "valid", "regular", "expression" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L736-L749
21,953
nitmir/django-cas-server
cas_server/utils.py
LdapHashUserPassword.hash
def hash(cls, scheme, password, salt=None, charset="utf8"): """ Hash ``password`` with ``scheme`` using ``salt``. This three variable beeing encoded in ``charset``. :param bytes scheme: A valid scheme :param bytes password: A byte string to hash using ``scheme`` :param bytes salt: An optional salt to use if ``scheme`` requires any :param str charset: The encoding of ``scheme``, ``password`` and ``salt`` :return: The hashed password encoded with ``charset`` :rtype: bytes """ scheme = scheme.upper() cls._test_scheme(scheme) if salt is None or salt == b"": salt = b"" cls._test_scheme_nosalt(scheme) else: cls._test_scheme_salt(scheme) try: return scheme + base64.b64encode( cls._schemes_to_hash[scheme](password + salt).digest() + salt ) except KeyError: if six.PY3: password = password.decode(charset) salt = salt.decode(charset) if not crypt_salt_is_valid(salt): raise cls.BadSalt("System crypt implementation do not support the salt %r" % salt) hashed_password = crypt.crypt(password, salt) if six.PY3: hashed_password = hashed_password.encode(charset) return scheme + hashed_password
python
def hash(cls, scheme, password, salt=None, charset="utf8"): scheme = scheme.upper() cls._test_scheme(scheme) if salt is None or salt == b"": salt = b"" cls._test_scheme_nosalt(scheme) else: cls._test_scheme_salt(scheme) try: return scheme + base64.b64encode( cls._schemes_to_hash[scheme](password + salt).digest() + salt ) except KeyError: if six.PY3: password = password.decode(charset) salt = salt.decode(charset) if not crypt_salt_is_valid(salt): raise cls.BadSalt("System crypt implementation do not support the salt %r" % salt) hashed_password = crypt.crypt(password, salt) if six.PY3: hashed_password = hashed_password.encode(charset) return scheme + hashed_password
[ "def", "hash", "(", "cls", ",", "scheme", ",", "password", ",", "salt", "=", "None", ",", "charset", "=", "\"utf8\"", ")", ":", "scheme", "=", "scheme", ".", "upper", "(", ")", "cls", ".", "_test_scheme", "(", "scheme", ")", "if", "salt", "is", "No...
Hash ``password`` with ``scheme`` using ``salt``. This three variable beeing encoded in ``charset``. :param bytes scheme: A valid scheme :param bytes password: A byte string to hash using ``scheme`` :param bytes salt: An optional salt to use if ``scheme`` requires any :param str charset: The encoding of ``scheme``, ``password`` and ``salt`` :return: The hashed password encoded with ``charset`` :rtype: bytes
[ "Hash", "password", "with", "scheme", "using", "salt", ".", "This", "three", "variable", "beeing", "encoded", "in", "charset", "." ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L530-L562
21,954
nitmir/django-cas-server
cas_server/utils.py
LdapHashUserPassword.get_salt
def get_salt(cls, hashed_passord): """ Return the salt of ``hashed_passord`` possibly empty :param bytes hashed_passord: A hashed password :return: The salt used by the hashed password (empty if no salt is used) :rtype: bytes :raises BadHash: if no valid scheme is found within ``hashed_passord`` or if the hashed password is too short for the scheme found. """ scheme = cls.get_scheme(hashed_passord) cls._test_scheme(scheme) if scheme in cls.schemes_nosalt: return b"" elif scheme == b'{CRYPT}': return b'$'.join(hashed_passord.split(b'$', 3)[:-1])[len(scheme):] else: try: hashed_passord = base64.b64decode(hashed_passord[len(scheme):]) except (TypeError, binascii.Error) as error: raise cls.BadHash("Bad base64: %s" % error) if len(hashed_passord) < cls._schemes_to_len[scheme]: raise cls.BadHash("Hash too short for the scheme %s" % scheme) return hashed_passord[cls._schemes_to_len[scheme]:]
python
def get_salt(cls, hashed_passord): scheme = cls.get_scheme(hashed_passord) cls._test_scheme(scheme) if scheme in cls.schemes_nosalt: return b"" elif scheme == b'{CRYPT}': return b'$'.join(hashed_passord.split(b'$', 3)[:-1])[len(scheme):] else: try: hashed_passord = base64.b64decode(hashed_passord[len(scheme):]) except (TypeError, binascii.Error) as error: raise cls.BadHash("Bad base64: %s" % error) if len(hashed_passord) < cls._schemes_to_len[scheme]: raise cls.BadHash("Hash too short for the scheme %s" % scheme) return hashed_passord[cls._schemes_to_len[scheme]:]
[ "def", "get_salt", "(", "cls", ",", "hashed_passord", ")", ":", "scheme", "=", "cls", ".", "get_scheme", "(", "hashed_passord", ")", "cls", ".", "_test_scheme", "(", "scheme", ")", "if", "scheme", "in", "cls", ".", "schemes_nosalt", ":", "return", "b\"\"",...
Return the salt of ``hashed_passord`` possibly empty :param bytes hashed_passord: A hashed password :return: The salt used by the hashed password (empty if no salt is used) :rtype: bytes :raises BadHash: if no valid scheme is found within ``hashed_passord`` or if the hashed password is too short for the scheme found.
[ "Return", "the", "salt", "of", "hashed_passord", "possibly", "empty" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L581-L604
21,955
nitmir/django-cas-server
docs/_ext/djangodocs.py
visit_snippet_latex
def visit_snippet_latex(self, node): """ Latex document generator visit handler """ code = node.rawsource.rstrip('\n') lang = self.hlsettingstack[-1][0] linenos = code.count('\n') >= self.hlsettingstack[-1][1] - 1 fname = node['filename'] highlight_args = node.get('highlight_args', {}) if 'language' in node: # code-block directives lang = node['language'] highlight_args['force'] = True if 'linenos' in node: linenos = node['linenos'] def warner(msg): self.builder.warn(msg, (self.curfilestack[-1], node.line)) hlcode = self.highlighter.highlight_block(code, lang, warn=warner, linenos=linenos, **highlight_args) self.body.append( '\n{\\colorbox[rgb]{0.9,0.9,0.9}' '{\\makebox[\\textwidth][l]' '{\\small\\texttt{%s}}}}\n' % ( # Some filenames have '_', which is special in latex. fname.replace('_', r'\_'), ) ) if self.table: hlcode = hlcode.replace('\\begin{Verbatim}', '\\begin{OriginalVerbatim}') self.table.has_problematic = True self.table.has_verbatim = True hlcode = hlcode.rstrip()[:-14] # strip \end{Verbatim} hlcode = hlcode.rstrip() + '\n' self.body.append('\n' + hlcode + '\\end{%sVerbatim}\n' % (self.table and 'Original' or '')) # Prevent rawsource from appearing in output a second time. raise nodes.SkipNode
python
def visit_snippet_latex(self, node): code = node.rawsource.rstrip('\n') lang = self.hlsettingstack[-1][0] linenos = code.count('\n') >= self.hlsettingstack[-1][1] - 1 fname = node['filename'] highlight_args = node.get('highlight_args', {}) if 'language' in node: # code-block directives lang = node['language'] highlight_args['force'] = True if 'linenos' in node: linenos = node['linenos'] def warner(msg): self.builder.warn(msg, (self.curfilestack[-1], node.line)) hlcode = self.highlighter.highlight_block(code, lang, warn=warner, linenos=linenos, **highlight_args) self.body.append( '\n{\\colorbox[rgb]{0.9,0.9,0.9}' '{\\makebox[\\textwidth][l]' '{\\small\\texttt{%s}}}}\n' % ( # Some filenames have '_', which is special in latex. fname.replace('_', r'\_'), ) ) if self.table: hlcode = hlcode.replace('\\begin{Verbatim}', '\\begin{OriginalVerbatim}') self.table.has_problematic = True self.table.has_verbatim = True hlcode = hlcode.rstrip()[:-14] # strip \end{Verbatim} hlcode = hlcode.rstrip() + '\n' self.body.append('\n' + hlcode + '\\end{%sVerbatim}\n' % (self.table and 'Original' or '')) # Prevent rawsource from appearing in output a second time. raise nodes.SkipNode
[ "def", "visit_snippet_latex", "(", "self", ",", "node", ")", ":", "code", "=", "node", ".", "rawsource", ".", "rstrip", "(", "'\\n'", ")", "lang", "=", "self", ".", "hlsettingstack", "[", "-", "1", "]", "[", "0", "]", "linenos", "=", "code", ".", "...
Latex document generator visit handler
[ "Latex", "document", "generator", "visit", "handler" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/docs/_ext/djangodocs.py#L121-L166
21,956
nitmir/django-cas-server
cas_server/views.py
LogoutMixin.logout
def logout(self, all_session=False): """ effectively destroy a CAS session :param boolean all_session: If ``True`` destroy all the user sessions, otherwise destroy the current user session. :return: The number of destroyed sessions :rtype: int """ # initialize the counter of the number of destroyed sesisons session_nb = 0 # save the current user username before flushing the session username = self.request.session.get("username") if username: if all_session: logger.info("Logging out user %s from all sessions." % username) else: logger.info("Logging out user %s." % username) users = [] # try to get the user from the current session try: users.append( models.User.objects.get( username=username, session_key=self.request.session.session_key ) ) except models.User.DoesNotExist: # if user not found in database, flush the session anyway self.request.session.flush() # If all_session is set, search all of the user sessions if all_session: users.extend( models.User.objects.filter( username=username ).exclude( session_key=self.request.session.session_key ) ) # Iterate over all user sessions that have to be logged out for user in users: # get the user session session = SessionStore(session_key=user.session_key) # flush the session session.flush() # send SLO requests user.logout(self.request) # delete the user user.delete() # increment the destroyed session counter session_nb += 1 if username: logger.info("User %s logged out" % username) return session_nb
python
def logout(self, all_session=False): # initialize the counter of the number of destroyed sesisons session_nb = 0 # save the current user username before flushing the session username = self.request.session.get("username") if username: if all_session: logger.info("Logging out user %s from all sessions." % username) else: logger.info("Logging out user %s." % username) users = [] # try to get the user from the current session try: users.append( models.User.objects.get( username=username, session_key=self.request.session.session_key ) ) except models.User.DoesNotExist: # if user not found in database, flush the session anyway self.request.session.flush() # If all_session is set, search all of the user sessions if all_session: users.extend( models.User.objects.filter( username=username ).exclude( session_key=self.request.session.session_key ) ) # Iterate over all user sessions that have to be logged out for user in users: # get the user session session = SessionStore(session_key=user.session_key) # flush the session session.flush() # send SLO requests user.logout(self.request) # delete the user user.delete() # increment the destroyed session counter session_nb += 1 if username: logger.info("User %s logged out" % username) return session_nb
[ "def", "logout", "(", "self", ",", "all_session", "=", "False", ")", ":", "# initialize the counter of the number of destroyed sesisons", "session_nb", "=", "0", "# save the current user username before flushing the session", "username", "=", "self", ".", "request", ".", "s...
effectively destroy a CAS session :param boolean all_session: If ``True`` destroy all the user sessions, otherwise destroy the current user session. :return: The number of destroyed sessions :rtype: int
[ "effectively", "destroy", "a", "CAS", "session" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/views.py#L53-L108
21,957
nitmir/django-cas-server
cas_server/views.py
FederateAuth.get_cas_client
def get_cas_client(self, request, provider, renew=False): """ return a CAS client object matching provider :param django.http.HttpRequest request: The current request object :param cas_server.models.FederatedIendityProvider provider: the user identity provider :return: The user CAS client object :rtype: :class:`federate.CASFederateValidateUser <cas_server.federate.CASFederateValidateUser>` """ # compute the current url, ignoring ticket dans provider GET parameters service_url = utils.get_current_url(request, {"ticket", "provider"}) self.service_url = service_url return CASFederateValidateUser(provider, service_url, renew=renew)
python
def get_cas_client(self, request, provider, renew=False): # compute the current url, ignoring ticket dans provider GET parameters service_url = utils.get_current_url(request, {"ticket", "provider"}) self.service_url = service_url return CASFederateValidateUser(provider, service_url, renew=renew)
[ "def", "get_cas_client", "(", "self", ",", "request", ",", "provider", ",", "renew", "=", "False", ")", ":", "# compute the current url, ignoring ticket dans provider GET parameters", "service_url", "=", "utils", ".", "get_current_url", "(", "request", ",", "{", "\"ti...
return a CAS client object matching provider :param django.http.HttpRequest request: The current request object :param cas_server.models.FederatedIendityProvider provider: the user identity provider :return: The user CAS client object :rtype: :class:`federate.CASFederateValidateUser <cas_server.federate.CASFederateValidateUser>`
[ "return", "a", "CAS", "client", "object", "matching", "provider" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/views.py#L244-L257
21,958
nitmir/django-cas-server
cas_server/views.py
FederateAuth.post
def post(self, request, provider=None): """ method called on POST request :param django.http.HttpRequest request: The current request object :param unicode provider: Optional parameter. The user provider suffix. """ # if settings.CAS_FEDERATE is not True redirect to the login page if not settings.CAS_FEDERATE: logger.warning("CAS_FEDERATE is False, set it to True to use federation") return redirect("cas_server:login") # POST with a provider suffix, this is probably an SLO request. csrf is disabled for # allowing SLO requests reception try: provider = FederatedIendityProvider.objects.get(suffix=provider) auth = self.get_cas_client(request, provider) try: auth.clean_sessions(request.POST['logoutRequest']) except (KeyError, AttributeError): pass return HttpResponse("ok") # else, a User is trying to log in using an identity provider except FederatedIendityProvider.DoesNotExist: # Manually checking for csrf to protect the code below reason = CsrfViewMiddleware().process_view(request, None, (), {}) if reason is not None: # pragma: no cover (csrf checks are disabled during tests) return reason # Failed the test, stop here. form = forms.FederateSelect(request.POST) if form.is_valid(): params = utils.copy_params( request.POST, ignore={"provider", "csrfmiddlewaretoken", "ticket", "lt"} ) if params.get("renew") == "False": del params["renew"] url = utils.reverse_params( "cas_server:federateAuth", kwargs=dict(provider=form.cleaned_data["provider"].suffix), params=params ) return HttpResponseRedirect(url) else: return redirect("cas_server:login")
python
def post(self, request, provider=None): # if settings.CAS_FEDERATE is not True redirect to the login page if not settings.CAS_FEDERATE: logger.warning("CAS_FEDERATE is False, set it to True to use federation") return redirect("cas_server:login") # POST with a provider suffix, this is probably an SLO request. csrf is disabled for # allowing SLO requests reception try: provider = FederatedIendityProvider.objects.get(suffix=provider) auth = self.get_cas_client(request, provider) try: auth.clean_sessions(request.POST['logoutRequest']) except (KeyError, AttributeError): pass return HttpResponse("ok") # else, a User is trying to log in using an identity provider except FederatedIendityProvider.DoesNotExist: # Manually checking for csrf to protect the code below reason = CsrfViewMiddleware().process_view(request, None, (), {}) if reason is not None: # pragma: no cover (csrf checks are disabled during tests) return reason # Failed the test, stop here. form = forms.FederateSelect(request.POST) if form.is_valid(): params = utils.copy_params( request.POST, ignore={"provider", "csrfmiddlewaretoken", "ticket", "lt"} ) if params.get("renew") == "False": del params["renew"] url = utils.reverse_params( "cas_server:federateAuth", kwargs=dict(provider=form.cleaned_data["provider"].suffix), params=params ) return HttpResponseRedirect(url) else: return redirect("cas_server:login")
[ "def", "post", "(", "self", ",", "request", ",", "provider", "=", "None", ")", ":", "# if settings.CAS_FEDERATE is not True redirect to the login page", "if", "not", "settings", ".", "CAS_FEDERATE", ":", "logger", ".", "warning", "(", "\"CAS_FEDERATE is False, set it to...
method called on POST request :param django.http.HttpRequest request: The current request object :param unicode provider: Optional parameter. The user provider suffix.
[ "method", "called", "on", "POST", "request" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/views.py#L259-L301
21,959
nitmir/django-cas-server
cas_server/views.py
FederateAuth.get
def get(self, request, provider=None): """ method called on GET request :param django.http.HttpRequestself. request: The current request object :param unicode provider: Optional parameter. The user provider suffix. """ # if settings.CAS_FEDERATE is not True redirect to the login page if not settings.CAS_FEDERATE: logger.warning("CAS_FEDERATE is False, set it to True to use federation") return redirect("cas_server:login") renew = bool(request.GET.get('renew') and request.GET['renew'] != "False") # Is the user is already authenticated, no need to request authentication to the user # identity provider. if self.request.session.get("authenticated") and not renew: logger.warning("User already authenticated, dropping federated authentication request") return redirect("cas_server:login") try: # get the identity provider from its suffix provider = FederatedIendityProvider.objects.get(suffix=provider) # get a CAS client for the user identity provider auth = self.get_cas_client(request, provider, renew) # if no ticket submited, redirect to the identity provider CAS login page if 'ticket' not in request.GET: logger.info("Trying to authenticate %s again" % auth.provider.server_url) return HttpResponseRedirect(auth.get_login_url()) else: ticket = request.GET['ticket'] try: # if the ticket validation succeed if auth.verify_ticket(ticket): logger.info( "Got a valid ticket for %s from %s" % ( auth.username, auth.provider.server_url ) ) params = utils.copy_params(request.GET, ignore={"ticket", "remember"}) request.session["federate_username"] = auth.federated_username request.session["federate_ticket"] = ticket auth.register_slo( auth.federated_username, request.session.session_key, ticket ) # redirect to the the login page for the user to become authenticated # thanks to the `federate_username` and `federate_ticket` session parameters url = utils.reverse_params("cas_server:login", params) response = HttpResponseRedirect(url) # If the user has checked "remember my identity provider" store it in a # cookie if request.GET.get("remember"): max_age = settings.CAS_FEDERATE_REMEMBER_TIMEOUT utils.set_cookie( response, "remember_provider", provider.suffix, max_age ) return response # else redirect to the identity provider CAS login page else: logger.info( ( "Got an invalid ticket %s from %s for service %s. " "Retrying authentication" ) % ( ticket, auth.provider.server_url, self.service_url ) ) return HttpResponseRedirect(auth.get_login_url()) # both xml.etree.ElementTree and lxml.etree exceptions inherit from SyntaxError except SyntaxError as error: messages.add_message( request, messages.ERROR, _( u"Invalid response from your identity provider CAS upon " u"ticket %(ticket)s validation: %(error)r" ) % {'ticket': ticket, 'error': error} ) response = redirect("cas_server:login") response.delete_cookie("remember_provider") return response except FederatedIendityProvider.DoesNotExist: logger.warning("Identity provider suffix %s not found" % provider) # if the identity provider is not found, redirect to the login page return redirect("cas_server:login")
python
def get(self, request, provider=None): # if settings.CAS_FEDERATE is not True redirect to the login page if not settings.CAS_FEDERATE: logger.warning("CAS_FEDERATE is False, set it to True to use federation") return redirect("cas_server:login") renew = bool(request.GET.get('renew') and request.GET['renew'] != "False") # Is the user is already authenticated, no need to request authentication to the user # identity provider. if self.request.session.get("authenticated") and not renew: logger.warning("User already authenticated, dropping federated authentication request") return redirect("cas_server:login") try: # get the identity provider from its suffix provider = FederatedIendityProvider.objects.get(suffix=provider) # get a CAS client for the user identity provider auth = self.get_cas_client(request, provider, renew) # if no ticket submited, redirect to the identity provider CAS login page if 'ticket' not in request.GET: logger.info("Trying to authenticate %s again" % auth.provider.server_url) return HttpResponseRedirect(auth.get_login_url()) else: ticket = request.GET['ticket'] try: # if the ticket validation succeed if auth.verify_ticket(ticket): logger.info( "Got a valid ticket for %s from %s" % ( auth.username, auth.provider.server_url ) ) params = utils.copy_params(request.GET, ignore={"ticket", "remember"}) request.session["federate_username"] = auth.federated_username request.session["federate_ticket"] = ticket auth.register_slo( auth.federated_username, request.session.session_key, ticket ) # redirect to the the login page for the user to become authenticated # thanks to the `federate_username` and `federate_ticket` session parameters url = utils.reverse_params("cas_server:login", params) response = HttpResponseRedirect(url) # If the user has checked "remember my identity provider" store it in a # cookie if request.GET.get("remember"): max_age = settings.CAS_FEDERATE_REMEMBER_TIMEOUT utils.set_cookie( response, "remember_provider", provider.suffix, max_age ) return response # else redirect to the identity provider CAS login page else: logger.info( ( "Got an invalid ticket %s from %s for service %s. " "Retrying authentication" ) % ( ticket, auth.provider.server_url, self.service_url ) ) return HttpResponseRedirect(auth.get_login_url()) # both xml.etree.ElementTree and lxml.etree exceptions inherit from SyntaxError except SyntaxError as error: messages.add_message( request, messages.ERROR, _( u"Invalid response from your identity provider CAS upon " u"ticket %(ticket)s validation: %(error)r" ) % {'ticket': ticket, 'error': error} ) response = redirect("cas_server:login") response.delete_cookie("remember_provider") return response except FederatedIendityProvider.DoesNotExist: logger.warning("Identity provider suffix %s not found" % provider) # if the identity provider is not found, redirect to the login page return redirect("cas_server:login")
[ "def", "get", "(", "self", ",", "request", ",", "provider", "=", "None", ")", ":", "# if settings.CAS_FEDERATE is not True redirect to the login page", "if", "not", "settings", ".", "CAS_FEDERATE", ":", "logger", ".", "warning", "(", "\"CAS_FEDERATE is False, set it to ...
method called on GET request :param django.http.HttpRequestself. request: The current request object :param unicode provider: Optional parameter. The user provider suffix.
[ "method", "called", "on", "GET", "request" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/views.py#L303-L392
21,960
nitmir/django-cas-server
cas_server/views.py
LoginView.init_post
def init_post(self, request): """ Initialize POST received parameters :param django.http.HttpRequest request: The current request object """ self.request = request self.service = request.POST.get('service') self.renew = bool(request.POST.get('renew') and request.POST['renew'] != "False") self.gateway = request.POST.get('gateway') self.method = request.POST.get('method') self.ajax = settings.CAS_ENABLE_AJAX_AUTH and 'HTTP_X_AJAX' in request.META if request.POST.get('warned') and request.POST['warned'] != "False": self.warned = True self.warn = request.POST.get('warn') if settings.CAS_FEDERATE: self.username = request.POST.get('username') # in federated mode, the valdated indentity provider CAS ticket is used as password self.ticket = request.POST.get('password')
python
def init_post(self, request): self.request = request self.service = request.POST.get('service') self.renew = bool(request.POST.get('renew') and request.POST['renew'] != "False") self.gateway = request.POST.get('gateway') self.method = request.POST.get('method') self.ajax = settings.CAS_ENABLE_AJAX_AUTH and 'HTTP_X_AJAX' in request.META if request.POST.get('warned') and request.POST['warned'] != "False": self.warned = True self.warn = request.POST.get('warn') if settings.CAS_FEDERATE: self.username = request.POST.get('username') # in federated mode, the valdated indentity provider CAS ticket is used as password self.ticket = request.POST.get('password')
[ "def", "init_post", "(", "self", ",", "request", ")", ":", "self", ".", "request", "=", "request", "self", ".", "service", "=", "request", ".", "POST", ".", "get", "(", "'service'", ")", "self", ".", "renew", "=", "bool", "(", "request", ".", "POST",...
Initialize POST received parameters :param django.http.HttpRequest request: The current request object
[ "Initialize", "POST", "received", "parameters" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/views.py#L442-L460
21,961
nitmir/django-cas-server
cas_server/views.py
LoginView.gen_lt
def gen_lt(self): """Generate a new LoginTicket and add it to the list of valid LT for the user""" self.request.session['lt'] = self.request.session.get('lt', []) + [utils.gen_lt()] if len(self.request.session['lt']) > 100: self.request.session['lt'] = self.request.session['lt'][-100:]
python
def gen_lt(self): self.request.session['lt'] = self.request.session.get('lt', []) + [utils.gen_lt()] if len(self.request.session['lt']) > 100: self.request.session['lt'] = self.request.session['lt'][-100:]
[ "def", "gen_lt", "(", "self", ")", ":", "self", ".", "request", ".", "session", "[", "'lt'", "]", "=", "self", ".", "request", ".", "session", ".", "get", "(", "'lt'", ",", "[", "]", ")", "+", "[", "utils", ".", "gen_lt", "(", ")", "]", "if", ...
Generate a new LoginTicket and add it to the list of valid LT for the user
[ "Generate", "a", "new", "LoginTicket", "and", "add", "it", "to", "the", "list", "of", "valid", "LT", "for", "the", "user" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/views.py#L462-L466
21,962
nitmir/django-cas-server
cas_server/views.py
LoginView.check_lt
def check_lt(self): """ Check is the POSTed LoginTicket is valid, if yes invalide it :return: ``True`` if the LoginTicket is valid, ``False`` otherwise :rtype: bool """ # save LT for later check lt_valid = self.request.session.get('lt', []) lt_send = self.request.POST.get('lt') # generate a new LT (by posting the LT has been consumed) self.gen_lt() # check if send LT is valid if lt_send not in lt_valid: return False else: self.request.session['lt'].remove(lt_send) # we need to redo the affectation for django to detect that the list has changed # and for its new value to be store in the session self.request.session['lt'] = self.request.session['lt'] return True
python
def check_lt(self): # save LT for later check lt_valid = self.request.session.get('lt', []) lt_send = self.request.POST.get('lt') # generate a new LT (by posting the LT has been consumed) self.gen_lt() # check if send LT is valid if lt_send not in lt_valid: return False else: self.request.session['lt'].remove(lt_send) # we need to redo the affectation for django to detect that the list has changed # and for its new value to be store in the session self.request.session['lt'] = self.request.session['lt'] return True
[ "def", "check_lt", "(", "self", ")", ":", "# save LT for later check", "lt_valid", "=", "self", ".", "request", ".", "session", ".", "get", "(", "'lt'", ",", "[", "]", ")", "lt_send", "=", "self", ".", "request", ".", "POST", ".", "get", "(", "'lt'", ...
Check is the POSTed LoginTicket is valid, if yes invalide it :return: ``True`` if the LoginTicket is valid, ``False`` otherwise :rtype: bool
[ "Check", "is", "the", "POSTed", "LoginTicket", "is", "valid", "if", "yes", "invalide", "it" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/views.py#L468-L488
21,963
nitmir/django-cas-server
cas_server/views.py
LoginView.init_get
def init_get(self, request): """ Initialize GET received parameters :param django.http.HttpRequest request: The current request object """ self.request = request self.service = request.GET.get('service') self.renew = bool(request.GET.get('renew') and request.GET['renew'] != "False") self.gateway = request.GET.get('gateway') self.method = request.GET.get('method') self.ajax = settings.CAS_ENABLE_AJAX_AUTH and 'HTTP_X_AJAX' in request.META self.warn = request.GET.get('warn') if settings.CAS_FEDERATE: # here username and ticket are fetch from the session after a redirection from # FederateAuth.get self.username = request.session.get("federate_username") self.ticket = request.session.get("federate_ticket") if self.username: del request.session["federate_username"] if self.ticket: del request.session["federate_ticket"]
python
def init_get(self, request): self.request = request self.service = request.GET.get('service') self.renew = bool(request.GET.get('renew') and request.GET['renew'] != "False") self.gateway = request.GET.get('gateway') self.method = request.GET.get('method') self.ajax = settings.CAS_ENABLE_AJAX_AUTH and 'HTTP_X_AJAX' in request.META self.warn = request.GET.get('warn') if settings.CAS_FEDERATE: # here username and ticket are fetch from the session after a redirection from # FederateAuth.get self.username = request.session.get("federate_username") self.ticket = request.session.get("federate_ticket") if self.username: del request.session["federate_username"] if self.ticket: del request.session["federate_ticket"]
[ "def", "init_get", "(", "self", ",", "request", ")", ":", "self", ".", "request", "=", "request", "self", ".", "service", "=", "request", ".", "GET", ".", "get", "(", "'service'", ")", "self", ".", "renew", "=", "bool", "(", "request", ".", "GET", ...
Initialize GET received parameters :param django.http.HttpRequest request: The current request object
[ "Initialize", "GET", "received", "parameters" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/views.py#L583-L604
21,964
nitmir/django-cas-server
cas_server/views.py
LoginView.process_get
def process_get(self): """ Analyse the GET request :return: * :attr:`USER_NOT_AUTHENTICATED` if the user is not authenticated or is requesting for authentication renewal * :attr:`USER_AUTHENTICATED` if the user is authenticated and is not requesting for authentication renewal :rtype: int """ # generate a new LT self.gen_lt() if not self.request.session.get("authenticated") or self.renew: # authentication will be needed, initialize the form to use self.init_form() return self.USER_NOT_AUTHENTICATED return self.USER_AUTHENTICATED
python
def process_get(self): # generate a new LT self.gen_lt() if not self.request.session.get("authenticated") or self.renew: # authentication will be needed, initialize the form to use self.init_form() return self.USER_NOT_AUTHENTICATED return self.USER_AUTHENTICATED
[ "def", "process_get", "(", "self", ")", ":", "# generate a new LT", "self", ".", "gen_lt", "(", ")", "if", "not", "self", ".", "request", ".", "session", ".", "get", "(", "\"authenticated\"", ")", "or", "self", ".", "renew", ":", "# authentication will be ne...
Analyse the GET request :return: * :attr:`USER_NOT_AUTHENTICATED` if the user is not authenticated or is requesting for authentication renewal * :attr:`USER_AUTHENTICATED` if the user is authenticated and is not requesting for authentication renewal :rtype: int
[ "Analyse", "the", "GET", "request" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/views.py#L619-L636
21,965
nitmir/django-cas-server
cas_server/views.py
LoginView.init_form
def init_form(self, values=None): """ Initialization of the good form depending of POST and GET parameters :param django.http.QueryDict values: A POST or GET QueryDict """ if values: values = values.copy() values['lt'] = self.request.session['lt'][-1] form_initial = { 'service': self.service, 'method': self.method, 'warn': ( self.warn or self.request.session.get("warn") or self.request.COOKIES.get('warn') ), 'lt': self.request.session['lt'][-1], 'renew': self.renew } if settings.CAS_FEDERATE: if self.username and self.ticket: form_initial['username'] = self.username form_initial['password'] = self.ticket form_initial['ticket'] = self.ticket self.form = forms.FederateUserCredential( values, initial=form_initial ) else: self.form = forms.FederateSelect(values, initial=form_initial) else: self.form = forms.UserCredential( values, initial=form_initial )
python
def init_form(self, values=None): if values: values = values.copy() values['lt'] = self.request.session['lt'][-1] form_initial = { 'service': self.service, 'method': self.method, 'warn': ( self.warn or self.request.session.get("warn") or self.request.COOKIES.get('warn') ), 'lt': self.request.session['lt'][-1], 'renew': self.renew } if settings.CAS_FEDERATE: if self.username and self.ticket: form_initial['username'] = self.username form_initial['password'] = self.ticket form_initial['ticket'] = self.ticket self.form = forms.FederateUserCredential( values, initial=form_initial ) else: self.form = forms.FederateSelect(values, initial=form_initial) else: self.form = forms.UserCredential( values, initial=form_initial )
[ "def", "init_form", "(", "self", ",", "values", "=", "None", ")", ":", "if", "values", ":", "values", "=", "values", ".", "copy", "(", ")", "values", "[", "'lt'", "]", "=", "self", ".", "request", ".", "session", "[", "'lt'", "]", "[", "-", "1", ...
Initialization of the good form depending of POST and GET parameters :param django.http.QueryDict values: A POST or GET QueryDict
[ "Initialization", "of", "the", "good", "form", "depending", "of", "POST", "and", "GET", "parameters" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/views.py#L638-L671
21,966
nitmir/django-cas-server
cas_server/views.py
LoginView.service_login
def service_login(self): """ Perform login against a service :return: * The rendering of the ``settings.CAS_WARN_TEMPLATE`` if the user asked to be warned before ticket emission and has not yep been warned. * The redirection to the service URL with a ticket GET parameter * The redirection to the service URL without a ticket if ticket generation failed and the :attr:`gateway` attribute is set * The rendering of the ``settings.CAS_LOGGED_TEMPLATE`` template with some error messages if the ticket generation failed (e.g: user not allowed). :rtype: django.http.HttpResponse """ try: # is the service allowed service_pattern = ServicePattern.validate(self.service) # is the current user allowed on this service service_pattern.check_user(self.user) # if the user has asked to be warned before any login to a service if self.request.session.get("warn", True) and not self.warned: messages.add_message( self.request, messages.WARNING, _(u"Authentication has been required by service %(name)s (%(url)s)") % {'name': service_pattern.name, 'url': self.service} ) if self.ajax: data = {"status": "error", "detail": "confirmation needed"} return json_response(self.request, data) else: warn_form = forms.WarnForm(initial={ 'service': self.service, 'renew': self.renew, 'gateway': self.gateway, 'method': self.method, 'warned': True, 'lt': self.request.session['lt'][-1] }) return render( self.request, settings.CAS_WARN_TEMPLATE, utils.context({'form': warn_form}) ) else: # redirect, using method ? list(messages.get_messages(self.request)) # clean messages before leaving django redirect_url = self.user.get_service_url( self.service, service_pattern, renew=self.renewed ) if not self.ajax: return HttpResponseRedirect(redirect_url) else: data = {"status": "success", "detail": "auth", "url": redirect_url} return json_response(self.request, data) except ServicePattern.DoesNotExist: error = 1 messages.add_message( self.request, messages.ERROR, _(u'Service %(url)s not allowed.') % {'url': self.service} ) except models.BadUsername: error = 2 messages.add_message( self.request, messages.ERROR, _(u"Username not allowed") ) except models.BadFilter: error = 3 messages.add_message( self.request, messages.ERROR, _(u"User characteristics not allowed") ) except models.UserFieldNotDefined: error = 4 messages.add_message( self.request, messages.ERROR, _(u"The attribute %(field)s is needed to use" u" that service") % {'field': service_pattern.user_field} ) # if gateway is set and auth failed redirect to the service without authentication if self.gateway and not self.ajax: list(messages.get_messages(self.request)) # clean messages before leaving django return HttpResponseRedirect(self.service) if not self.ajax: return render( self.request, settings.CAS_LOGGED_TEMPLATE, utils.context({'session': self.request.session}) ) else: data = {"status": "error", "detail": "auth", "code": error} return json_response(self.request, data)
python
def service_login(self): try: # is the service allowed service_pattern = ServicePattern.validate(self.service) # is the current user allowed on this service service_pattern.check_user(self.user) # if the user has asked to be warned before any login to a service if self.request.session.get("warn", True) and not self.warned: messages.add_message( self.request, messages.WARNING, _(u"Authentication has been required by service %(name)s (%(url)s)") % {'name': service_pattern.name, 'url': self.service} ) if self.ajax: data = {"status": "error", "detail": "confirmation needed"} return json_response(self.request, data) else: warn_form = forms.WarnForm(initial={ 'service': self.service, 'renew': self.renew, 'gateway': self.gateway, 'method': self.method, 'warned': True, 'lt': self.request.session['lt'][-1] }) return render( self.request, settings.CAS_WARN_TEMPLATE, utils.context({'form': warn_form}) ) else: # redirect, using method ? list(messages.get_messages(self.request)) # clean messages before leaving django redirect_url = self.user.get_service_url( self.service, service_pattern, renew=self.renewed ) if not self.ajax: return HttpResponseRedirect(redirect_url) else: data = {"status": "success", "detail": "auth", "url": redirect_url} return json_response(self.request, data) except ServicePattern.DoesNotExist: error = 1 messages.add_message( self.request, messages.ERROR, _(u'Service %(url)s not allowed.') % {'url': self.service} ) except models.BadUsername: error = 2 messages.add_message( self.request, messages.ERROR, _(u"Username not allowed") ) except models.BadFilter: error = 3 messages.add_message( self.request, messages.ERROR, _(u"User characteristics not allowed") ) except models.UserFieldNotDefined: error = 4 messages.add_message( self.request, messages.ERROR, _(u"The attribute %(field)s is needed to use" u" that service") % {'field': service_pattern.user_field} ) # if gateway is set and auth failed redirect to the service without authentication if self.gateway and not self.ajax: list(messages.get_messages(self.request)) # clean messages before leaving django return HttpResponseRedirect(self.service) if not self.ajax: return render( self.request, settings.CAS_LOGGED_TEMPLATE, utils.context({'session': self.request.session}) ) else: data = {"status": "error", "detail": "auth", "code": error} return json_response(self.request, data)
[ "def", "service_login", "(", "self", ")", ":", "try", ":", "# is the service allowed", "service_pattern", "=", "ServicePattern", ".", "validate", "(", "self", ".", "service", ")", "# is the current user allowed on this service", "service_pattern", ".", "check_user", "("...
Perform login against a service :return: * The rendering of the ``settings.CAS_WARN_TEMPLATE`` if the user asked to be warned before ticket emission and has not yep been warned. * The redirection to the service URL with a ticket GET parameter * The redirection to the service URL without a ticket if ticket generation failed and the :attr:`gateway` attribute is set * The rendering of the ``settings.CAS_LOGGED_TEMPLATE`` template with some error messages if the ticket generation failed (e.g: user not allowed). :rtype: django.http.HttpResponse
[ "Perform", "login", "against", "a", "service" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/views.py#L673-L773
21,967
nitmir/django-cas-server
cas_server/views.py
LoginView.authenticated
def authenticated(self): """ Processing authenticated users :return: * The returned value of :meth:`service_login` if :attr:`service` is defined * The rendering of ``settings.CAS_LOGGED_TEMPLATE`` otherwise :rtype: django.http.HttpResponse """ # Try to get the current :class:`models.User<cas_server.models.User>` object for the current # session try: self.user = models.User.objects.get( username=self.request.session.get("username"), session_key=self.request.session.session_key ) # if not found, flush the session and redirect to the login page except models.User.DoesNotExist: logger.warning( "User %s seems authenticated but is not found in the database." % ( self.request.session.get("username"), ) ) self.logout() if self.ajax: data = { "status": "error", "detail": "login required", "url": utils.reverse_params("cas_server:login", params=self.request.GET) } return json_response(self.request, data) else: return utils.redirect_params("cas_server:login", params=self.request.GET) # if login against a service if self.service: return self.service_login() # else display the logged template else: if self.ajax: data = {"status": "success", "detail": "logged"} return json_response(self.request, data) else: return render( self.request, settings.CAS_LOGGED_TEMPLATE, utils.context({'session': self.request.session}) )
python
def authenticated(self): # Try to get the current :class:`models.User<cas_server.models.User>` object for the current # session try: self.user = models.User.objects.get( username=self.request.session.get("username"), session_key=self.request.session.session_key ) # if not found, flush the session and redirect to the login page except models.User.DoesNotExist: logger.warning( "User %s seems authenticated but is not found in the database." % ( self.request.session.get("username"), ) ) self.logout() if self.ajax: data = { "status": "error", "detail": "login required", "url": utils.reverse_params("cas_server:login", params=self.request.GET) } return json_response(self.request, data) else: return utils.redirect_params("cas_server:login", params=self.request.GET) # if login against a service if self.service: return self.service_login() # else display the logged template else: if self.ajax: data = {"status": "success", "detail": "logged"} return json_response(self.request, data) else: return render( self.request, settings.CAS_LOGGED_TEMPLATE, utils.context({'session': self.request.session}) )
[ "def", "authenticated", "(", "self", ")", ":", "# Try to get the current :class:`models.User<cas_server.models.User>` object for the current", "# session", "try", ":", "self", ".", "user", "=", "models", ".", "User", ".", "objects", ".", "get", "(", "username", "=", "...
Processing authenticated users :return: * The returned value of :meth:`service_login` if :attr:`service` is defined * The rendering of ``settings.CAS_LOGGED_TEMPLATE`` otherwise :rtype: django.http.HttpResponse
[ "Processing", "authenticated", "users" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/views.py#L775-L822
21,968
nitmir/django-cas-server
cas_server/views.py
LoginView.not_authenticated
def not_authenticated(self): """ Processing non authenticated users :return: * The rendering of ``settings.CAS_LOGIN_TEMPLATE`` with various messages depending of GET/POST parameters * The redirection to :class:`FederateAuth` if ``settings.CAS_FEDERATE`` is ``True`` and the "remember my identity provider" cookie is found :rtype: django.http.HttpResponse """ if self.service: try: service_pattern = ServicePattern.validate(self.service) if self.gateway and not self.ajax: # clean messages before leaving django list(messages.get_messages(self.request)) return HttpResponseRedirect(self.service) if settings.CAS_SHOW_SERVICE_MESSAGES: if self.request.session.get("authenticated") and self.renew: messages.add_message( self.request, messages.WARNING, _(u"Authentication renewal required by service %(name)s (%(url)s).") % {'name': service_pattern.name, 'url': self.service} ) else: messages.add_message( self.request, messages.WARNING, _(u"Authentication required by service %(name)s (%(url)s).") % {'name': service_pattern.name, 'url': self.service} ) except ServicePattern.DoesNotExist: if settings.CAS_SHOW_SERVICE_MESSAGES: messages.add_message( self.request, messages.ERROR, _(u'Service %s not allowed') % self.service ) if self.ajax: data = { "status": "error", "detail": "login required", "url": utils.reverse_params("cas_server:login", params=self.request.GET) } return json_response(self.request, data) else: if settings.CAS_FEDERATE: if self.username and self.ticket: return render( self.request, settings.CAS_LOGIN_TEMPLATE, utils.context({ 'form': self.form, 'auto_submit': True, 'post_url': reverse("cas_server:login") }) ) else: if ( self.request.COOKIES.get('remember_provider') and FederatedIendityProvider.objects.filter( suffix=self.request.COOKIES['remember_provider'] ) ): params = utils.copy_params(self.request.GET) url = utils.reverse_params( "cas_server:federateAuth", params=params, kwargs=dict(provider=self.request.COOKIES['remember_provider']) ) return HttpResponseRedirect(url) else: # if user is authenticated and auth renewal is requested, redirect directly # to the user identity provider if self.renew and self.request.session.get("authenticated"): try: user = FederatedUser.get_from_federated_username( self.request.session.get("username") ) params = utils.copy_params(self.request.GET) url = utils.reverse_params( "cas_server:federateAuth", params=params, kwargs=dict(provider=user.provider.suffix) ) return HttpResponseRedirect(url) # Should normally not happen: if the user is logged, it exists in the # database. except FederatedUser.DoesNotExist: # pragma: no cover pass return render( self.request, settings.CAS_LOGIN_TEMPLATE, utils.context({ 'form': self.form, 'post_url': reverse("cas_server:federateAuth") }) ) else: return render( self.request, settings.CAS_LOGIN_TEMPLATE, utils.context({'form': self.form}) )
python
def not_authenticated(self): if self.service: try: service_pattern = ServicePattern.validate(self.service) if self.gateway and not self.ajax: # clean messages before leaving django list(messages.get_messages(self.request)) return HttpResponseRedirect(self.service) if settings.CAS_SHOW_SERVICE_MESSAGES: if self.request.session.get("authenticated") and self.renew: messages.add_message( self.request, messages.WARNING, _(u"Authentication renewal required by service %(name)s (%(url)s).") % {'name': service_pattern.name, 'url': self.service} ) else: messages.add_message( self.request, messages.WARNING, _(u"Authentication required by service %(name)s (%(url)s).") % {'name': service_pattern.name, 'url': self.service} ) except ServicePattern.DoesNotExist: if settings.CAS_SHOW_SERVICE_MESSAGES: messages.add_message( self.request, messages.ERROR, _(u'Service %s not allowed') % self.service ) if self.ajax: data = { "status": "error", "detail": "login required", "url": utils.reverse_params("cas_server:login", params=self.request.GET) } return json_response(self.request, data) else: if settings.CAS_FEDERATE: if self.username and self.ticket: return render( self.request, settings.CAS_LOGIN_TEMPLATE, utils.context({ 'form': self.form, 'auto_submit': True, 'post_url': reverse("cas_server:login") }) ) else: if ( self.request.COOKIES.get('remember_provider') and FederatedIendityProvider.objects.filter( suffix=self.request.COOKIES['remember_provider'] ) ): params = utils.copy_params(self.request.GET) url = utils.reverse_params( "cas_server:federateAuth", params=params, kwargs=dict(provider=self.request.COOKIES['remember_provider']) ) return HttpResponseRedirect(url) else: # if user is authenticated and auth renewal is requested, redirect directly # to the user identity provider if self.renew and self.request.session.get("authenticated"): try: user = FederatedUser.get_from_federated_username( self.request.session.get("username") ) params = utils.copy_params(self.request.GET) url = utils.reverse_params( "cas_server:federateAuth", params=params, kwargs=dict(provider=user.provider.suffix) ) return HttpResponseRedirect(url) # Should normally not happen: if the user is logged, it exists in the # database. except FederatedUser.DoesNotExist: # pragma: no cover pass return render( self.request, settings.CAS_LOGIN_TEMPLATE, utils.context({ 'form': self.form, 'post_url': reverse("cas_server:federateAuth") }) ) else: return render( self.request, settings.CAS_LOGIN_TEMPLATE, utils.context({'form': self.form}) )
[ "def", "not_authenticated", "(", "self", ")", ":", "if", "self", ".", "service", ":", "try", ":", "service_pattern", "=", "ServicePattern", ".", "validate", "(", "self", ".", "service", ")", "if", "self", ".", "gateway", "and", "not", "self", ".", "ajax"...
Processing non authenticated users :return: * The rendering of ``settings.CAS_LOGIN_TEMPLATE`` with various messages depending of GET/POST parameters * The redirection to :class:`FederateAuth` if ``settings.CAS_FEDERATE`` is ``True`` and the "remember my identity provider" cookie is found :rtype: django.http.HttpResponse
[ "Processing", "non", "authenticated", "users" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/views.py#L824-L930
21,969
nitmir/django-cas-server
cas_server/views.py
LoginView.common
def common(self): """ Common part execute uppon GET and POST request :return: * The returned value of :meth:`authenticated` if the user is authenticated and not requesting for authentication or if the authentication has just been renewed * The returned value of :meth:`not_authenticated` otherwise :rtype: django.http.HttpResponse """ # if authenticated and successfully renewed authentication if needed if self.request.session.get("authenticated") and (not self.renew or self.renewed): return self.authenticated() else: return self.not_authenticated()
python
def common(self): # if authenticated and successfully renewed authentication if needed if self.request.session.get("authenticated") and (not self.renew or self.renewed): return self.authenticated() else: return self.not_authenticated()
[ "def", "common", "(", "self", ")", ":", "# if authenticated and successfully renewed authentication if needed", "if", "self", ".", "request", ".", "session", ".", "get", "(", "\"authenticated\"", ")", "and", "(", "not", "self", ".", "renew", "or", "self", ".", "...
Common part execute uppon GET and POST request :return: * The returned value of :meth:`authenticated` if the user is authenticated and not requesting for authentication or if the authentication has just been renewed * The returned value of :meth:`not_authenticated` otherwise :rtype: django.http.HttpResponse
[ "Common", "part", "execute", "uppon", "GET", "and", "POST", "request" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/views.py#L932-L946
21,970
nitmir/django-cas-server
cas_server/views.py
ValidateService.process_ticket
def process_ticket(self): """ fetch the ticket against the database and check its validity :raises ValidateError: if the ticket is not found or not valid, potentially for that service :returns: A couple (ticket, proxies list) :rtype: :obj:`tuple` """ try: proxies = [] if self.allow_proxy_ticket: ticket = models.Ticket.get(self.ticket, self.renew) else: ticket = models.ServiceTicket.get(self.ticket, self.renew) try: for prox in ticket.proxies.all(): proxies.append(prox.url) except AttributeError: pass if ticket.service != self.service: raise ValidateError(u'INVALID_SERVICE', self.service) return ticket, proxies except Ticket.DoesNotExist: raise ValidateError(u'INVALID_TICKET', self.ticket) except (ServiceTicket.DoesNotExist, ProxyTicket.DoesNotExist): raise ValidateError(u'INVALID_TICKET', 'ticket not found')
python
def process_ticket(self): try: proxies = [] if self.allow_proxy_ticket: ticket = models.Ticket.get(self.ticket, self.renew) else: ticket = models.ServiceTicket.get(self.ticket, self.renew) try: for prox in ticket.proxies.all(): proxies.append(prox.url) except AttributeError: pass if ticket.service != self.service: raise ValidateError(u'INVALID_SERVICE', self.service) return ticket, proxies except Ticket.DoesNotExist: raise ValidateError(u'INVALID_TICKET', self.ticket) except (ServiceTicket.DoesNotExist, ProxyTicket.DoesNotExist): raise ValidateError(u'INVALID_TICKET', 'ticket not found')
[ "def", "process_ticket", "(", "self", ")", ":", "try", ":", "proxies", "=", "[", "]", "if", "self", ".", "allow_proxy_ticket", ":", "ticket", "=", "models", ".", "Ticket", ".", "get", "(", "self", ".", "ticket", ",", "self", ".", "renew", ")", "else"...
fetch the ticket against the database and check its validity :raises ValidateError: if the ticket is not found or not valid, potentially for that service :returns: A couple (ticket, proxies list) :rtype: :obj:`tuple`
[ "fetch", "the", "ticket", "against", "the", "database", "and", "check", "its", "validity" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/views.py#L1191-L1217
21,971
nitmir/django-cas-server
cas_server/views.py
ValidateService.process_pgturl
def process_pgturl(self, params): """ Handle PGT request :param dict params: A template context dict :raises ValidateError: if pgtUrl is invalid or if TLS validation of the pgtUrl fails :return: The rendering of ``cas_server/serviceValidate.xml``, using ``params`` :rtype: django.http.HttpResponse """ try: pattern = ServicePattern.validate(self.pgt_url) if pattern.proxy_callback: proxyid = utils.gen_pgtiou() pticket = ProxyGrantingTicket.objects.create( user=self.ticket.user, service=self.pgt_url, service_pattern=pattern, single_log_out=pattern.single_log_out ) url = utils.update_url(self.pgt_url, {'pgtIou': proxyid, 'pgtId': pticket.value}) try: ret = requests.get(url, verify=settings.CAS_PROXY_CA_CERTIFICATE_PATH) if ret.status_code == 200: params['proxyGrantingTicket'] = proxyid else: pticket.delete() logger.info( ( "ValidateService: ticket %s validated for user %s on service %s. " "Proxy Granting Ticket transmited to %s." ) % ( self.ticket.value, self.ticket.user.username, self.ticket.service, self.pgt_url ) ) logger.debug( "ValidateService: User attributs are:\n%s" % ( pprint.pformat(self.ticket.attributs), ) ) return render( self.request, "cas_server/serviceValidate.xml", params, content_type="text/xml; charset=utf-8" ) except requests.exceptions.RequestException as error: error = utils.unpack_nested_exception(error) raise ValidateError( u'INVALID_PROXY_CALLBACK', u"%s: %s" % (type(error), str(error)) ) else: raise ValidateError( u'INVALID_PROXY_CALLBACK', u"callback url not allowed by configuration" ) except ServicePattern.DoesNotExist: raise ValidateError( u'INVALID_PROXY_CALLBACK', u'callback url not allowed by configuration' )
python
def process_pgturl(self, params): try: pattern = ServicePattern.validate(self.pgt_url) if pattern.proxy_callback: proxyid = utils.gen_pgtiou() pticket = ProxyGrantingTicket.objects.create( user=self.ticket.user, service=self.pgt_url, service_pattern=pattern, single_log_out=pattern.single_log_out ) url = utils.update_url(self.pgt_url, {'pgtIou': proxyid, 'pgtId': pticket.value}) try: ret = requests.get(url, verify=settings.CAS_PROXY_CA_CERTIFICATE_PATH) if ret.status_code == 200: params['proxyGrantingTicket'] = proxyid else: pticket.delete() logger.info( ( "ValidateService: ticket %s validated for user %s on service %s. " "Proxy Granting Ticket transmited to %s." ) % ( self.ticket.value, self.ticket.user.username, self.ticket.service, self.pgt_url ) ) logger.debug( "ValidateService: User attributs are:\n%s" % ( pprint.pformat(self.ticket.attributs), ) ) return render( self.request, "cas_server/serviceValidate.xml", params, content_type="text/xml; charset=utf-8" ) except requests.exceptions.RequestException as error: error = utils.unpack_nested_exception(error) raise ValidateError( u'INVALID_PROXY_CALLBACK', u"%s: %s" % (type(error), str(error)) ) else: raise ValidateError( u'INVALID_PROXY_CALLBACK', u"callback url not allowed by configuration" ) except ServicePattern.DoesNotExist: raise ValidateError( u'INVALID_PROXY_CALLBACK', u'callback url not allowed by configuration' )
[ "def", "process_pgturl", "(", "self", ",", "params", ")", ":", "try", ":", "pattern", "=", "ServicePattern", ".", "validate", "(", "self", ".", "pgt_url", ")", "if", "pattern", ".", "proxy_callback", ":", "proxyid", "=", "utils", ".", "gen_pgtiou", "(", ...
Handle PGT request :param dict params: A template context dict :raises ValidateError: if pgtUrl is invalid or if TLS validation of the pgtUrl fails :return: The rendering of ``cas_server/serviceValidate.xml``, using ``params`` :rtype: django.http.HttpResponse
[ "Handle", "PGT", "request" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/views.py#L1219-L1282
21,972
nitmir/django-cas-server
cas_server/views.py
Proxy.process_proxy
def process_proxy(self): """ handle PT request :raises ValidateError: if the PGT is not found, or the target service not allowed or the user not allowed on the tardet service. :return: The rendering of ``cas_server/proxy.xml`` :rtype: django.http.HttpResponse """ try: # is the target service allowed pattern = ServicePattern.validate(self.target_service) # to get a proxy ticket require that the service allow it if not pattern.proxy: raise ValidateError( u'UNAUTHORIZED_SERVICE', u'the service %s does not allow proxy tickets' % self.target_service ) # is the proxy granting ticket valid ticket = ProxyGrantingTicket.get(self.pgt) # is the pgt user allowed on the target service pattern.check_user(ticket.user) pticket = ticket.user.get_ticket( ProxyTicket, self.target_service, pattern, renew=False ) models.Proxy.objects.create(proxy_ticket=pticket, url=ticket.service) logger.info( "Proxy ticket created for user %s on service %s." % ( ticket.user.username, self.target_service ) ) return render( self.request, "cas_server/proxy.xml", {'ticket': pticket.value}, content_type="text/xml; charset=utf-8" ) except (Ticket.DoesNotExist, ProxyGrantingTicket.DoesNotExist): raise ValidateError(u'INVALID_TICKET', u'PGT %s not found' % self.pgt) except ServicePattern.DoesNotExist: raise ValidateError(u'UNAUTHORIZED_SERVICE', self.target_service) except (models.BadUsername, models.BadFilter, models.UserFieldNotDefined): raise ValidateError( u'UNAUTHORIZED_USER', u'User %s not allowed on %s' % (ticket.user.username, self.target_service) )
python
def process_proxy(self): try: # is the target service allowed pattern = ServicePattern.validate(self.target_service) # to get a proxy ticket require that the service allow it if not pattern.proxy: raise ValidateError( u'UNAUTHORIZED_SERVICE', u'the service %s does not allow proxy tickets' % self.target_service ) # is the proxy granting ticket valid ticket = ProxyGrantingTicket.get(self.pgt) # is the pgt user allowed on the target service pattern.check_user(ticket.user) pticket = ticket.user.get_ticket( ProxyTicket, self.target_service, pattern, renew=False ) models.Proxy.objects.create(proxy_ticket=pticket, url=ticket.service) logger.info( "Proxy ticket created for user %s on service %s." % ( ticket.user.username, self.target_service ) ) return render( self.request, "cas_server/proxy.xml", {'ticket': pticket.value}, content_type="text/xml; charset=utf-8" ) except (Ticket.DoesNotExist, ProxyGrantingTicket.DoesNotExist): raise ValidateError(u'INVALID_TICKET', u'PGT %s not found' % self.pgt) except ServicePattern.DoesNotExist: raise ValidateError(u'UNAUTHORIZED_SERVICE', self.target_service) except (models.BadUsername, models.BadFilter, models.UserFieldNotDefined): raise ValidateError( u'UNAUTHORIZED_USER', u'User %s not allowed on %s' % (ticket.user.username, self.target_service) )
[ "def", "process_proxy", "(", "self", ")", ":", "try", ":", "# is the target service allowed", "pattern", "=", "ServicePattern", ".", "validate", "(", "self", ".", "target_service", ")", "# to get a proxy ticket require that the service allow it", "if", "not", "pattern", ...
handle PT request :raises ValidateError: if the PGT is not found, or the target service not allowed or the user not allowed on the tardet service. :return: The rendering of ``cas_server/proxy.xml`` :rtype: django.http.HttpResponse
[ "handle", "PT", "request" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/views.py#L1320-L1369
21,973
nitmir/django-cas-server
cas_server/views.py
SamlValidate.process_ticket
def process_ticket(self): """ validate ticket from SAML XML body :raises: SamlValidateError: if the ticket is not found or not valid, or if we fail to parse the posted XML. :return: a ticket object :rtype: :class:`models.Ticket<cas_server.models.Ticket>` """ try: auth_req = self.root.getchildren()[1].getchildren()[0] ticket = auth_req.getchildren()[0].text ticket = models.Ticket.get(ticket) if ticket.service != self.target: raise SamlValidateError( u'AuthnFailed', u'TARGET %s does not match ticket service' % self.target ) return ticket except (IndexError, KeyError): raise SamlValidateError(u'VersionMismatch') except Ticket.DoesNotExist: raise SamlValidateError( u'AuthnFailed', u'ticket %s should begin with PT- or ST-' % ticket ) except (ServiceTicket.DoesNotExist, ProxyTicket.DoesNotExist): raise SamlValidateError(u'AuthnFailed', u'ticket %s not found' % ticket)
python
def process_ticket(self): try: auth_req = self.root.getchildren()[1].getchildren()[0] ticket = auth_req.getchildren()[0].text ticket = models.Ticket.get(ticket) if ticket.service != self.target: raise SamlValidateError( u'AuthnFailed', u'TARGET %s does not match ticket service' % self.target ) return ticket except (IndexError, KeyError): raise SamlValidateError(u'VersionMismatch') except Ticket.DoesNotExist: raise SamlValidateError( u'AuthnFailed', u'ticket %s should begin with PT- or ST-' % ticket ) except (ServiceTicket.DoesNotExist, ProxyTicket.DoesNotExist): raise SamlValidateError(u'AuthnFailed', u'ticket %s not found' % ticket)
[ "def", "process_ticket", "(", "self", ")", ":", "try", ":", "auth_req", "=", "self", ".", "root", ".", "getchildren", "(", ")", "[", "1", "]", ".", "getchildren", "(", ")", "[", "0", "]", "ticket", "=", "auth_req", ".", "getchildren", "(", ")", "["...
validate ticket from SAML XML body :raises: SamlValidateError: if the ticket is not found or not valid, or if we fail to parse the posted XML. :return: a ticket object :rtype: :class:`models.Ticket<cas_server.models.Ticket>`
[ "validate", "ticket", "from", "SAML", "XML", "body" ]
d106181b94c444f1946269da5c20f6c904840ad3
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/views.py#L1446-L1473
21,974
pipermerriam/flex
flex/cli.py
main
def main(source): """ For a given command line supplied argument, negotiate the content, parse the schema and then return any issues to stdout or if no schema issues, return success exit code. """ if source is None: click.echo( "You need to supply a file or url to a schema to a swagger schema, for" "the validator to work." ) return 1 try: load(source) click.echo("Validation passed") return 0 except ValidationError as e: raise click.ClickException(str(e))
python
def main(source): if source is None: click.echo( "You need to supply a file or url to a schema to a swagger schema, for" "the validator to work." ) return 1 try: load(source) click.echo("Validation passed") return 0 except ValidationError as e: raise click.ClickException(str(e))
[ "def", "main", "(", "source", ")", ":", "if", "source", "is", "None", ":", "click", ".", "echo", "(", "\"You need to supply a file or url to a schema to a swagger schema, for\"", "\"the validator to work.\"", ")", "return", "1", "try", ":", "load", "(", "source", ")...
For a given command line supplied argument, negotiate the content, parse the schema and then return any issues to stdout or if no schema issues, return success exit code.
[ "For", "a", "given", "command", "line", "supplied", "argument", "negotiate", "the", "content", "parse", "the", "schema", "and", "then", "return", "any", "issues", "to", "stdout", "or", "if", "no", "schema", "issues", "return", "success", "exit", "code", "." ...
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/cli.py#L12-L29
21,975
pipermerriam/flex
flex/core.py
load_source
def load_source(source): """ Common entry point for loading some form of raw swagger schema. Supports: - python object (dictionary-like) - path to yaml file - path to json file - file object (json or yaml). - json string. - yaml string. """ if isinstance(source, collections.Mapping): return deepcopy(source) elif hasattr(source, 'read') and callable(source.read): raw_source = source.read() elif os.path.exists(os.path.expanduser(str(source))): with open(os.path.expanduser(str(source)), 'r') as source_file: raw_source = source_file.read() elif isinstance(source, six.string_types): parts = urlparse.urlparse(source) if parts.scheme and parts.netloc: response = requests.get(source) if isinstance(response.content, six.binary_type): raw_source = six.text_type(response.content, encoding='utf-8') else: raw_source = response.content else: raw_source = source try: try: return json.loads(raw_source) except ValueError: pass try: return yaml.safe_load(raw_source) except (yaml.scanner.ScannerError, yaml.parser.ParserError): pass except NameError: pass raise ValueError( "Unable to parse `{0}`. Tried yaml and json.".format(source), )
python
def load_source(source): if isinstance(source, collections.Mapping): return deepcopy(source) elif hasattr(source, 'read') and callable(source.read): raw_source = source.read() elif os.path.exists(os.path.expanduser(str(source))): with open(os.path.expanduser(str(source)), 'r') as source_file: raw_source = source_file.read() elif isinstance(source, six.string_types): parts = urlparse.urlparse(source) if parts.scheme and parts.netloc: response = requests.get(source) if isinstance(response.content, six.binary_type): raw_source = six.text_type(response.content, encoding='utf-8') else: raw_source = response.content else: raw_source = source try: try: return json.loads(raw_source) except ValueError: pass try: return yaml.safe_load(raw_source) except (yaml.scanner.ScannerError, yaml.parser.ParserError): pass except NameError: pass raise ValueError( "Unable to parse `{0}`. Tried yaml and json.".format(source), )
[ "def", "load_source", "(", "source", ")", ":", "if", "isinstance", "(", "source", ",", "collections", ".", "Mapping", ")", ":", "return", "deepcopy", "(", "source", ")", "elif", "hasattr", "(", "source", ",", "'read'", ")", "and", "callable", "(", "sourc...
Common entry point for loading some form of raw swagger schema. Supports: - python object (dictionary-like) - path to yaml file - path to json file - file object (json or yaml). - json string. - yaml string.
[ "Common", "entry", "point", "for", "loading", "some", "form", "of", "raw", "swagger", "schema", "." ]
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/core.py#L33-L78
21,976
pipermerriam/flex
flex/core.py
validate
def validate(raw_schema, target=None, **kwargs): """ Given the python representation of a JSONschema as defined in the swagger spec, validate that the schema complies to spec. If `target` is provided, that target will be validated against the provided schema. """ schema = schema_validator(raw_schema, **kwargs) if target is not None: validate_object(target, schema=schema, **kwargs)
python
def validate(raw_schema, target=None, **kwargs): schema = schema_validator(raw_schema, **kwargs) if target is not None: validate_object(target, schema=schema, **kwargs)
[ "def", "validate", "(", "raw_schema", ",", "target", "=", "None", ",", "*", "*", "kwargs", ")", ":", "schema", "=", "schema_validator", "(", "raw_schema", ",", "*", "*", "kwargs", ")", "if", "target", "is", "not", "None", ":", "validate_object", "(", "...
Given the python representation of a JSONschema as defined in the swagger spec, validate that the schema complies to spec. If `target` is provided, that target will be validated against the provided schema.
[ "Given", "the", "python", "representation", "of", "a", "JSONschema", "as", "defined", "in", "the", "swagger", "spec", "validate", "that", "the", "schema", "complies", "to", "spec", ".", "If", "target", "is", "provided", "that", "target", "will", "be", "valid...
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/core.py#L103-L111
21,977
pipermerriam/flex
flex/core.py
validate_api_response
def validate_api_response(schema, raw_response, request_method='get', raw_request=None): """ Validate the response of an api call against a swagger schema. """ request = None if raw_request is not None: request = normalize_request(raw_request) response = None if raw_response is not None: response = normalize_response(raw_response, request=request) if response is not None: validate_response( response=response, request_method=request_method, schema=schema )
python
def validate_api_response(schema, raw_response, request_method='get', raw_request=None): request = None if raw_request is not None: request = normalize_request(raw_request) response = None if raw_response is not None: response = normalize_response(raw_response, request=request) if response is not None: validate_response( response=response, request_method=request_method, schema=schema )
[ "def", "validate_api_response", "(", "schema", ",", "raw_response", ",", "request_method", "=", "'get'", ",", "raw_request", "=", "None", ")", ":", "request", "=", "None", "if", "raw_request", "is", "not", "None", ":", "request", "=", "normalize_request", "(",...
Validate the response of an api call against a swagger schema.
[ "Validate", "the", "response", "of", "an", "api", "call", "against", "a", "swagger", "schema", "." ]
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/core.py#L121-L138
21,978
pipermerriam/flex
flex/parameters.py
find_parameter
def find_parameter(parameters, **kwargs): """ Given a list of parameters, find the one with the given name. """ matching_parameters = filter_parameters(parameters, **kwargs) if len(matching_parameters) == 1: return matching_parameters[0] elif len(matching_parameters) > 1: raise MultipleParametersFound() raise NoParameterFound()
python
def find_parameter(parameters, **kwargs): matching_parameters = filter_parameters(parameters, **kwargs) if len(matching_parameters) == 1: return matching_parameters[0] elif len(matching_parameters) > 1: raise MultipleParametersFound() raise NoParameterFound()
[ "def", "find_parameter", "(", "parameters", ",", "*", "*", "kwargs", ")", ":", "matching_parameters", "=", "filter_parameters", "(", "parameters", ",", "*", "*", "kwargs", ")", "if", "len", "(", "matching_parameters", ")", "==", "1", ":", "return", "matching...
Given a list of parameters, find the one with the given name.
[ "Given", "a", "list", "of", "parameters", "find", "the", "one", "with", "the", "given", "name", "." ]
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/parameters.py#L25-L34
21,979
pipermerriam/flex
flex/parameters.py
merge_parameter_lists
def merge_parameter_lists(*parameter_definitions): """ Merge multiple lists of parameters into a single list. If there are any duplicate definitions, the last write wins. """ merged_parameters = {} for parameter_list in parameter_definitions: for parameter in parameter_list: key = (parameter['name'], parameter['in']) merged_parameters[key] = parameter return merged_parameters.values()
python
def merge_parameter_lists(*parameter_definitions): merged_parameters = {} for parameter_list in parameter_definitions: for parameter in parameter_list: key = (parameter['name'], parameter['in']) merged_parameters[key] = parameter return merged_parameters.values()
[ "def", "merge_parameter_lists", "(", "*", "parameter_definitions", ")", ":", "merged_parameters", "=", "{", "}", "for", "parameter_list", "in", "parameter_definitions", ":", "for", "parameter", "in", "parameter_list", ":", "key", "=", "(", "parameter", "[", "'name...
Merge multiple lists of parameters into a single list. If there are any duplicate definitions, the last write wins.
[ "Merge", "multiple", "lists", "of", "parameters", "into", "a", "single", "list", ".", "If", "there", "are", "any", "duplicate", "definitions", "the", "last", "write", "wins", "." ]
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/parameters.py#L37-L47
21,980
pipermerriam/flex
flex/validation/response.py
validate_status_code_to_response_definition
def validate_status_code_to_response_definition(response, operation_definition): """ Given a response, validate that the response status code is in the accepted status codes defined by this endpoint. If so, return the response definition that corresponds to the status code. """ status_code = response.status_code operation_responses = {str(code): val for code, val in operation_definition['responses'].items()} key = status_code if key not in operation_responses: key = 'default' try: response_definition = operation_responses[key] except KeyError: raise ValidationError( MESSAGES['response']['invalid_status_code'].format( status_code, ', '.join(operation_responses.keys()), ), ) return response_definition
python
def validate_status_code_to_response_definition(response, operation_definition): status_code = response.status_code operation_responses = {str(code): val for code, val in operation_definition['responses'].items()} key = status_code if key not in operation_responses: key = 'default' try: response_definition = operation_responses[key] except KeyError: raise ValidationError( MESSAGES['response']['invalid_status_code'].format( status_code, ', '.join(operation_responses.keys()), ), ) return response_definition
[ "def", "validate_status_code_to_response_definition", "(", "response", ",", "operation_definition", ")", ":", "status_code", "=", "response", ".", "status_code", "operation_responses", "=", "{", "str", "(", "code", ")", ":", "val", "for", "code", ",", "val", "in",...
Given a response, validate that the response status code is in the accepted status codes defined by this endpoint. If so, return the response definition that corresponds to the status code.
[ "Given", "a", "response", "validate", "that", "the", "response", "status", "code", "is", "in", "the", "accepted", "status", "codes", "defined", "by", "this", "endpoint", "." ]
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/response.py#L37-L60
21,981
pipermerriam/flex
flex/validation/response.py
generate_path_validator
def generate_path_validator(api_path, path_definition, parameters, context, **kwargs): """ Generates a callable for validating the parameters in a response object. """ path_level_parameters = dereference_parameter_list( path_definition.get('parameters', []), context, ) operation_level_parameters = dereference_parameter_list( parameters, context, ) all_parameters = merge_parameter_lists( path_level_parameters, operation_level_parameters, ) # PATH in_path_parameters = filter_parameters(all_parameters, in_=PATH) return chain_reduce_partial( attrgetter('path'), generate_path_parameters_validator(api_path, in_path_parameters, context), )
python
def generate_path_validator(api_path, path_definition, parameters, context, **kwargs): path_level_parameters = dereference_parameter_list( path_definition.get('parameters', []), context, ) operation_level_parameters = dereference_parameter_list( parameters, context, ) all_parameters = merge_parameter_lists( path_level_parameters, operation_level_parameters, ) # PATH in_path_parameters = filter_parameters(all_parameters, in_=PATH) return chain_reduce_partial( attrgetter('path'), generate_path_parameters_validator(api_path, in_path_parameters, context), )
[ "def", "generate_path_validator", "(", "api_path", ",", "path_definition", ",", "parameters", ",", "context", ",", "*", "*", "kwargs", ")", ":", "path_level_parameters", "=", "dereference_parameter_list", "(", "path_definition", ".", "get", "(", "'parameters'", ",",...
Generates a callable for validating the parameters in a response object.
[ "Generates", "a", "callable", "for", "validating", "the", "parameters", "in", "a", "response", "object", "." ]
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/response.py#L115-L139
21,982
pipermerriam/flex
flex/validation/response.py
validate_response
def validate_response(response, request_method, schema): """ Response validation involves the following steps. 4. validate that the response status_code is in the allowed responses for the request method. 5. validate that the response content validates against any provided schemas for the responses. 6. headers, content-types, etc..., ??? """ with ErrorDict() as errors: # 1 # TODO: tests try: api_path = validate_path_to_api_path( path=response.path, context=schema, **schema ) except ValidationError as err: errors['path'].extend(list(err.messages)) return # this causes an exception to be raised since errors is no longer falsy. path_definition = schema['paths'][api_path] or {} # TODO: tests try: operation_definition = validate_request_method_to_operation( request_method=request_method, path_definition=path_definition, ) except ValidationError as err: errors['method'].add_error(err.detail) return # 4 try: response_definition = validate_status_code_to_response_definition( response=response, operation_definition=operation_definition, ) except ValidationError as err: errors['status_code'].add_error(err.detail) else: # 5 response_validator = generate_response_validator( api_path, operation_definition=operation_definition, path_definition=path_definition, response_definition=response_definition, context=schema, ) try: response_validator(response, context=schema) except ValidationError as err: errors['body'].add_error(err.detail)
python
def validate_response(response, request_method, schema): with ErrorDict() as errors: # 1 # TODO: tests try: api_path = validate_path_to_api_path( path=response.path, context=schema, **schema ) except ValidationError as err: errors['path'].extend(list(err.messages)) return # this causes an exception to be raised since errors is no longer falsy. path_definition = schema['paths'][api_path] or {} # TODO: tests try: operation_definition = validate_request_method_to_operation( request_method=request_method, path_definition=path_definition, ) except ValidationError as err: errors['method'].add_error(err.detail) return # 4 try: response_definition = validate_status_code_to_response_definition( response=response, operation_definition=operation_definition, ) except ValidationError as err: errors['status_code'].add_error(err.detail) else: # 5 response_validator = generate_response_validator( api_path, operation_definition=operation_definition, path_definition=path_definition, response_definition=response_definition, context=schema, ) try: response_validator(response, context=schema) except ValidationError as err: errors['body'].add_error(err.detail)
[ "def", "validate_response", "(", "response", ",", "request_method", ",", "schema", ")", ":", "with", "ErrorDict", "(", ")", "as", "errors", ":", "# 1", "# TODO: tests", "try", ":", "api_path", "=", "validate_path_to_api_path", "(", "path", "=", "response", "."...
Response validation involves the following steps. 4. validate that the response status_code is in the allowed responses for the request method. 5. validate that the response content validates against any provided schemas for the responses. 6. headers, content-types, etc..., ???
[ "Response", "validation", "involves", "the", "following", "steps", ".", "4", ".", "validate", "that", "the", "response", "status_code", "is", "in", "the", "allowed", "responses", "for", "the", "request", "method", ".", "5", ".", "validate", "that", "the", "r...
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/response.py#L194-L248
21,983
pipermerriam/flex
flex/validation/schema.py
construct_schema_validators
def construct_schema_validators(schema, context): """ Given a schema object, construct a dictionary of validators needed to validate a response matching the given schema. Special Cases: - $ref: These validators need to be Lazily evaluating so that circular validation dependencies do not result in an infinitely deep validation chain. - properties: These validators are meant to apply to properties of the object being validated rather than the object itself. In this case, we need recurse back into this function to generate a dictionary of validators for the property. """ validators = ValidationDict() if '$ref' in schema: validators.add_validator( '$ref', SchemaReferenceValidator(schema['$ref'], context), ) if 'properties' in schema: for property_, property_schema in schema['properties'].items(): property_validator = generate_object_validator( schema=property_schema, context=context, ) validators.add_property_validator(property_, property_validator) if schema.get('additionalProperties') is False: validators.add_validator( 'additionalProperties', generate_additional_properties_validator(context=context, **schema), ) assert 'context' not in schema for key in schema: if key in validator_mapping: validators.add_validator(key, validator_mapping[key](context=context, **schema)) return validators
python
def construct_schema_validators(schema, context): validators = ValidationDict() if '$ref' in schema: validators.add_validator( '$ref', SchemaReferenceValidator(schema['$ref'], context), ) if 'properties' in schema: for property_, property_schema in schema['properties'].items(): property_validator = generate_object_validator( schema=property_schema, context=context, ) validators.add_property_validator(property_, property_validator) if schema.get('additionalProperties') is False: validators.add_validator( 'additionalProperties', generate_additional_properties_validator(context=context, **schema), ) assert 'context' not in schema for key in schema: if key in validator_mapping: validators.add_validator(key, validator_mapping[key](context=context, **schema)) return validators
[ "def", "construct_schema_validators", "(", "schema", ",", "context", ")", ":", "validators", "=", "ValidationDict", "(", ")", "if", "'$ref'", "in", "schema", ":", "validators", ".", "add_validator", "(", "'$ref'", ",", "SchemaReferenceValidator", "(", "schema", ...
Given a schema object, construct a dictionary of validators needed to validate a response matching the given schema. Special Cases: - $ref: These validators need to be Lazily evaluating so that circular validation dependencies do not result in an infinitely deep validation chain. - properties: These validators are meant to apply to properties of the object being validated rather than the object itself. In this case, we need recurse back into this function to generate a dictionary of validators for the property.
[ "Given", "a", "schema", "object", "construct", "a", "dictionary", "of", "validators", "needed", "to", "validate", "a", "response", "matching", "the", "given", "schema", "." ]
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/schema.py#L199-L236
21,984
pipermerriam/flex
flex/validation/common.py
validate_type
def validate_type(value, types, **kwargs): """ Validate that the value is one of the provided primative types. """ if not is_value_of_any_type(value, types): raise ValidationError(MESSAGES['type']['invalid'].format( repr(value), get_type_for_value(value), types, ))
python
def validate_type(value, types, **kwargs): if not is_value_of_any_type(value, types): raise ValidationError(MESSAGES['type']['invalid'].format( repr(value), get_type_for_value(value), types, ))
[ "def", "validate_type", "(", "value", ",", "types", ",", "*", "*", "kwargs", ")", ":", "if", "not", "is_value_of_any_type", "(", "value", ",", "types", ")", ":", "raise", "ValidationError", "(", "MESSAGES", "[", "'type'", "]", "[", "'invalid'", "]", ".",...
Validate that the value is one of the provided primative types.
[ "Validate", "that", "the", "value", "is", "one", "of", "the", "provided", "primative", "types", "." ]
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/common.py#L56-L63
21,985
pipermerriam/flex
flex/validation/common.py
generate_type_validator
def generate_type_validator(type_, **kwargs): """ Generates a callable validator for the given type or iterable of types. """ if is_non_string_iterable(type_): types = tuple(type_) else: types = (type_,) # support x-nullable since Swagger 2.0 doesn't support null type # (see https://github.com/OAI/OpenAPI-Specification/issues/229) if kwargs.get('x-nullable', False) and NULL not in types: types = types + (NULL,) return functools.partial(validate_type, types=types)
python
def generate_type_validator(type_, **kwargs): if is_non_string_iterable(type_): types = tuple(type_) else: types = (type_,) # support x-nullable since Swagger 2.0 doesn't support null type # (see https://github.com/OAI/OpenAPI-Specification/issues/229) if kwargs.get('x-nullable', False) and NULL not in types: types = types + (NULL,) return functools.partial(validate_type, types=types)
[ "def", "generate_type_validator", "(", "type_", ",", "*", "*", "kwargs", ")", ":", "if", "is_non_string_iterable", "(", "type_", ")", ":", "types", "=", "tuple", "(", "type_", ")", "else", ":", "types", "=", "(", "type_", ",", ")", "# support x-nullable si...
Generates a callable validator for the given type or iterable of types.
[ "Generates", "a", "callable", "validator", "for", "the", "given", "type", "or", "iterable", "of", "types", "." ]
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/common.py#L67-L79
21,986
pipermerriam/flex
flex/validation/common.py
validate_multiple_of
def validate_multiple_of(value, divisor, **kwargs): """ Given a value and a divisor, validate that the value is divisible by the divisor. """ if not decimal.Decimal(str(value)) % decimal.Decimal(str(divisor)) == 0: raise ValidationError( MESSAGES['multiple_of']['invalid'].format(divisor, value), )
python
def validate_multiple_of(value, divisor, **kwargs): if not decimal.Decimal(str(value)) % decimal.Decimal(str(divisor)) == 0: raise ValidationError( MESSAGES['multiple_of']['invalid'].format(divisor, value), )
[ "def", "validate_multiple_of", "(", "value", ",", "divisor", ",", "*", "*", "kwargs", ")", ":", "if", "not", "decimal", ".", "Decimal", "(", "str", "(", "value", ")", ")", "%", "decimal", ".", "Decimal", "(", "str", "(", "divisor", ")", ")", "==", ...
Given a value and a divisor, validate that the value is divisible by the divisor.
[ "Given", "a", "value", "and", "a", "divisor", "validate", "that", "the", "value", "is", "divisible", "by", "the", "divisor", "." ]
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/common.py#L103-L111
21,987
pipermerriam/flex
flex/validation/common.py
validate_minimum
def validate_minimum(value, minimum, is_exclusive, **kwargs): """ Validator function for validating that a value does not violate it's minimum allowed value. This validation can be inclusive, or exclusive of the minimum depending on the value of `is_exclusive`. """ if is_exclusive: comparison_text = "greater than" compare_fn = operator.gt else: comparison_text = "greater than or equal to" compare_fn = operator.ge if not compare_fn(value, minimum): raise ValidationError( MESSAGES['minimum']['invalid'].format(value, comparison_text, minimum), )
python
def validate_minimum(value, minimum, is_exclusive, **kwargs): if is_exclusive: comparison_text = "greater than" compare_fn = operator.gt else: comparison_text = "greater than or equal to" compare_fn = operator.ge if not compare_fn(value, minimum): raise ValidationError( MESSAGES['minimum']['invalid'].format(value, comparison_text, minimum), )
[ "def", "validate_minimum", "(", "value", ",", "minimum", ",", "is_exclusive", ",", "*", "*", "kwargs", ")", ":", "if", "is_exclusive", ":", "comparison_text", "=", "\"greater than\"", "compare_fn", "=", "operator", ".", "gt", "else", ":", "comparison_text", "=...
Validator function for validating that a value does not violate it's minimum allowed value. This validation can be inclusive, or exclusive of the minimum depending on the value of `is_exclusive`.
[ "Validator", "function", "for", "validating", "that", "a", "value", "does", "not", "violate", "it", "s", "minimum", "allowed", "value", ".", "This", "validation", "can", "be", "inclusive", "or", "exclusive", "of", "the", "minimum", "depending", "on", "the", ...
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/common.py#L120-L136
21,988
pipermerriam/flex
flex/validation/common.py
generate_minimum_validator
def generate_minimum_validator(minimum, exclusiveMinimum=False, **kwargs): """ Generator function returning a callable for minimum value validation. """ return functools.partial(validate_minimum, minimum=minimum, is_exclusive=exclusiveMinimum)
python
def generate_minimum_validator(minimum, exclusiveMinimum=False, **kwargs): return functools.partial(validate_minimum, minimum=minimum, is_exclusive=exclusiveMinimum)
[ "def", "generate_minimum_validator", "(", "minimum", ",", "exclusiveMinimum", "=", "False", ",", "*", "*", "kwargs", ")", ":", "return", "functools", ".", "partial", "(", "validate_minimum", ",", "minimum", "=", "minimum", ",", "is_exclusive", "=", "exclusiveMin...
Generator function returning a callable for minimum value validation.
[ "Generator", "function", "returning", "a", "callable", "for", "minimum", "value", "validation", "." ]
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/common.py#L139-L143
21,989
pipermerriam/flex
flex/validation/common.py
validate_maximum
def validate_maximum(value, maximum, is_exclusive, **kwargs): """ Validator function for validating that a value does not violate it's maximum allowed value. This validation can be inclusive, or exclusive of the maximum depending on the value of `is_exclusive`. """ if is_exclusive: comparison_text = "less than" compare_fn = operator.lt else: comparison_text = "less than or equal to" compare_fn = operator.le if not compare_fn(value, maximum): raise ValidationError( MESSAGES['maximum']['invalid'].format(value, comparison_text, maximum), )
python
def validate_maximum(value, maximum, is_exclusive, **kwargs): if is_exclusive: comparison_text = "less than" compare_fn = operator.lt else: comparison_text = "less than or equal to" compare_fn = operator.le if not compare_fn(value, maximum): raise ValidationError( MESSAGES['maximum']['invalid'].format(value, comparison_text, maximum), )
[ "def", "validate_maximum", "(", "value", ",", "maximum", ",", "is_exclusive", ",", "*", "*", "kwargs", ")", ":", "if", "is_exclusive", ":", "comparison_text", "=", "\"less than\"", "compare_fn", "=", "operator", ".", "lt", "else", ":", "comparison_text", "=", ...
Validator function for validating that a value does not violate it's maximum allowed value. This validation can be inclusive, or exclusive of the maximum depending on the value of `is_exclusive`.
[ "Validator", "function", "for", "validating", "that", "a", "value", "does", "not", "violate", "it", "s", "maximum", "allowed", "value", ".", "This", "validation", "can", "be", "inclusive", "or", "exclusive", "of", "the", "maximum", "depending", "on", "the", ...
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/common.py#L148-L164
21,990
pipermerriam/flex
flex/validation/common.py
generate_maximum_validator
def generate_maximum_validator(maximum, exclusiveMaximum=False, **kwargs): """ Generator function returning a callable for maximum value validation. """ return functools.partial(validate_maximum, maximum=maximum, is_exclusive=exclusiveMaximum)
python
def generate_maximum_validator(maximum, exclusiveMaximum=False, **kwargs): return functools.partial(validate_maximum, maximum=maximum, is_exclusive=exclusiveMaximum)
[ "def", "generate_maximum_validator", "(", "maximum", ",", "exclusiveMaximum", "=", "False", ",", "*", "*", "kwargs", ")", ":", "return", "functools", ".", "partial", "(", "validate_maximum", ",", "maximum", "=", "maximum", ",", "is_exclusive", "=", "exclusiveMax...
Generator function returning a callable for maximum value validation.
[ "Generator", "function", "returning", "a", "callable", "for", "maximum", "value", "validation", "." ]
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/common.py#L167-L171
21,991
pipermerriam/flex
flex/validation/common.py
validate_min_items
def validate_min_items(value, minimum, **kwargs): """ Validator for ARRAY types to enforce a minimum number of items allowed for the ARRAY to be valid. """ if len(value) < minimum: raise ValidationError( MESSAGES['min_items']['invalid'].format( minimum, len(value), ), )
python
def validate_min_items(value, minimum, **kwargs): if len(value) < minimum: raise ValidationError( MESSAGES['min_items']['invalid'].format( minimum, len(value), ), )
[ "def", "validate_min_items", "(", "value", ",", "minimum", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "value", ")", "<", "minimum", ":", "raise", "ValidationError", "(", "MESSAGES", "[", "'min_items'", "]", "[", "'invalid'", "]", ".", "format",...
Validator for ARRAY types to enforce a minimum number of items allowed for the ARRAY to be valid.
[ "Validator", "for", "ARRAY", "types", "to", "enforce", "a", "minimum", "number", "of", "items", "allowed", "for", "the", "ARRAY", "to", "be", "valid", "." ]
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/common.py#L204-L214
21,992
pipermerriam/flex
flex/validation/common.py
validate_max_items
def validate_max_items(value, maximum, **kwargs): """ Validator for ARRAY types to enforce a maximum number of items allowed for the ARRAY to be valid. """ if len(value) > maximum: raise ValidationError( MESSAGES['max_items']['invalid'].format( maximum, len(value), ), )
python
def validate_max_items(value, maximum, **kwargs): if len(value) > maximum: raise ValidationError( MESSAGES['max_items']['invalid'].format( maximum, len(value), ), )
[ "def", "validate_max_items", "(", "value", ",", "maximum", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "value", ")", ">", "maximum", ":", "raise", "ValidationError", "(", "MESSAGES", "[", "'max_items'", "]", "[", "'invalid'", "]", ".", "format",...
Validator for ARRAY types to enforce a maximum number of items allowed for the ARRAY to be valid.
[ "Validator", "for", "ARRAY", "types", "to", "enforce", "a", "maximum", "number", "of", "items", "allowed", "for", "the", "ARRAY", "to", "be", "valid", "." ]
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/common.py#L226-L236
21,993
pipermerriam/flex
flex/validation/common.py
validate_unique_items
def validate_unique_items(value, **kwargs): """ Validator for ARRAY types to enforce that all array items must be unique. """ # we can't just look at the items themselves since 0 and False are treated # the same as dictionary keys, and objects aren't hashable. counter = collections.Counter(( json.dumps(v, sort_keys=True) for v in value )) dupes = [json.loads(v) for v, count in counter.items() if count > 1] if dupes: raise ValidationError( MESSAGES['unique_items']['invalid'].format( repr(dupes), ), )
python
def validate_unique_items(value, **kwargs): # we can't just look at the items themselves since 0 and False are treated # the same as dictionary keys, and objects aren't hashable. counter = collections.Counter(( json.dumps(v, sort_keys=True) for v in value )) dupes = [json.loads(v) for v, count in counter.items() if count > 1] if dupes: raise ValidationError( MESSAGES['unique_items']['invalid'].format( repr(dupes), ), )
[ "def", "validate_unique_items", "(", "value", ",", "*", "*", "kwargs", ")", ":", "# we can't just look at the items themselves since 0 and False are treated", "# the same as dictionary keys, and objects aren't hashable.", "counter", "=", "collections", ".", "Counter", "(", "(", ...
Validator for ARRAY types to enforce that all array items must be unique.
[ "Validator", "for", "ARRAY", "types", "to", "enforce", "that", "all", "array", "items", "must", "be", "unique", "." ]
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/common.py#L248-L264
21,994
pipermerriam/flex
flex/validation/common.py
validate_object
def validate_object(obj, field_validators=None, non_field_validators=None, schema=None, context=None): """ Takes a mapping and applies a mapping of validator functions to it collecting and reraising any validation errors that occur. """ if schema is None: schema = {} if context is None: context = {} if field_validators is None: field_validators = ValidationDict() if non_field_validators is None: non_field_validators = ValidationList() from flex.validation.schema import ( construct_schema_validators, ) schema_validators = construct_schema_validators(schema, context) if '$ref' in schema_validators and hasattr(schema_validators['$ref'], 'validators'): ref_ = field_validators.pop('$ref') for k, v in ref_.validators.items(): if k not in schema_validators: schema_validators.add_validator(k, v) if 'discriminator' in schema: schema_validators = add_polymorphism_requirements(obj, schema, context, schema_validators) # delete resolved discriminator to avoid infinite recursion del schema['discriminator'] schema_validators.update(field_validators) schema_validators.validate_object(obj, context=context) non_field_validators.validate_object(obj, context=context) return obj
python
def validate_object(obj, field_validators=None, non_field_validators=None, schema=None, context=None): if schema is None: schema = {} if context is None: context = {} if field_validators is None: field_validators = ValidationDict() if non_field_validators is None: non_field_validators = ValidationList() from flex.validation.schema import ( construct_schema_validators, ) schema_validators = construct_schema_validators(schema, context) if '$ref' in schema_validators and hasattr(schema_validators['$ref'], 'validators'): ref_ = field_validators.pop('$ref') for k, v in ref_.validators.items(): if k not in schema_validators: schema_validators.add_validator(k, v) if 'discriminator' in schema: schema_validators = add_polymorphism_requirements(obj, schema, context, schema_validators) # delete resolved discriminator to avoid infinite recursion del schema['discriminator'] schema_validators.update(field_validators) schema_validators.validate_object(obj, context=context) non_field_validators.validate_object(obj, context=context) return obj
[ "def", "validate_object", "(", "obj", ",", "field_validators", "=", "None", ",", "non_field_validators", "=", "None", ",", "schema", "=", "None", ",", "context", "=", "None", ")", ":", "if", "schema", "is", "None", ":", "schema", "=", "{", "}", "if", "...
Takes a mapping and applies a mapping of validator functions to it collecting and reraising any validation errors that occur.
[ "Takes", "a", "mapping", "and", "applies", "a", "mapping", "of", "validator", "functions", "to", "it", "collecting", "and", "reraising", "any", "validation", "errors", "that", "occur", "." ]
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/common.py#L365-L398
21,995
pipermerriam/flex
flex/validation/common.py
validate_request_method_to_operation
def validate_request_method_to_operation(request_method, path_definition): """ Given a request method, validate that the request method is valid for the api path. If so, return the operation definition related to this request method. """ try: operation_definition = path_definition[request_method] except KeyError: allowed_methods = set(REQUEST_METHODS).intersection(path_definition.keys()) raise ValidationError( MESSAGES['request']['invalid_method'].format( request_method, allowed_methods, ), ) return operation_definition
python
def validate_request_method_to_operation(request_method, path_definition): try: operation_definition = path_definition[request_method] except KeyError: allowed_methods = set(REQUEST_METHODS).intersection(path_definition.keys()) raise ValidationError( MESSAGES['request']['invalid_method'].format( request_method, allowed_methods, ), ) return operation_definition
[ "def", "validate_request_method_to_operation", "(", "request_method", ",", "path_definition", ")", ":", "try", ":", "operation_definition", "=", "path_definition", "[", "request_method", "]", "except", "KeyError", ":", "allowed_methods", "=", "set", "(", "REQUEST_METHOD...
Given a request method, validate that the request method is valid for the api path. If so, return the operation definition related to this request method.
[ "Given", "a", "request", "method", "validate", "that", "the", "request", "method", "is", "valid", "for", "the", "api", "path", "." ]
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/common.py#L498-L514
21,996
pipermerriam/flex
flex/validation/common.py
validate_path_to_api_path
def validate_path_to_api_path(path, paths, basePath='', context=None, **kwargs): """ Given a path, find the api_path it matches. """ if context is None: context = {} try: api_path = match_path_to_api_path( path_definitions=paths, target_path=path, base_path=basePath, context=context, ) except LookupError as err: raise ValidationError(str(err)) except MultiplePathsFound as err: raise ValidationError(str(err)) return api_path
python
def validate_path_to_api_path(path, paths, basePath='', context=None, **kwargs): if context is None: context = {} try: api_path = match_path_to_api_path( path_definitions=paths, target_path=path, base_path=basePath, context=context, ) except LookupError as err: raise ValidationError(str(err)) except MultiplePathsFound as err: raise ValidationError(str(err)) return api_path
[ "def", "validate_path_to_api_path", "(", "path", ",", "paths", ",", "basePath", "=", "''", ",", "context", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "context", "is", "None", ":", "context", "=", "{", "}", "try", ":", "api_path", "=", "mat...
Given a path, find the api_path it matches.
[ "Given", "a", "path", "find", "the", "api_path", "it", "matches", "." ]
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/common.py#L517-L535
21,997
pipermerriam/flex
flex/validation/parameter.py
validate_path_parameters
def validate_path_parameters(target_path, api_path, path_parameters, context): """ Helper function for validating a request path """ base_path = context.get('basePath', '') full_api_path = re.sub(NORMALIZE_SLASH_REGEX, '/', base_path + api_path) parameter_values = get_path_parameter_values( target_path, full_api_path, path_parameters, context, ) validate_parameters(parameter_values, path_parameters, context=context)
python
def validate_path_parameters(target_path, api_path, path_parameters, context): base_path = context.get('basePath', '') full_api_path = re.sub(NORMALIZE_SLASH_REGEX, '/', base_path + api_path) parameter_values = get_path_parameter_values( target_path, full_api_path, path_parameters, context, ) validate_parameters(parameter_values, path_parameters, context=context)
[ "def", "validate_path_parameters", "(", "target_path", ",", "api_path", ",", "path_parameters", ",", "context", ")", ":", "base_path", "=", "context", ".", "get", "(", "'basePath'", ",", "''", ")", "full_api_path", "=", "re", ".", "sub", "(", "NORMALIZE_SLASH_...
Helper function for validating a request path
[ "Helper", "function", "for", "validating", "a", "request", "path" ]
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/parameter.py#L75-L84
21,998
pipermerriam/flex
flex/validation/parameter.py
construct_parameter_validators
def construct_parameter_validators(parameter, context): """ Constructs a dictionary of validator functions for the provided parameter definition. """ validators = ValidationDict() if '$ref' in parameter: validators.add_validator( '$ref', ParameterReferenceValidator(parameter['$ref'], context), ) for key in parameter: if key in validator_mapping: validators.add_validator( key, validator_mapping[key](context=context, **parameter), ) if 'schema' in parameter: schema_validators = construct_schema_validators(parameter['schema'], context=context) for key, value in schema_validators.items(): validators.setdefault(key, value) return validators
python
def construct_parameter_validators(parameter, context): validators = ValidationDict() if '$ref' in parameter: validators.add_validator( '$ref', ParameterReferenceValidator(parameter['$ref'], context), ) for key in parameter: if key in validator_mapping: validators.add_validator( key, validator_mapping[key](context=context, **parameter), ) if 'schema' in parameter: schema_validators = construct_schema_validators(parameter['schema'], context=context) for key, value in schema_validators.items(): validators.setdefault(key, value) return validators
[ "def", "construct_parameter_validators", "(", "parameter", ",", "context", ")", ":", "validators", "=", "ValidationDict", "(", ")", "if", "'$ref'", "in", "parameter", ":", "validators", ".", "add_validator", "(", "'$ref'", ",", "ParameterReferenceValidator", "(", ...
Constructs a dictionary of validator functions for the provided parameter definition.
[ "Constructs", "a", "dictionary", "of", "validator", "functions", "for", "the", "provided", "parameter", "definition", "." ]
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/parameter.py#L109-L129
21,999
pipermerriam/flex
flex/validation/parameter.py
construct_multi_parameter_validators
def construct_multi_parameter_validators(parameters, context): """ Given an iterable of parameters, returns a dictionary of validator functions for each parameter. Note that this expects the parameters to be unique in their name value, and throws an error if this is not the case. """ validators = ValidationDict() for parameter in parameters: key = parameter['name'] if key in validators: raise ValueError("Duplicate parameter name {0}".format(key)) parameter_validators = construct_parameter_validators(parameter, context=context) validators.add_validator( key, generate_object_validator(field_validators=parameter_validators), ) return validators
python
def construct_multi_parameter_validators(parameters, context): validators = ValidationDict() for parameter in parameters: key = parameter['name'] if key in validators: raise ValueError("Duplicate parameter name {0}".format(key)) parameter_validators = construct_parameter_validators(parameter, context=context) validators.add_validator( key, generate_object_validator(field_validators=parameter_validators), ) return validators
[ "def", "construct_multi_parameter_validators", "(", "parameters", ",", "context", ")", ":", "validators", "=", "ValidationDict", "(", ")", "for", "parameter", "in", "parameters", ":", "key", "=", "parameter", "[", "'name'", "]", "if", "key", "in", "validators", ...
Given an iterable of parameters, returns a dictionary of validator functions for each parameter. Note that this expects the parameters to be unique in their name value, and throws an error if this is not the case.
[ "Given", "an", "iterable", "of", "parameters", "returns", "a", "dictionary", "of", "validator", "functions", "for", "each", "parameter", ".", "Note", "that", "this", "expects", "the", "parameters", "to", "be", "unique", "in", "their", "name", "value", "and", ...
233f8149fb851a6255753bcec948cb6fefb2723b
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/validation/parameter.py#L150-L167