signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def set_permissions_mode_from_octal(file_path, code):
<EOL>user, group, other = tuple(str(code[-<NUM_LIT:3>:])) if len(str(code)) > <NUM_LIT:3> else tuple(str(code))<EOL>user, group, other = int(user), int(group), int(other)<EOL>mode = get_permissions_mode(user,<EOL>'<STR_LIT:user>') & get_permissions_mode(group, '<STR_LIT>') & get_permissions_mode(other, '<STR_LIT>')<EOL>os.chmod(file_path, mode)<EOL>
Set permissions for a file or directory. :param file_path: Path to a file or directory :param code: Permission code in absolute notation (octal) :return:
f12068:m1
def get_permissions_mode(permission_octal, name):
read = PERMISSIONS[name]['<STR_LIT>']<EOL>write = PERMISSIONS[name]['<STR_LIT>']<EOL>execute = PERMISSIONS[name]['<STR_LIT>']<EOL>if permission_octal == <NUM_LIT:4>:<EOL><INDENT>return read & ~write & ~execute<EOL><DEDENT>elif permission_octal == <NUM_LIT:2>:<EOL><INDENT>return ~read & write & ~execute<EOL><DEDENT>elif permission_octal == <NUM_LIT:1>:<EOL><INDENT>return ~read & ~write & execute<EOL><DEDENT>elif permission_octal == <NUM_LIT:6>:<EOL><INDENT>return read & write & ~execute<EOL><DEDENT>elif permission_octal == <NUM_LIT:5>:<EOL><INDENT>return read & ~write & execute<EOL><DEDENT>elif permission_octal == <NUM_LIT:3>:<EOL><INDENT>return ~read & write & execute<EOL><DEDENT>elif permission_octal == <NUM_LIT:7>:<EOL><INDENT>return read & write & execute<EOL><DEDENT>else:<EOL><INDENT>return ~read & ~write & ~execute<EOL><DEDENT>
Retrieve a user name group permissions bitwise code.
f12068:m2
@property<EOL><INDENT>def octal(self):<DEDENT>
return stat.S_IMODE(os.lstat(self.file_path).st_mode)<EOL>
Return file permissions in absolute notation (octal) format.
f12068:c0:m1
def allow(self, privilege):
assert privilege in PERMISSIONS['<STR_LIT:user>'].keys()<EOL>reading = PERMISSIONS['<STR_LIT:user>'][privilege] + PERMISSIONS['<STR_LIT>'][privilege] + PERMISSIONS['<STR_LIT>'][privilege]<EOL>os.chmod(self.file_path, reading)<EOL>
Add an allowed privilege (read, write, execute, all).
f12068:c0:m2
def allow_readonly(self):
os.chmod(self.file_path, <NUM_LIT>)<EOL>
Add an allowed privilege (read, write, execute, all).
f12068:c0:m3
def allow_rwe(self, name):
assert name in PERMISSIONS.keys()<EOL>os.chmod(self.file_path, PERMISSIONS[name]['<STR_LIT:all>'])<EOL>
Allow all privileges for a particular name group (user, group, other).
f12068:c0:m4
def revoke_access(self):
reading = PERMISSIONS['<STR_LIT:user>']['<STR_LIT>'] + PERMISSIONS['<STR_LIT>']['<STR_LIT>'] + PERMISSIONS['<STR_LIT>']['<STR_LIT>']<EOL>os.chmod(self.file_path, reading)<EOL>
Revoke all access to this path.
f12068:c0:m5
def unique(list1, list2):
set2 = set(list2)<EOL>list1_unique = [x for x in tqdm(list1, desc='<STR_LIT>', total=len(list1)) if x not in set2]<EOL>return list1_unique<EOL>
Get unique items in list1 that are not in list2 :return: Unique items only in list 1
f12069:m0
def unique_venn(list1, list2):
return unique(list1, list2), unique(list2, list1)<EOL>
Get unique items that are only in list1 and only in list2
f12069:m1
def compare_trees(dir1, dir2):
paths1 = DirPaths(dir1).walk()<EOL>paths2 = DirPaths(dir2).walk()<EOL>return unique_venn(paths1, paths2)<EOL>
Parse two directories and return lists of unique files
f12069:m2
def __init__(self, directory, filters, full_paths, pool_size, _printer):
self.directory = directory<EOL>self.filters = filters<EOL>self.pool_size = pool_size<EOL>self._printer = _printer<EOL>if self.filters:<EOL><INDENT>self._printer('<STR_LIT>')<EOL>self.explore_path = self.explore_path_filter<EOL><DEDENT>else:<EOL><INDENT>self._printer('<STR_LIT>')<EOL>self.explore_path = self.explore_path_encompass<EOL><DEDENT>self.filepaths = Manager().list()<EOL>self.unsearched = Manager().Queue()<EOL>if full_paths:<EOL><INDENT>self._printer('<STR_LIT>')<EOL>self.add_path = self._add_filepath_absolute<EOL><DEDENT>else:<EOL><INDENT>self._printer('<STR_LIT>')<EOL>self.add_path = self._add_filepath_relative<EOL><DEDENT>
DirPaths sub class for directory parsing using parallel processing.
f12070:c0:m0
def _get_root_files(self, directory):
if len(self.filepaths) is <NUM_LIT:0>:<EOL><INDENT>if self.filters:<EOL><INDENT>root_files = [(directory, f) for f in os.listdir(directory)<EOL>if os.path.isfile(os.path.join(directory, f))<EOL>and self.filters.validate(f)<EOL>and self.filters.get_level(f) == self.filters.max_level]<EOL><DEDENT>else:<EOL><INDENT>root_files = [(directory, f) for f in os.listdir(directory)<EOL>if os.path.isfile(os.path.join(directory, f))]<EOL><DEDENT>self.add_path(root_files)<EOL><DEDENT>
Retrieve files within the root directory
f12070:c0:m5
def explore_path_filter(self, task_num, dirpath):
base, path = dirpath<EOL>directories = []<EOL>nondirectories = []<EOL>if self.filters.validate(path):<EOL><INDENT>self._printer("<STR_LIT>" + str(task_num) + "<STR_LIT>" + path, stream=True)<EOL>for filename in os.listdir(base + os.sep + path):<EOL><INDENT>fullname = os.path.join(path, filename)<EOL>if self.filters.validate(fullname):<EOL><INDENT>if self.filters.non_empty_folders and self.filters.get_level(fullname) == self.filters.max_level:<EOL><INDENT>if os.path.isdir(base + os.sep + fullname):<EOL><INDENT>paths = os.listdir(base + os.sep + fullname)<EOL>if paths and any(os.path.isfile(os.path.join(base, fullname, p)) for p in paths):<EOL><INDENT>nondirectories.append((base, fullname))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if os.path.isdir(base + os.sep + fullname):<EOL><INDENT>directories.append((base, fullname))<EOL><DEDENT>elif self.filters.validate(fullname):<EOL><INDENT>nondirectories.append((base, fullname))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>self.add_path(nondirectories)<EOL><DEDENT>return directories<EOL>
Explore path to discover unsearched directories and save filepaths :param task_num: Processor ID :param dirpath: Tuple (base directory, path), path information pulled from unsearched Queue :return: Directories to add to unsearched Queue
f12070:c0:m6
def explore_path_encompass(self, task_num, dirpath):
base, path = dirpath<EOL>directories = []<EOL>nondirectories = []<EOL>self._printer("<STR_LIT>" + str(task_num) + "<STR_LIT>" + path, stream=True)<EOL>for filename in os.listdir(base + os.sep + path):<EOL><INDENT>fullname = os.path.join(path, filename)<EOL>if os.path.isdir(base + os.sep + fullname):<EOL><INDENT>directories.append((base, fullname))<EOL><DEDENT>else:<EOL><INDENT>nondirectories.append((base, fullname))<EOL><DEDENT><DEDENT>self.add_path(nondirectories)<EOL>return directories<EOL>
Explore path to discover unsearched directories and save filepaths :param task_num: Processor ID :param dirpath: Tuple (base directory, path), path information pulled from unsearched Queue :return: Directories to add to unsearched Queue
f12070:c0:m7
def parallel_worker(self, task_num):
while True:<EOL><INDENT>base, path = self.unsearched.get()<EOL>dirs = self.explore_path(task_num, (base, path))<EOL>for newdir in dirs:<EOL><INDENT>self.unsearched.put(newdir)<EOL><DEDENT>self.unsearched.task_done()<EOL><DEDENT>
Continuously pulls directories from the Queue until it is empty. Gets child directories from parent and adds them to Queue. Executes task_done() to remove directory from unsearched Queue :param task_num: Processor ID
f12070:c0:m8
def sprinter(self):
self._printer('<STR_LIT>')<EOL>for directory in self.directory:<EOL><INDENT>self._get_root_files(directory) <EOL>first_level_dirs = next(os.walk(directory))[<NUM_LIT:1>]<EOL>for path in first_level_dirs:<EOL><INDENT>self.unsearched.put((directory, path))<EOL><DEDENT><DEDENT>self._printer('<STR_LIT>')<EOL>pool = Pool(self.pool_size)<EOL>pool.map_async(self.parallel_worker, range(self.pool_size))<EOL>pool.close()<EOL>self.unsearched.join()<EOL>self._printer('<STR_LIT>')<EOL>return self.filepaths<EOL>
Called when parallelize is True. This function will generate the file names in a directory tree by adding directories to a Queue and continuously exploring directories in the Queue until Queue is emptied. Significantly faster than crawler method for larger directory trees.
f12070:c0:m9
def pool_process(func, iterable, process_name='<STR_LIT>', cpus=cpu_count()):
with Timer('<STR_LIT>'.format(process_name, str(func))):<EOL><INDENT>pool = Pool(cpus)<EOL>vals = pool.map(func, iterable)<EOL>pool.close()<EOL><DEDENT>return vals<EOL>
Apply a function to each element in an iterable and return a result list. :param func: A function that returns a value :param iterable: A list or set of elements to be passed to the func as the singular parameter :param process_name: Name of the process, for printing purposes only :param cpus: Number of CPUs :return: Result list
f12071:m0
def md5_hash(file_path):
with open(file_path, '<STR_LIT:rb>') as fp:<EOL><INDENT>return md5(fp.read()).hexdigest()<EOL><DEDENT>
Open a file path and hash the contents.
f12071:m1
def md5_tuple(file_path):
return file_path, md5_hash(file_path)<EOL>
Returns a file_path, hash tuple.
f12071:m2
def pool_hash(path_list):
return pool_process(md5_tuple, path_list, '<STR_LIT>')<EOL>
Pool process file hashing.
f12071:m3
def remover(file_path):
if os.path.isfile(file_path):<EOL><INDENT>os.remove(file_path)<EOL>return True<EOL><DEDENT>elif os.path.isdir(file_path):<EOL><INDENT>shutil.rmtree(file_path)<EOL>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>
Delete a file or directory path only if it exists.
f12071:m4
def creation_date(path_to_file, return_datetime=True):
if platform.system() == '<STR_LIT>':<EOL><INDENT>created_at = os.path.getctime(path_to_file)<EOL><DEDENT>else:<EOL><INDENT>stat = os.stat(path_to_file)<EOL>try:<EOL><INDENT>created_at = stat.st_birthtime<EOL><DEDENT>except AttributeError:<EOL><INDENT>created_at = stat.st_mtime<EOL><DEDENT><DEDENT>if return_datetime:<EOL><INDENT>return datetime.fromtimestamp(created_at)<EOL><DEDENT>else:<EOL><INDENT>return created_at<EOL><DEDENT>
Retrieve a file's creation date. Try to get the date that a file was created, falling back to when it was last modified if that isn't possible. See http://stackoverflow.com/a/39501288/1709587 for explanation. :param path_to_file: File path :param return_datetime: Bool, returns value in Datetime format :return: Creation date
f12071:m5
def creation_date_tuple(file_path):
return file_path, creation_date(file_path)<EOL>
Returns a (file_path, creation_date) tuple.
f12071:m6
def pool_creation_date(path_list):
return pool_process(creation_date_tuple, path_list, '<STR_LIT>')<EOL>
Pool process file creation dates.
f12071:m7
def __init__(self, console_output, console_stream):
self.console_output = console_output<EOL>self.console_stream = console_stream<EOL>
Printer function initialized with classes. Used for optional printing
f12071:c0:m0
def __init__(self, directory, full_paths=False, topdown=True, to_include=None, to_exclude=None,<EOL>min_level=<NUM_LIT:0>, max_level=inf, filters=None, non_empty_folders=False, parallelize=False,<EOL>pool_size=cpu_count(), console_output=False, console_stream=False, hash_files=False):
self.timer = Timer()<EOL>self.full_paths = full_paths<EOL>self.topdown = topdown<EOL>to_exclude = ['<STR_LIT>'] if to_exclude is None else to_exclude<EOL>if any(i for i in [to_include, to_exclude, filters]) or min_level != <NUM_LIT:0> or max_level != inf:<EOL><INDENT>self.filters = PathFilters(to_include, to_exclude, min_level, max_level, filters, non_empty_folders)<EOL><DEDENT>else:<EOL><INDENT>self.filters = False<EOL><DEDENT>self.console_output = console_output<EOL>self.console_stream = console_stream<EOL>self._hash_files = hash_files<EOL>self._printer = Printer(console_output, console_stream).printer<EOL>self._printer('<STR_LIT>')<EOL>if parallelize:<EOL><INDENT>self.pool_size = pool_size<EOL><DEDENT>self.parallelize = parallelize<EOL>self.filepaths = []<EOL>try:<EOL><INDENT>self.directory = [str(directory)]<EOL><DEDENT>except TypeError:<EOL><INDENT>self.directory = [str(dirs) for dirs in directory]<EOL><DEDENT>
This class generates a list of either files and or folders within a root directory. The walk method generates a directory list of files by walking the file tree top down or bottom up. The files and folders method generate a list of files or folders in the top level of the tree. :param directory: Starting directory file path :param full_paths: Bool, when true full paths are concatenated to file paths list :param topdown: Bool, when true walk method walks tree from the topdwon. When false tree is walked bottom up :param to_include: None by default. List of filters acceptable to find within file path string return :param to_exclude: None by default. List of filters NOT acceptable to return :param min_level: 0 by default. Minimum directory level to save paths from :param max_level: Infinity by default. Maximum directory level to save paths from :param parallelize: Bool, when true pool processing is enabled within walk method :param pool_size: Number of CPUs for pool processing, default is number of processors :param console_output: Bool, when true console output is printed :param console_stream: Bool, when true loops print live results :param hash_files: Bool, when true walk() method return a dictionary file_paths and hashes
f12071:c1:m0
def _get_filepaths(self):
self._printer(str(self.__len__()) + "<STR_LIT>" + str(self.timer.end))<EOL>if self._hash_files:<EOL><INDENT>return pool_hash(self.filepaths)<EOL><DEDENT>else:<EOL><INDENT>return self.filepaths<EOL><DEDENT>
Filters list of file paths to remove non-included, remove excluded files and concatenate full paths.
f12071:c1:m4
def creation_dates(self, sort=True):
if not sort:<EOL><INDENT>return pool_creation_date(self.filepaths)<EOL><DEDENT>else:<EOL><INDENT>pcd = pool_creation_date(self.filepaths)<EOL>pcd.sort(key=itemgetter(<NUM_LIT:1>), reverse=True)<EOL>return pcd<EOL><DEDENT>
Return a list of (file_path, creation_date) tuples created from list of walked paths. :param sort: Bool, sorts file_paths on created_date from newest to oldest. :return: List of (file_path, created_date) tuples.
f12071:c1:m5
def walk(self):
if self.parallelize:<EOL><INDENT>self.filepaths = Sprinter(self.directory, self.filters, self.full_paths, self.pool_size, self._printer).sprinter()<EOL><DEDENT>else:<EOL><INDENT>self.filepaths = Crawler(self.directory, self.filters, self.full_paths, self.topdown, self._printer).crawler()<EOL><DEDENT>return self._get_filepaths()<EOL>
Default file path retrieval function. sprinter() - Generates file path list using pool processing and Queues crawler() - Generates file path list using os.walk() in sequence
f12071:c1:m6
def files(self):
self._printer('<STR_LIT>')<EOL>for directory in self.directory:<EOL><INDENT>for path in os.listdir(directory):<EOL><INDENT>full_path = os.path.join(directory, path)<EOL>if os.path.isfile(full_path):<EOL><INDENT>if not path.startswith('<STR_LIT:.>'):<EOL><INDENT>self.filepaths.append(full_path)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return self._get_filepaths()<EOL>
Return list of files in root directory
f12071:c1:m7
def folders(self):
for directory in self.directory:<EOL><INDENT>for path in os.listdir(directory):<EOL><INDENT>full_path = os.path.join(directory, path)<EOL>if os.path.isdir(full_path):<EOL><INDENT>if not path.startswith('<STR_LIT:.>'):<EOL><INDENT>self.filepaths.append(full_path)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return self._get_filepaths()<EOL>
Return list of folders in root directory
f12071:c1:m8
def __init__(self, root, branches=None):
self.tree_dict = {}<EOL>self.directory = Path(root)<EOL>self.start = str(self.directory).rfind(os.sep) + <NUM_LIT:1><EOL>self.branches = branches<EOL>self.get()<EOL>
Generate a tree dictionary of the contents of a root directory. :param root: Starting directory :param branches: List of function tuples used for filtering
f12071:c2:m0
def get(self):
for path, dirs, files in os.walk(self.directory):<EOL><INDENT>folders = path[self.start:].split(os.sep)<EOL>if self.branches:<EOL><INDENT>if self._filter(folders, '<STR_LIT>'):<EOL><INDENT>files = dict.fromkeys(files)<EOL>parent = reduce(dict.get, folders[:-<NUM_LIT:1>], self.tree_dict)<EOL>parent[folders[-<NUM_LIT:1>]] = files<EOL><DEDENT><DEDENT>else:<EOL><INDENT>files = dict.fromkeys(files)<EOL>parent = reduce(dict.get, folders[:-<NUM_LIT:1>], self.tree_dict)<EOL>parent[folders[-<NUM_LIT:1>]] = files<EOL><DEDENT><DEDENT>return self.tree_dict<EOL>
Generate path, dirs, files tuple for each path in directory. Executes filters if branches are not None :return:
f12071:c2:m5
def validate(self, path):
<EOL>if os.path.basename(path).startswith('<STR_LIT:.>'):<EOL><INDENT>return False<EOL><DEDENT>if not self.check_level(path):<EOL><INDENT>return False<EOL><DEDENT>if self.filters:<EOL><INDENT>if not self._level_filters(path):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>if self.to_exclude:<EOL><INDENT>if any(str(ex).lower() in path.lower() for ex in self.to_exclude):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>if self.to_include:<EOL><INDENT>if not any(str(inc).lower() in path.lower() for inc in self.to_include):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>
Run path against filter sets and return True if all pass
f12072:c0:m5
def __init__(self, directory, filters, full_paths, topown, _printer):
self.directory = directory<EOL>self.filters = filters<EOL>self.topdown = topown<EOL>self._printer = _printer<EOL>self.filepaths = []<EOL>if full_paths:<EOL><INDENT>self.add_path = self._add_filepath_absolute<EOL>self._printer('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>self.add_path = self._add_filepath_relative<EOL>self._printer('<STR_LIT>')<EOL><DEDENT>
Sub class of DirPaths used for sequential directory parsing
f12073:c0:m0
def encompass(self):
self._printer('<STR_LIT>')<EOL>count = Counter(length=<NUM_LIT:3>)<EOL>for directory in self.directory:<EOL><INDENT>for root, directories, files in os.walk(directory, topdown=self.topdown):<EOL><INDENT>root = root[len(str(directory)) + <NUM_LIT:1>:]<EOL>self._printer(str(count.up) + "<STR_LIT>" + str(root), stream=True)<EOL>for filename in files:<EOL><INDENT>fullname = os.path.join(root, filename)<EOL>self.add_path(directory, fullname)<EOL><DEDENT><DEDENT><DEDENT>
Called when parallelize is False. This function will generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).
f12073:c0:m6
def filter(self):
self._printer('<STR_LIT>')<EOL>count = Counter(length=<NUM_LIT:3>)<EOL>for directory in self.directory:<EOL><INDENT>self._printer('<STR_LIT>' + directory)<EOL>for root, directories, files in os.walk(directory, topdown=self.topdown):<EOL><INDENT>root = root[len(str(directory)) + <NUM_LIT:1>:]<EOL>self._printer(str(count.up) + "<STR_LIT>" + str(root), stream=True)<EOL>if self.filters.validate(root):<EOL><INDENT>if self.filters.non_empty_folders and self.filters.get_level(root) == self.filters.max_level:<EOL><INDENT>if os.path.isdir(directory + os.sep + root):<EOL><INDENT>paths = os.listdir(directory + os.sep + root)<EOL>if paths and any(os.path.isfile(os.path.join(directory, p)) for p in paths):<EOL><INDENT>self.add_path(directory, root)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for filename in files:<EOL><INDENT>fullname = os.path.join(root, filename)<EOL>if self.filters.validate(fullname):<EOL><INDENT>self.add_path(directory, fullname)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>
Called when parallelize is False. This function will generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).
f12073:c0:m7
def get_version(version_file='<STR_LIT>'):
filename = os.path.join(os.path.dirname(__file__), '<STR_LIT>', version_file)<EOL>with open(filename, '<STR_LIT:rb>') as fp:<EOL><INDENT>return fp.read().decode('<STR_LIT:utf8>').split('<STR_LIT:=>')[<NUM_LIT:1>].strip("<STR_LIT>")<EOL><DEDENT>
Retrieve the package version from a version file in the package root.
f12075:m0
def application(environ, start_response):
response_body = six.b('<STR_LIT>'.format(environ['<STR_LIT>']))<EOL>response_len = len(response_body)<EOL>status = '<STR_LIT>'<EOL>response_headers = [('<STR_LIT:Content-Type>', '<STR_LIT>'),<EOL>('<STR_LIT>', str(response_len))]<EOL>start_response(status, response_headers)<EOL>return Response(<EOL>app_iter=AppIterRange([response_body], <NUM_LIT:0>, response_len), headerlist=response_headers).app_iter<EOL>
Simple application for test purposes.
f12076:m0
def raising_application(environ, start_response):
application(environ, start_response)<EOL>raise Exception()<EOL>
Application which raises an exception.
f12076:m1
def __init__(self, app, client, time_exceptions=False, separator='<STR_LIT:_>'):
self.app = app<EOL>self.statsd_client = client<EOL>self.time_exceptions = time_exceptions<EOL>self.separator = separator<EOL>
Initialize the middleware with an application and a Statsd client. :param app: The application object. :param client: `statsd.StatsClient` object. :param time_exceptions: send stats when exception happens or not, `False` by default. :type time_exceptions: bool :param separator: separator of the parts of key sent to statsd, defaults to '_' :type separator: str
f12077:c0:m0
def __call__(self, environ, start_response):
response_interception = {}<EOL>def start_response_wrapper(status, response_headers, exc_info=None):<EOL><INDENT>"""<STR_LIT>"""<EOL>response_interception.update(status=status, response_headers=response_headers, exc_info=exc_info)<EOL>return start_response(status, response_headers, exc_info)<EOL><DEDENT>start = time.time()<EOL>try:<EOL><INDENT>response = self.app(environ, start_response_wrapper)<EOL>try:<EOL><INDENT>for event in response:<EOL><INDENT>yield event<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>if hasattr(response, '<STR_LIT>'):<EOL><INDENT>response.close()<EOL><DEDENT><DEDENT>self.send_stats(start, environ, response_interception)<EOL><DEDENT>except Exception as exception:<EOL><INDENT>if self.time_exceptions:<EOL><INDENT>self.send_stats(start, environ, response_interception, exception)<EOL><DEDENT>raise<EOL><DEDENT>
Call the application and time it. :param environ: Dictionary object, containing CGI-style environment variables. :param start_response: Callable used to begin the HTTP response.
f12077:c0:m1
def get_key_name(self, environ, response_interception, exception=None):
status = response_interception.get('<STR_LIT:status>')<EOL>status_code = status.split()[<NUM_LIT:0>] <EOL>path = CHAR_RE.sub(self.separator, (environ['<STR_LIT>'].rstrip('<STR_LIT>') or '<STR_LIT:/>')[<NUM_LIT:1>:])<EOL>parts = [path, environ['<STR_LIT>'], status_code]<EOL>if exception:<EOL><INDENT>parts.append(exception.__class__.__name__)<EOL><DEDENT>return '<STR_LIT:.>'.join(parts)<EOL>
Get the timer key name. :param environ: wsgi environment :type environ: dict :param response_interception: dictionary in form {'status': '<response status>', 'response_headers': [<response headers], 'exc_info': <exc_info>} This is the interception of what was passed to start_response handler. :type response_interception: dict :param exception: optional exception happened during the iteration of the response :type exception: Exception :return: string in form '{{UNDERSCORED_PATH}}.{{METHOD}}.{{STATUS_CODE}}' :rtype: str
f12077:c0:m2
def send_stats(self, start, environ, response_interception, exception=None):
<EOL>if response_interception:<EOL><INDENT>key_name = self.get_key_name(environ, response_interception, exception=exception)<EOL>timer = self.statsd_client.timer(key_name)<EOL>timer._start_time = start<EOL>timer.stop()<EOL><DEDENT>
Send the actual timing stats. :param start: start time in seconds since the epoch as a floating point number :type start: float :param environ: wsgi environment :type environ: dict :param response_interception: dictionary in form {'status': '<response status>', 'response_headers': [<response headers], 'exc_info': <exc_info>} This is the interception of what was passed to start_response handler. :type response_interception: dict :param exception: optional exception happened during the iteration of the response :type exception: Exception
f12077:c0:m3
def initialize_options(self):
TestCommand.initialize_options(self)<EOL>self.tox_args = '<STR_LIT>'<EOL>
Initialize options and set their defaults.
f12078:c0:m0
def finalize_options(self):
TestCommand.finalize_options(self)<EOL>self.test_args = []<EOL>self.test_suite = True<EOL>
Add options to the test runner (tox).
f12078:c0:m1
@property<EOL><INDENT>def delta(self):<DEDENT>
if len(self.cache) == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>return (time.time() - self.cache[<NUM_LIT:0>])<EOL>
Time since earliest call
f12079:c0:m1
@property<EOL><INDENT>def blocked(self):<DEDENT>
self.update()<EOL>return len(self.cache) >= self.n<EOL>
Test if additional calls need to be blocked
f12079:c0:m3
def _limited(self, payload):
return any(arg in payload for arg in self._limited_args)<EOL>
Turn off bells and whistles for special API endpoints
f12079:c1:m3
def _wrap_thing(self, thing, kind):
thing['<STR_LIT>'] = self._epoch_utc_to_local(thing['<STR_LIT>'])<EOL>thing['<STR_LIT>'] = copy.deepcopy(thing)<EOL>ThingType = namedtuple(kind, thing.keys())<EOL>thing = ThingType(**thing)<EOL>return thing<EOL>
Mimic praw.Submission and praw.Comment API
f12079:c1:m5
def _add_nec_args(self, payload):
if self._limited(payload):<EOL><INDENT>return<EOL><DEDENT>if '<STR_LIT>' not in payload:<EOL><INDENT>payload['<STR_LIT>'] = self.max_results_per_request<EOL><DEDENT>if '<STR_LIT>' not in payload:<EOL><INDENT>payload['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>if '<STR_LIT>' in payload: <EOL><INDENT>if not isinstance(payload['<STR_LIT>'], list):<EOL><INDENT>if isinstance(payload['<STR_LIT>'], str):<EOL><INDENT>payload['<STR_LIT>'] = [payload['<STR_LIT>']]<EOL><DEDENT>else:<EOL><INDENT>payload['<STR_LIT>'] = list(payload['<STR_LIT>'])<EOL><DEDENT><DEDENT>if '<STR_LIT>' not in payload['<STR_LIT>']:<EOL><INDENT>payload['<STR_LIT>'].append('<STR_LIT>')<EOL><DEDENT><DEDENT>
Adds 'limit' and 'created_utc' arguments to the payload as necessary.
f12079:c1:m7
def get_env_value(name, required=False, default=empty):
if required and default is not empty:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>elif required:<EOL><INDENT>try:<EOL><INDENT>value = os.environ[name]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise KeyError(<EOL>"<STR_LIT>".format(name)<EOL>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>value = os.environ.get(name, default)<EOL><DEDENT>return value<EOL>
Core function for extracting the environment variable. Enforces mutual exclusivity between `required` and `default` keywords. The `empty` sentinal value is used as the default `default` value to allow other function to handle default/empty logic in the appropriate way.
f12091:m0
def env_int(name, required=False, default=empty):
value = get_env_value(name, required=required, default=default)<EOL>if value is empty:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>return int(value)<EOL>
Pulls an environment variable out of the environment and casts it to an integer. If the name is not present in the environment and no default is specified then a ``ValueError`` will be raised. Similarly, if the environment value is not castable to an integer, a ``ValueError`` will be raised. :param name: The name of the environment variable be pulled :type name: str :param required: Whether the environment variable is required. If ``True`` and the variable is not present, a ``KeyError`` is raised. :type required: bool :param default: The value to return if the environment variable is not present. (Providing a default alongside setting ``required=True`` will raise a ``ValueError``) :type default: bool
f12091:m1
def env_float(name, required=False, default=empty):
value = get_env_value(name, required=required, default=default)<EOL>if value is empty:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>return float(value)<EOL>
Pulls an environment variable out of the environment and casts it to an float. If the name is not present in the environment and no default is specified then a ``ValueError`` will be raised. Similarly, if the environment value is not castable to an float, a ``ValueError`` will be raised. :param name: The name of the environment variable be pulled :type name: str :param required: Whether the environment variable is required. If ``True`` and the variable is not present, a ``KeyError`` is raised. :type required: bool :param default: The value to return if the environment variable is not present. (Providing a default alongside setting ``required=True`` will raise a ``ValueError``) :type default: bool
f12091:m2
def env_bool(name, truthy_values=TRUE_VALUES, required=False, default=empty):
value = get_env_value(name, required=required, default=default)<EOL>if value is empty:<EOL><INDENT>return None<EOL><DEDENT>return value in TRUE_VALUES<EOL>
Pulls an environment variable out of the environment returning it as a boolean. The strings ``'True'`` and ``'true'`` are the default *truthy* values. If not present in the environment and no default is specified, ``None`` is returned. :param name: The name of the environment variable be pulled :type name: str :param truthy_values: An iterable of values that should be considered truthy. :type truthy_values: iterable :param required: Whether the environment variable is required. If ``True`` and the variable is not present, a ``KeyError`` is raised. :type required: bool :param default: The value to return if the environment variable is not present. (Providing a default alongside setting ``required=True`` will raise a ``ValueError``) :type default: bool
f12091:m3
def env_string(name, required=False, default=empty):
value = get_env_value(name, default=default, required=required)<EOL>if value is empty:<EOL><INDENT>value = '<STR_LIT>'<EOL><DEDENT>return value<EOL>
Pulls an environment variable out of the environment returning it as a string. If not present in the environment and no default is specified, an empty string is returned. :param name: The name of the environment variable be pulled :type name: str :param required: Whether the environment variable is required. If ``True`` and the variable is not present, a ``KeyError`` is raised. :type required: bool :param default: The value to return if the environment variable is not present. (Providing a default alongside setting ``required=True`` will raise a ``ValueError``) :type default: bool
f12091:m4
def env_list(name, separator='<STR_LIT:U+002C>', required=False, default=empty):
value = get_env_value(name, required=required, default=default)<EOL>if value is empty:<EOL><INDENT>return []<EOL><DEDENT>return list(filter(bool, [v.strip() for v in value.split(separator)]))<EOL>
Pulls an environment variable out of the environment, splitting it on a separator, and returning it as a list. Extra whitespace on the list values is stripped. List values that evaluate as falsy are removed. If not present and no default specified, an empty list is returned. :param name: The name of the environment variable be pulled :type name: str :param separator: The separator that the string should be split on. :type separator: str :param required: Whether the environment variable is required. If ``True`` and the variable is not present, a ``KeyError`` is raised. :type required: bool :param default: The value to return if the environment variable is not present. (Providing a default alongside setting ``required=True`` will raise a ``ValueError``) :type default: bool
f12091:m5
def env_timestamp(name, required=False, default=empty):
if required and default is not empty:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>value = get_env_value(name, required=required, default=empty)<EOL>if default is not empty and value is empty:<EOL><INDENT>return default<EOL><DEDENT>if value is empty:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>timestamp = float(value)<EOL>return datetime.datetime.fromtimestamp(timestamp)<EOL>
Pulls an environment variable out of the environment and parses it to a ``datetime.datetime`` object. The environment variable is expected to be a timestamp in the form of a float. If the name is not present in the environment and no default is specified then a ``ValueError`` will be raised. :param name: The name of the environment variable be pulled :type name: str :param required: Whether the environment variable is required. If ``True`` and the variable is not present, a ``KeyError`` is raised. :type required: bool :param default: The value to return if the environment variable is not present. (Providing a default alongside setting ``required=True`` will raise a ``ValueError``) :type default: bool
f12091:m6
def env_iso8601(name, required=False, default=empty):
try:<EOL><INDENT>import iso8601<EOL><DEDENT>except ImportError:<EOL><INDENT>raise ImportError(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>if required and default is not empty:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>value = get_env_value(name, required=required, default=empty)<EOL>if default is not empty and value is empty:<EOL><INDENT>return default<EOL><DEDENT>if value is empty:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>return iso8601.parse_date(value)<EOL>
Pulls an environment variable out of the environment and parses it to a ``datetime.datetime`` object. The environment variable is expected to be an iso8601 formatted string. If the name is not present in the environment and no default is specified then a ``ValueError`` will be raised. :param name: The name of the environment variable be pulled :type name: str :param required: Whether the environment variable is required. If ``True`` and the variable is not present, a ``KeyError`` is raised. :type required: bool :param default: The value to return if the environment variable is not present. (Providing a default alongside setting ``required=True`` will raise a ``ValueError``) :type default: bool
f12091:m7
def get(name, required=False, default=empty, type=None):
fn = {<EOL>'<STR_LIT:int>': env_int,<EOL>int: env_int,<EOL>'<STR_LIT:bool>': env_bool,<EOL>bool: env_bool,<EOL>'<STR_LIT:string>': env_string,<EOL>str: env_string,<EOL>'<STR_LIT:list>': env_list,<EOL>list: env_list,<EOL>'<STR_LIT>': env_timestamp,<EOL>datetime.time: env_timestamp,<EOL>'<STR_LIT>': env_iso8601,<EOL>datetime.datetime: env_iso8601,<EOL>}.get(type, env_string)<EOL>return fn(name, default=default, required=required)<EOL>
Generic getter for environment variables. Handles defaults, required-ness, and what type to expect. :param name: The name of the environment variable be pulled :type name: str :param required: Whether the environment variable is required. If ``True`` and the variable is not present, a ``KeyError`` is raised. :type required: bool :param default: The value to return if the environment variable is not present. (Providing a default alongside setting ``required=True`` will raise a ``ValueError``) :type default: bool :param type: The type of variable expected. :param type: str or type
f12091:m8
def series2df(Series, layer=<NUM_LIT:2>, split_sign = '<STR_LIT:_>'):
try:<EOL><INDENT>Series.columns<EOL>Series = Series.iloc[:,<NUM_LIT:0>]<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>def _helper(x, layer=<NUM_LIT:2>):<EOL><INDENT>try:<EOL><INDENT>return flatten_dict(ast.literal_eval(x), layers=layer, split_sign=split_sign)<EOL><DEDENT>except:<EOL><INDENT>try:<EOL><INDENT>return flatten_dict(x, layers=layer, split_sign=split_sign)<EOL><DEDENT>except:<EOL><INDENT>return x<EOL><DEDENT><DEDENT><DEDENT>df=pd.DataFrame(Series.apply(_helper).tolist())<EOL>return df<EOL>
expect pass a series that each row is string formated Json data with the same structure
f12093:m3
def load_data(self, path, *args, **kwargs):
self.df = self._load(path,*args, **kwargs)<EOL>self.series = self.df.iloc[:,<NUM_LIT:0>]<EOL>print ("<STR_LIT>" +str(self.df.shape[<NUM_LIT:0>]))<EOL>
see print instance.doc, e.g. cat=LoadFile(kind='excel') read how to use cat.load_data, exec: print (cat.doc)
f12093:c0:m1
def convert(self, layer=<NUM_LIT:2>, split_sign = '<STR_LIT:_>', *args, **kwargs):
return series2df(self.series, *args, **kwargs)<EOL>
convert data to DataFrame
f12093:c0:m2
def create_access_token(identity, user_claims=None):
jwt_manager = _get_jwt_manager()<EOL>return jwt_manager._create_access_token(identity, user_claims)<EOL>
Create a new access token. :param identity: The identity of this token, which can be any data that is json serializable. It can also be a python object :param user_claims: User made claims that will be added to this token. it should be dictionary. :return: An encoded access token
f12096:m1
def create_refresh_token(identity, user_claims=None):
jwt_manager = _get_jwt_manager()<EOL>return jwt_manager._create_refresh_token(identity, user_claims)<EOL>
Creates a new refresh token. :param identity: The identity of this token, which can be any data that is json serializable. It can also be a python object :param user_claims: User made claims that will be added to this token. it should be dictionary. :return: An encoded refresh token
f12096:m2
def get_raw_jwt():
return getattr(ctx_stack.top, '<STR_LIT>', {})<EOL>
In a protected endpoint, this will return the python dictionary which has all of the claims of the JWT that is accessing the endpoint. If no JWT is currently present, an empty dict is returned instead.
f12096:m3
def get_jwt_identity():
return get_raw_jwt().get(current_app.config['<STR_LIT>'], None)<EOL>
In a protected resolver or mutation, this will return the identity of the JWT that is accessing this endpoint. If no JWT is present,`None` is returned instead.
f12096:m4
def get_jwt_claims():
return get_raw_jwt().get(current_app.config['<STR_LIT>'], {})<EOL>
In a protected resolver or mutation, this will return the dictionary of custom claims in the JWT that is accessing the endpoint. If no custom user claims are present, an empty dict is returned instead.
f12096:m5
def __init__(self, app=None):
self.app = app<EOL>if app is not None:<EOL><INDENT>self.init_app(app)<EOL><DEDENT>
Create the GraphQLAuth instance. You can either pass a flask application in directly here to register this extension with the flask app, or call init_app after creating this object (in a factory pattern). :param app: A flask application
f12097:c0:m0
def init_app(self, app):
<EOL>if not hasattr(app, '<STR_LIT>'): <EOL><INDENT>app.extensions = {}<EOL><DEDENT>app.extensions['<STR_LIT>'] = self<EOL>self._set_default__configuration_options(app)<EOL>
Register this extension with the flask app. :param app: A flask application
f12097:c0:m1
@staticmethod<EOL><INDENT>def _set_default__configuration_options(app):<DEDENT>
app.config.setdefault('<STR_LIT>', "<STR_LIT>") <EOL>app.config.setdefault('<STR_LIT>', "<STR_LIT>")<EOL>app.config.setdefault('<STR_LIT>', datetime.timedelta(minutes=<NUM_LIT:15>))<EOL>app.config.setdefault('<STR_LIT>', datetime.timedelta(days=<NUM_LIT:30>))<EOL>app.config.setdefault('<STR_LIT>', None)<EOL>app.config.setdefault('<STR_LIT>', '<STR_LIT>')<EOL>app.config.setdefault('<STR_LIT>', '<STR_LIT>')<EOL>
Sets the default configuration options used by this extension
f12097:c0:m2
def decode_jwt(encoded_token, secret, algorithm, identity_claim_key,<EOL>user_claims_key):
<EOL>data = jwt.decode(encoded_token, secret, algorithms=[algorithm])<EOL>if '<STR_LIT>' not in data:<EOL><INDENT>raise JWTDecodeError("<STR_LIT>")<EOL><DEDENT>if identity_claim_key not in data:<EOL><INDENT>raise JWTDecodeError("<STR_LIT>".format(identity_claim_key))<EOL><DEDENT>if '<STR_LIT:type>' not in data or data['<STR_LIT:type>'] not in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise JWTDecodeError("<STR_LIT>")<EOL><DEDENT>if user_claims_key not in data:<EOL><INDENT>data[user_claims_key] = {}<EOL><DEDENT>return data<EOL>
Decodes an encoded JWT :param encoded_token: The encoded JWT string to decode :param secret: Secret key used to encode the JWT :param algorithm: Algorithm used to encode the JWT :param identity_claim_key: expected key that contains the identity :param user_claims_key: expected key that contains the user claims :return: Dictionary containing contents of the JWT
f12100:m0
def get_jwt_data(token, token_type):
jwt_data = decode_jwt(<EOL>encoded_token=token,<EOL>secret=current_app.config['<STR_LIT>'],<EOL>algorithm='<STR_LIT>',<EOL>identity_claim_key=current_app.config['<STR_LIT>'],<EOL>user_claims_key=current_app.config['<STR_LIT>']<EOL>)<EOL>if jwt_data['<STR_LIT:type>'] != token_type:<EOL><INDENT>raise WrongTokenError('<STR_LIT>'.format(token_type))<EOL><DEDENT>return jwt_data<EOL>
Decodes encoded JWT token by using extension setting and validates token type :param token: The encoded JWT string to decode :param token_type: JWT type for type validation (access or refresh) :return: Dictionary containing contents of the JWT
f12100:m1
def verify_jwt_in_argument(token):
jwt_data = get_jwt_data(token, '<STR_LIT>')<EOL>ctx_stack.top.jwt = jwt_data<EOL>
Verify access token :param token: The encoded access type JWT string to decode :return: Dictionary containing contents of the JWT
f12100:m2
def verify_refresh_jwt_in_argument(token):
jwt_data = get_jwt_data(token, '<STR_LIT>')<EOL>ctx_stack.top.jwt = jwt_data<EOL>
Verify refresh token :param token: The encoded refresh type JWT string to decode :return: Dictionary containing contents of the JWT
f12100:m3
def query_jwt_required(fn):
@wraps(fn)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>print(args[<NUM_LIT:0>])<EOL>token = kwargs.pop(current_app.config['<STR_LIT>'])<EOL>try:<EOL><INDENT>verify_jwt_in_argument(token)<EOL><DEDENT>except Exception as e:<EOL><INDENT>return AuthInfoField(message=str(e))<EOL><DEDENT>return fn(*args, **kwargs)<EOL><DEDENT>return wrapper<EOL>
A decorator to protect a query resolver. If you decorate an resolver with this, it will ensure that the requester has a valid access token before allowing the resolver to be called. This does not check the freshness of the access token.
f12100:m4
def query_jwt_refresh_token_required(fn):
@wraps(fn)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>token = kwargs.pop(current_app.config['<STR_LIT>'])<EOL>try:<EOL><INDENT>verify_refresh_jwt_in_argument(token)<EOL><DEDENT>except Exception as e:<EOL><INDENT>return AuthInfoField(message=str(e))<EOL><DEDENT>return fn(*args, **kwargs)<EOL><DEDENT>return wrapper<EOL>
A decorator to protect a query resolver. If you decorate an query resolver with this, it will ensure that the requester has a valid refresh token before allowing the resolver to be called.
f12100:m5
def mutation_jwt_required(fn):
@wraps(fn)<EOL>def wrapper(cls, *args, **kwargs):<EOL><INDENT>token = kwargs.pop(current_app.config['<STR_LIT>'])<EOL>try:<EOL><INDENT>verify_jwt_in_argument(token)<EOL><DEDENT>except Exception as e:<EOL><INDENT>return cls(AuthInfoField(message=str(e)))<EOL><DEDENT>return fn(cls, *args, **kwargs)<EOL><DEDENT>return wrapper<EOL>
A decorator to protect a mutation. If you decorate a mutation with this, it will ensure that the requester has a valid access token before allowing the mutation to be called. This does not check the freshness of the access token.
f12100:m6
def mutation_jwt_refresh_token_required(fn):
@wraps(fn)<EOL>def wrapper(cls, *args, **kwargs):<EOL><INDENT>token = kwargs.pop(current_app.config['<STR_LIT>'])<EOL>try:<EOL><INDENT>verify_refresh_jwt_in_argument(token)<EOL><DEDENT>except Exception as e:<EOL><INDENT>return cls(AuthInfoField(message=str(e)))<EOL><DEDENT>return fn(*args, **kwargs)<EOL><DEDENT>return wrapper<EOL>
A decorator to protect a mutation. If you decorate anmutation with this, it will ensure that the requester has a valid refresh token before allowing the mutation to be called.
f12100:m7
def shuffle_sattolo(items):
_randrange = random.randrange<EOL>for i in reversed(range(<NUM_LIT:1>, len(items))):<EOL><INDENT>j = _randrange(i) <EOL>items[j], items[i] = items[i], items[j]<EOL><DEDENT>
Shuffle items in place using Sattolo's algorithm.
f12107:m0
def column_list(string):
try:<EOL><INDENT>columns = list(map(int, string.split('<STR_LIT:U+002C>')))<EOL><DEDENT>except ValueError as e:<EOL><INDENT>raise argparse.ArgumentTypeError(*e.args)<EOL><DEDENT>for column in columns:<EOL><INDENT>if column < <NUM_LIT:1>:<EOL><INDENT>raise argparse.ArgumentTypeError(<EOL>'<STR_LIT>'<EOL>.format(column))<EOL><DEDENT><DEDENT>return columns<EOL>
Validate and convert comma-separated list of column numbers.
f12107:m1
def get_model_class( klass, api = None, use_request_api = True):
if api is None and use_request_api:<EOL><INDENT>api = APIClient()<EOL><DEDENT>_type = klass<EOL>if isinstance(klass, dict):<EOL><INDENT>_type = klass['<STR_LIT:type>']<EOL><DEDENT>schema = loaders.load_schema_raw(_type)<EOL>model_cls = model_factory(schema, base_class = RemoteResource)<EOL>model_cls.__api__ = api<EOL>return model_cls<EOL>
Generates the Model Class based on the klass loads automatically the corresponding json schema file form schemes folder :param klass: json schema filename :param use_request_api: if True autoinitializes request class if api is None :param api: the transportation api if none the default settings are taken an instantiated
f12110:m0
def validate(self, data):
try:<EOL><INDENT>schema_path = os.path.normpath(SCHEMA_ROOT)<EOL>location = u'<STR_LIT>' % (schema_path)<EOL>fs_resolver = resolver.LocalRefResolver(location, self.schema)<EOL>jsonschema.Draft3Validator(self.schema, resolver=fs_resolver).validate(data)<EOL><DEDENT>except jsonschema.ValidationError as exc:<EOL><INDENT>raise jsonschema.exceptions.ValidationError(str(exc))<EOL><DEDENT>
Apply a JSON schema to an object
f12110:c0:m0
def _pre_save(self, *args, **kwargs):
pass<EOL>
pre save hook
f12110:c1:m3
def _post_save(self, response, *args, **kwargs):
return response<EOL>
post save hook
f12110:c1:m4
def save(self, *args, **kwargs):
self._pre_save(*args, **kwargs)<EOL>response = self._save(*args, **kwargs)<EOL>response = self._post_save(response, *args, **kwargs)<EOL>return response<EOL>
saves creates or updates current resource returns new resource
f12110:c1:m5
def _pre_load(self, id, *args, **kwargs):
pass<EOL>
pre load hook
f12110:c1:m6
def _post_load(self, response, *args, **kwargs):
return response<EOL>
post laod hook
f12110:c1:m7
def load(self, id, *args, **kwargs):
self._pre_load(id, *args, **kwargs)<EOL>response = self._load(id, *args, **kwargs)<EOL>response = self._post_load(response, *args, **kwargs)<EOL>return response<EOL>
loads a remote resource by id
f12110:c1:m8
def _pre_delete(self, *args,**kwargs):
pass<EOL>
pre delete hook
f12110:c1:m9
def _post_delete(self, response, *args, **kwargs):
return response<EOL>
post delete hook
f12110:c1:m10
def delete(self, *args, **kwargs):
self._pre_delete(*args, **kwargs)<EOL>response = self._delete(*args, **kwargs)<EOL>response = self._post_delete(response, *args, **kwargs)<EOL>return response<EOL>
deletes current resource returns response from api
f12110:c1:m11
def get_id(self):
id = None<EOL>try:<EOL><INDENT>id = self.__getattr__(u'<STR_LIT:id>')<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>return id<EOL>
Model may have an unset id id is used to determine if it is a save or update
f12110:c2:m0
def to_json(self):
data = json.dumps(self)<EOL>out = u'<STR_LIT>' % (self.schema['<STR_LIT:title>'], data)<EOL>return out<EOL>
put the object to json and remove the internal stuff salesking schema stores the type in the title
f12110:c2:m2
def _do_api_call(self, call_type=u'<STR_LIT>', id = None):
endpoint = None<EOL>url = None<EOL>if call_type == u'<STR_LIT>':<EOL><INDENT>endpoint = self.get_endpoint("<STR_LIT>")<EOL>if id is None:<EOL><INDENT>raise APIException("<STR_LIT>", "<STR_LIT>")<EOL><DEDENT><DEDENT>elif call_type == u'<STR_LIT>' or (call_type == u"<STR_LIT>"):<EOL><INDENT>endpoint = self.get_endpoint("<STR_LIT>")<EOL>if id is None:<EOL><INDENT>raise APIException("<STR_LIT>", "<STR_LIT>")<EOL><DEDENT><DEDENT>elif call_type == u'<STR_LIT>':<EOL><INDENT>endpoint = self.get_endpoint("<STR_LIT>")<EOL>if id is None:<EOL><INDENT>raise APIException("<STR_LIT>", "<STR_LIT>")<EOL><DEDENT><DEDENT>elif call_type == u'<STR_LIT>':<EOL><INDENT>endpoint = self.get_endpoint("<STR_LIT>")<EOL>url = u"<STR_LIT>" % (self.__api__.base_url, API_BASE_PATH, endpoint['<STR_LIT>'])<EOL><DEDENT>elif call_type == u'<STR_LIT>':<EOL><INDENT>endpoint = self.get_endpoint("<STR_LIT>")<EOL>url = u"<STR_LIT>" % (self.__api__.base_url, API_BASE_PATH, endpoint['<STR_LIT>'])<EOL>endpoint['<STR_LIT>'] = u'<STR_LIT:GET>' <EOL><DEDENT>if id is not None:<EOL><INDENT>url = u"<STR_LIT>" % (self.__api__.base_url, API_BASE_PATH, endpoint['<STR_LIT>'].replace(u"<STR_LIT>",id))<EOL><DEDENT>payload = self.to_json()<EOL>if u'<STR_LIT>' in endpoint.keys():<EOL><INDENT>method = endpoint['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>method = u'<STR_LIT:GET>'<EOL><DEDENT>obj = None<EOL>try:<EOL><INDENT>msg = u"<STR_LIT>" % (url, method, payload)<EOL>response = self.__api__.request(url, method, data=payload)<EOL>if ((response.status_code == <NUM_LIT:200> and <EOL>call_type in ['<STR_LIT>', '<STR_LIT>']) or<EOL>(response.status_code == <NUM_LIT> and call_type == '<STR_LIT>')):<EOL><INDENT>msg = "<STR_LIT>" % call_type<EOL>log.info(msg)<EOL>return self.to_instance(response)<EOL><DEDENT>elif (response.status_code == <NUM_LIT:200> and call_type in ['<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>msg ="<STR_LIT>" % call_type<EOL>log.info(msg)<EOL>return self._try_to_serialize(response)<EOL><DEDENT>elif <NUM_LIT:200> <= response.status_code <= <NUM_LIT>:<EOL><INDENT>return self._try_to_serialize(response)<EOL><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>msg = "<STR_LIT>" % (e, url)<EOL>log.error(msg)<EOL>raise e<EOL><DEDENT>
returns a response if it is a valid call otherwise the corresponding error
f12110:c3:m5
def to_instance(self, response):
klass = self.schema['<STR_LIT:title>']<EOL>cls = get_model_class(klass, api=self.__api__)<EOL>jdict = json.loads(response.content, encoding="<STR_LIT:utf-8>")<EOL>properties_dict = jdict[self.schema['<STR_LIT:title>']]<EOL>new_dict = helpers.remove_properties_containing_None(properties_dict)<EOL>obj = cls(new_dict)<EOL>return obj<EOL>
transforms the content to a new instace of object self.schema['title'] :param content: valid response :returns new instance of current class
f12110:c3:m6
def dict_to_instance(self, content):
klass = self.schema['<STR_LIT:title>']<EOL>cls = get_model_class(klass, api=self.__api__)<EOL>properties_dict = content[self.schema['<STR_LIT:title>']][self.schema['<STR_LIT:title>']]<EOL>new_dict = helpers.remove_properties_containing_None(properties_dict)<EOL>obj = cls(new_dict)<EOL>return obj<EOL>
transforms the content to a new instace of object self.schema['title'] :param content: valid response :returns new instance of current class
f12110:c3:m7
def setUp(self):
super(LiveInvoiceCollectionBaseTestCase,self).setUp()<EOL>self.api_client = api.APIClient()<EOL>
this test is slow as it gets over the air creates 201 resources of client named fb-counter if they do not exist
f12112:c0:m0
def setUp(self):
super(LiveCollectionBaseTestCase,self).setUp()<EOL>self.api_client = api.APIClient()<EOL>valid_filters = {"<STR_LIT>": self.org_name_token}<EOL>col = collection.get_collection_instance("<STR_LIT>")<EOL>col.set_filters(valid_filters)<EOL>col.load()<EOL>items_per_page_cnt = col.get_per_page()<EOL>self.total_pages = col.get_total_pages()<EOL>total_entries = col.get_total_entries()<EOL>current_page = col.get_current_page()<EOL>msg = u"<STR_LIT>" % (<EOL>valid_filters, items_per_page_cnt, self.total_pages, total_entries, current_page)<EOL>if total_entries <= <NUM_LIT>:<EOL><INDENT>model = resources.get_model_class("<STR_LIT>", api=self.api_client)<EOL>for x in xrange(total_entries, <NUM_LIT>):<EOL><INDENT>self.valid_data["<STR_LIT>"] = "<STR_LIT>" % (self.org_name_token, x)<EOL>client = model(self.valid_data)<EOL>client = client.save()<EOL><DEDENT><DEDENT>
this test is slow as it gets over the air creates 201 resources of client named fb-counter if they do not exist
f12116:c0:m0
def _check_schema_file_content_for_reference_to_json(fs):
"""<STR_LIT>"""<EOL>seek = "<STR_LIT>"<EOL>if fs.find(seek) != -<NUM_LIT:1>:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
checks file contents fs for .json :param fs: :return: True/False
f12126:m0