def parse(self, field, field_type, nullable=False, length=float("inf")): is_dict = self.type == dict data_request = self.data_request if is_dict: value = data_request.get(field) if not nullable and not value: msg = { "message": 'field {} it\'s can\'t be null'.format(field) } abort(result(msg, 400)) wrong_type = type(value) != field_type wrong_len = len(str(value)) > length if wrong_type: msg = { "message": 'field {} it\'s must be {}'.format(field, field_type) } abort(result(msg, 400)) if wrong_len: msg = { "message": 'length of filed {} can\'t over {}'.format(field, length) } abort(result(msg, 400)) self.__parsed.update({field: value})
def programRun(): move = rps.get() if result(move)['status'] != 200: v.set(result(move)['reason']) else: v.set(result(move)['result'].capitalize()) if result(move)['status'] != 200: score.set(result(move)['reason']) else: score.set( f"Yours: {result(move)['user_score']}\nMine: {result(move)['client_score']}" ) rps.delete(0, END) rps.insert(0, "")
def main(secrets): x = core.runSystemCommand([ "rclone", "sync", "/media/hdd2/content", "Barry:", "-v", "--stats=10m" ]) return core.result(log=x.stdout, success=x.returncode == 0, subject="Remote Backup")
def register(data): user = User( username=data['username'], email=data['email'], password=data['password'] ) user.add() return result({'data': 'success register'}, 200)
def index(): data = parser.ValueChecker(request.json) data.parse('username', field_type=str, length=30) data.parse('email', field_type=str, length=30) data.parse('password', field_type=str, length=30) if method_is('POST'): return register(data.parse()) return result(data.get_parsed(), 210)
def main(secrets): x = core.runSystemCommand([ "rsync", "-ahv", "--delete", "--backup", "--backup-dir=/media/hdd2/backup/backup_{}".format(date.today()), "/media/hdd/content/", "/media/hdd2/content/" ]) return core.result(log=x.stdout, success=x.returncode == 0, subject="Local Backup")
def main(secrets): x = core.runSystemCommand(["df", "-h"]) return core.result(log=x.stdout, success=x.returncode == 0, subject="Usage Report")
def main(secrets): logger.info("Starting sync_github") REPO_REMOTE = "[email protected]:gowerc/{repo}.git" REPO_DIR = "/media/hdd2/GitHub" REPO_EXISTING = os.listdir(REPO_DIR) headers = {"Authorization": "token {t}".format(t=secrets["githubToken"])} resp = requests.get( url="https://api.github.com/search/repositories?q=user:gowerc", headers=headers) resp.raise_for_status() repo_obj = resp.json()["items"] repos = [i["name"] for i in repo_obj] logger.info("Found repos " + ",".join(repos)) PROC_CLONE = [] PROC_PULL = [] for repo in repos: repo_remote = REPO_REMOTE.format(repo=repo) repo_dir = REPO_DIR + "/" + repo logger.info("Dealing with " + repo) if repo not in REPO_EXISTING: proc = subprocess.run(["git", "clone", repo_remote], check=False, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, cwd=REPO_DIR) PROC_CLONE.append({ "repo": repo, "returncode": proc.returncode, "stdout": proc.stdout }) proc = subprocess.run(["git", "pull", "--all"], check=False, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, cwd=repo_dir) PROC_PULL.append({ "repo": repo, "returncode": proc.returncode, "stdout": proc.stdout }) PROC_ALL = PROC_CLONE + PROC_PULL stdout = "\n".join([ "repopisitory = " + i["repo"] + "\n" + i["stdout"].decode("utf-8") + "\n" for i in PROC_ALL ]) status = all([i["returncode"] == 0 for i in PROC_ALL]) return core.result(log=stdout, success=status, subject="GitHub Sync")
ch.setFormatter(formatter) logger.addHandler(ch) return logger if __name__ == "__main__": set_logger() root = os.path.dirname(os.path.realpath(__file__)) secrets = core.get_secrets(root) arg = sys.argv[1] try: assert core.is_hdd_reachable("hdd") and core.is_hdd_reachable("hdd2") module = importlib.import_module("core." + arg) results = module.main(secrets) except Exception as e: results = core.result(log=str(e), success=False, subject=arg) result_string = "Success" if results.success else "Failure" if results.log: tf = tempfile.NamedTemporaryFile(suffix='.txt') tf.write(results.log) tf.seek(0) FILES = [tf.name] else: FILES = [] core.send_mail(send_to=[secrets["emailAddressTo"]], send_from=secrets["emailAddressFrom"], pwd=secrets["emailPassword"], subject=results.subject + " - " + result_string,
def parse(self, field, field_type, nullable=False, length=float("inf"), enum=None, unique_from_model=None): is_dict = self.type == dict data_request = self.data_request if isinstance(None, self.type): if not nullable: msg = {"message": 'you have to set a data'} abort(result(msg, 400)) return self.__parsed.update({field: None}) if enum != None and type(enum) != list: raise ValueError("enum must be list, for '{}' field".format(field)) if unique_from_model != None: must_field = {'model', 'field'} if type(unique_from_model) != dict: raise ValueError( "unique_from_model must be dict, for '{}' field".format( field)) if must_field != set(unique_from_model.keys()): raise ValueError("key must be {} for '{}' field".format( must_field, field)) if len(unique_from_model.keys()) != 2: raise ValueError( "expected {} keys, and we got {} keys, for '{}' field". format(len(must_field), len(unique_from_model.keys()), field)) if is_dict: value = data_request.get(field) if enum: if value not in enum: msg = {"message": 'value error for field {}'.format(field)} abort(result(msg, 400)) if unique_from_model: model = unique_from_model['model'] model_field = unique_from_model['field'] if hasattr(model, model_field): obj_model = getattr(getattr(model, 'query'), 'filter')( getattr(model, model_field) == value).first() if obj_model: msg = { "message": '{} with {}={} is already exist'.format( model.__tablename__, model_field, value) } abort(result(msg, 400)) if not nullable: if isinstance(None, type(value)): msg = { "message": 'field {} it\'s can\'t be null'.format(field) } abort(result(msg, 400)) else: if isinstance(None, type(value)): return self.__parsed.update({field: value}) if field_type == date: try: value = datetime.strptime(value, "%d-%m-%Y").date() wrong_type = False wrong_len = False except: msg = { "message": 'for field {} date type format must be : dd-mm-yyyy'. format(field) } abort(result(msg, 400)) else: wrong_type = type(value) != field_type wrong_len = len(str(value)) > length if wrong_type: msg = { "message": 'field {} it\'s must be {}'.format(field, field_type) } abort(result(msg, 400)) if wrong_len: msg = { "message": 'length of filed {} can\'t over {}'.format(field, length) } abort(result(msg, 400)) self.__parsed.update({field: value})