def render_POST(self, request): try: postData = request.content.read() unpacker = json.loads(postData) logging.debug('fed data to unpacker') for msg in unpacker: logging.debug('found message in unpacker') if type(msg) == dict: logging.debug('found object in message') msg['hash'] = ErrorHasher(msg).get_hash() if 'timestamp' not in msg: msg['timestamp'] = int(time()) Error.validate_and_upsert(msg) logging.debug('saved error') ErrorInstance.from_raw(msg).save(safe=False) HourlyOccurrence.from_msg(msg) DailyOccurrence.from_msg(msg) logging.debug('saved instance') except Exception, a: logging.exception('Failed to process error') logging.info(postData) return 'FAILED';
def get_posts(): limit = int(request.args.get('limit')) offset = int(request.args.get('offset')) sort_order = request.args.get('sortOrder') sort_direction = request.args.get('sortDirection') if limit <= 0: error = Error('Limit must be greater than 0') return Response(jsonpickle.encode(error, unpicklable=False), 400, content_type='application/json') if offset < 0: error = Error('Offset must be greater or equal than 0') return Response(jsonpickle.encode(error, unpicklable=False), 400, content_type='application/json') if sort_direction == 'asc': sort_order = '+' + sort_order else: sort_order = '-' + sort_order post_list = get_post_list(limit, offset, sort_order) return Response(jsonpickle.encode(post_list, unpicklable=False), 200, content_type='application/json')
def get_posts_by_tag(tag): tag_doc = find_tag_by_slug(tag) if tag_doc is None: error = Error('Tag with slug {} not found!'.format(tag)) return Response(jsonpickle.encode(error, unpicklable=False), 404, content_type='application/json') limit = int(request.args.get('limit')) offset = int(request.args.get('offset')) sort_order = request.args.get('sortOrder') sort_direction = request.args.get('sortDirection') if limit <= 0: error = Error('Limit must be greater than 0') return Response(jsonpickle.encode(error, unpicklable=False), 400, content_type='application/json') if offset < 0: error = Error('Offset must be greater or equal than 0') return Response(jsonpickle.encode(error, unpicklable=False), 400, content_type='application/json') if sort_direction == 'asc': sort_order = '+' + sort_order else: sort_order = '-' + sort_order post_list = get_post_list_by_tag(tag_doc, limit, offset, sort_order) return Response(jsonpickle.encode(post_list, unpicklable=False), 200, content_type='application/json')
def __init__(self, req_data): """ Create term object from an http request body's req_data. If any errors occur in creating the Term object, they will be attached to the errors dictionary :param req_data: the http request body as a dictionary """ super().__init__() # Initally assume the data has a year and semester, # change to False otherwise. data_has_year = True data_has_semester = True # Grab the semester if it's in the request try: semester_type = req_data["term"] except KeyError: error = Error("term", "term is required") self.add_error(ErrorTypes.MISSING_PARAM, error) data_has_semester = False # Grab the year if it's in the request try: year = req_data["year"] except KeyError: data_has_year = False error = Error("year", "year is required") self.add_error(ErrorTypes.MISSING_PARAM, error) if data_has_year: # Make sure the year is an integer try: self.year = int(year) except ValueError: error = Error("year", "year must be integer") self.add_error(ErrorTypes.BAD_DATA, error) if data_has_semester: # Make sure the semester type is valid try: self.semester_type = SemesterTypes(semester_type) except ValueError: error = Error("term", "semester not valid") self.add_error(ErrorTypes.BAD_DATA, error)
def post(self): theJsonRequest = json.loads(self.request.body) theErrorCodeId = theJsonRequest["errorCodeId"] theErrorDescription = theJsonRequest["description"] theErrorLongDescription = theJsonRequest["longDescription"] anError = Error( key_name=str(theErrorCodeId), errorCodeId=theErrorCodeId, description=theErrorDescription, longDescription=theErrorLongDescription, ) anError.put() self.response.headers["Content-Type"] = "application/json" theJsonResponse = {"result": 0, "message": "Error agregado correctamente"} self.response.out.write(json.dumps(theJsonResponse))
def addExecutionError(self, noType, errorType, desc, line, column): numberError, description = get_type_error(noType) self._idExecutionError += 1 description += desc self._executionErrorList.append(Error(self._idExecutionError, errorType, numberError, description, line, column))
def delete(self): for anError in Error.all().fetch(None): anError.delete() self.response.headers["Content-Type"] = "application/json" theJsonResponse = {"result": 0, "message": "Error eliminados correctamente"} self.response.out.write(json.dumps(theJsonResponse))
def pending_list(role, email): if role == "admin": pending_object = admin.Pending.objects(status=False) pending_data = OrderedDict() pending_data_tmp = list() admin_object = admin.Admin.objects(email=email).first() for tmp_object in pending_object: if int(admin_object.amount) >= int(tmp_object.amount): tmp_data = OrderedDict() tmp_data["pk"] = str(tmp_object.pk) tmp_data["email"] = tmp_object.email tmp_data["to"] = tmp_object.to tmp_data["amount"] = tmp_object.amount pending_data_tmp.append(tmp_data) pending_data["data"] = pending_data_tmp pending_data["length"] = len(pending_data_tmp) return jsonify({ "success": True, "msg": "Get pending list successfully.", "data": json.dumps(pending_data, ensure_ascii=False) }) else: return Error.permission_deny()
def add(self, noType, type, desc, line, column): numberError, description = get_type_error(noType) self._idError += 1 description += desc self._errorsList.append( Error(self._idError, type, numberError, description, line, column))
def returnObjectOrResult(self, resultCode, objectToReturn=None, encoderForObject=None): self.response.headers["Content-Type"] = "application/json" if objectToReturn is None or (isinstance(objectToReturn, list) and len(objectToReturn) == 0): errorResult = Error.get_by_key_name(resultCode) return ErrorEncoder().encode(errorResult) else: return encoderForObject.encode(objectToReturn)
def register(): try: email = str(request.form['email']) password = str( app.bcrypt.generate_password_hash(request.form['password'])) phone = request.form['phone'].replace("-", "") try: airdrop = request.form['airdrop'] except Exception as e: print(e) airdrop = "" auth.User(email=email, password=password, phone=phone, airdrop=airdrop).save() return jsonify({ "success": True, "msg": "successful created new user", "wallet": "", "accessToken": app.create_access_token(identity={ "email": email, "wallet": "" }) }), 200 except Exception as e: print(e) return Error.id_or_phone_overlapped()
def get_detail_post(category, post): category_doc = find_category_by_slug(category) if category_doc is None: error = Error('Category with slug {} not found!'.format(category)) return Response(jsonpickle.encode(error, unpicklable=False), 404, content_type='application/json') post_detail = get_post_detail(category_doc, post) if post_detail is None: error = Error('Post with slug {} not found!'.format(post)) return Response(jsonpickle.encode(error, unpicklable=False), 404, content_type='application/json') else: return Response(jsonpickle.encode(post_detail, unpicklable=False), 200, content_type='application/json')
def get(self, errorId): theErrorToReturn = Error.get_by_key_name(errorId) self.response.headers["Content-Type"] = "application/json" if theErrorToReturn is None: theJsonResponse = {} else: theJsonResponse = theErrorToReturn.__dict__["_entity"] self.response.out.write(json.dumps(theJsonResponse))
def add(self, noType, errorType, desc, line, column): numberError, description = get_type_error(noType) self._idError += 1 description += desc self._errorsList.append( Error(self._idError, errorType, numberError, description, line, column)) DataWindow().consoleTable(['Code', 'Description'], [[self._idError, description]])
def login(): email = str(request.form['email']) password = str(request.form['password']) master_object = admin.Master.objects(email=email) if len(master_object) == 0: return Error.invalid_input() else: if app.bcrypt.check_password_hash(str(master_object[0].password), password): return jsonify({ "success": True, "type": "master", "accessToken": app.create_access_token(identity={"role": "master"}) }), 200 else: return Error.wrong_password()
def register(role): if role == "master": try: email = str(request.form['email']) password = str( app.bcrypt.generate_password_hash( request.form['password'])) amount = str(request.form['amount']) admin.Admin(email=email, password=password, amount=amount).save() return jsonify({ "success": True, "msg": "successful created new admin user" }), 200 except Exception as e: print(e) return Error.id_overlapped() else: return Error.permission_deny()
def login(): email = str(request.form['email']) password = str(request.form['password']) user_object = admin.Admin.objects(email=email) if len(user_object) == 0: return Error.user_not_found() else: if app.bcrypt.check_password_hash(eval(user_object[0].password), password): return jsonify({ "success": True, "accessToken": app.create_access_token(identity={ "role": "admin", "email": user_object[0].email }) }), 200 else: return Error.wrong_password()
def add(self, noType, errorType, desc, line, column): numberError, description = get_type_error(noType) self._idError += 1 description += f": {desc}" description = ' '.join(description.split()) description = description.replace(': :', ':') self._errorsList.append( Error(self._idError, errorType, numberError, description, line, column)) DataWindow().consoleTable(['Code', 'Description'], [[numberError, description]])
def get_posts_by_category(category): category_doc = find_category_by_slug(category) if category_doc is None: error = Error('Category with slug {} not found!'.format(category)) return Response(jsonpickle.encode(error, unpicklable=False), 404, content_type='application/json') limit = int(request.args.get('limit')) offset = int(request.args.get('offset')) sort_order = request.args.get('sortOrder') sort_direction = request.args.get('sortDirection') if limit <= 0: error = Error('Limit must be greater than 0') return Response(jsonpickle.encode(error, unpicklable=False), 400, content_type='application/json') if offset < 0: error = Error('Offset must be greater or equal than 0') return Response(jsonpickle.encode(error, unpicklable=False), 400, content_type='application/json') if sort_direction == 'asc': sort_order = '+' + sort_order elif sort_direction == 'desc': sort_order = '-' + sort_order else: error = Error('Sort direction must be equal "asc" or "desc"') return Response(jsonpickle.encode(error, unpicklable=False), 400, content_type='application/json') post_list = get_post_list_by_category(category_doc, limit, offset, sort_order) return Response(jsonpickle.encode(post_list, unpicklable=False), 200, content_type='application/json')
def put(self, errorId): theJsonRequest = json.loads(self.request.body) theErrorDescription = theJsonRequest["description"] theErrorLongDescription = theJsonRequest["longDescription"] theErrorToUpdate = Error.get_by_key_name(errorId) theErrorToUpdate.description = theErrorDescription theErrorToUpdate.longDescription = theErrorLongDescription theErrorToUpdate.put() self.response.headers["Content-Type"] = "application/json" theJsonResponse = {"result": 0, "message": "Error modificado correctamente"} self.response.out.write(json.dumps(theJsonResponse))
def balance(role): if role == "admin": email = request.form['email'] atcg_balance = ATCG_func().balance(email=email) eth_balance = ETH().balance(email=email) return jsonify({ "success": True, "msg": "Get user balance successfully.", "atcg": atcg_balance, "eth": eth_balance }), 200 else: return Error.permission_deny()
def register(): try: email = "email" password = "******" password = app.bcrypt.generate_password_hash(password) admin.Master(email=email, password=password).save() return jsonify({ "success": True, }), 200 except Exception as e: print(e) return Error.unexpected_error()
def pending_deny(role): if role == "admin": try: admin.Pending.objects( pk=str(request.form["pk"])).first().delete() return jsonify({ "success": True, "msg": "Ticket deny successfully." }), 200 except Exception as e: print(e) return jsonify({"success": False, "msg": "Ticket Rejected"}) else: return Error.permission_deny()
def login(): email = str(request.form['email']) password = str(request.form['password']) user_object = auth.User.objects(email=email) if len(user_object) == 0: return Error.invalid_input() else: if app.bcrypt.check_password_hash(eval(user_object[0].password), password): return jsonify({ "success": True, "wallet": user_object[0].wallet, "accessToken": app.create_access_token( identity={ "email": user_object[0].email, "wallet": user_object[0].wallet }) }), 200 else: return Error.wrong_password()
def t_error(t): global list_errors global input global id_error id_error = list_errors.count + 1 if list_errors.count > 0 else 1 description = f'Caracter Desconocido {t.value[0]}' column = find_column(t) print(f"The character {t.value[0]} ilegal, {t.lexer.lineno} {find_column(t)}") list_errors.insert_end(Error(id_error, 'Lexical', description, t.lexer.lineno, column)) id_error += 1 t.lexer.skip(1)
def search(): email = str(request.form['email']) user_object = db_auth.User.objects(email=email) if len(user_object) == 0: return Error.cant_find() else: user_object = db_auth.User.objects(email=email).first() profile = user_object.profile name = user_object.name return jsonify({ "success": True, "data": { "name": name, "profile": profile } }), 200
def t_error(t): global list_errors global input global id_error id_error = list_errors.count + 1 if list_errors.count > 0 else 1 SQLERROR = FindTypeError('Lexical') number_error, description = SQLERROR.find_type_error() description += ' or near ' + str(t.value[0]) column = find_column(t) print( f"The character {t.value[0]} ilegal, {t.lexer.lineno} {find_column(t)}" ) list_errors.insert_end( Error(id_error, 'Lexical', number_error, description, t.lexer.lineno, column)) id_error += 1 t.lexer.skip(1)
def add(): my_email = app.get_jwt_identity()["email"] add_email = str(request.form['email']) user_object = db_auth.User.objects(email=my_email) if len(user_object) == 0: return Error.invalid_input() else: add_object = db_auth.User.objects(email=add_email) if len(add_object) == 0: return jsonify({ "success": False, "msg": "fail to find added user" }) else: user_object = user_object.first() user_object.friends.append(add_email) user_object.save() return jsonify({ "success": True, "msg": "add new friend at list" }), 200
def pending_accept(role): if role == "admin": try: pending_object = admin.Pending.objects( pk=str(request.form["pk"])).first() response, response_code = ATCG_func().transfer( email=pending_object.email, to=pending_object.to, amount=pending_object.amount) pending_object.status = True pending_object.save() return response, response_code except Exception as e: print(e) return jsonify({ "success": False, "msg": "Ticket Rejected" }), 200 else: return Error.permission_deny()
def list(role): if role == "admin": user_objects = auth.User.objects() user_list = OrderedDict() user_list_tmp = list() for user_object in user_objects: tmp_data = OrderedDict() tmp_data["email"] = user_object.email tmp_data["phone"] = user_object.phone tmp_data["wallet"] = user_object.wallet tmp_data["airdrop"] = user_object.airdrop user_list_tmp.append(tmp_data) user_list["data"] = user_list_tmp user_list["length"] = len(user_list_tmp) return jsonify({ "success": True, "msg": "Get pending list successfully.", "data": json.dumps(user_list, ensure_ascii=False) }), 200 else: return Error.permission_deny()
def get_certificate(fqdn): # noqa: E501 """API that get server certificate server certificate of the domain which specified in fqdn. # noqa: E501 :param fqdn: FQDN of certificate to get :type fqdn: str :rtype: Certificate """ with LOCK: try: target_Certificate = Certificate() error_message = Error() # path cert_path = '/etc/letsencrypt/live/' + fqdn + '/cert.pem' fullchain_path = '/etc/letsencrypt/live/' + fqdn + '/fullchain.pem' key_path = '/etc/letsencrypt/live/' + fqdn + '/privkey.pem' # get certificate if not exist if not os.path.exists('/etc/letsencrypt/live/' + fqdn): args = [ 'certbot', '--agree-tos', '--text', '--renew-by-default', '-n', '--no-eff-email', '--authenticator', 'certbot-pdns:auth', 'certonly', '-d', fqdn ] if 'CERTBOT_EMAIL' in os.environ: args += ['-m', os.environ['CERTBOT_EMAIL']] proc = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # noqa: E501 logger.info(f'{proc.stdout.decode()}') if proc.returncode != 0: logger.error( f'error occur in certbot new: {proc.stderr.decode()}' ) # noqa: E501 error_message.message = f'error occur in certbot new: {proc.stderr.decode()}' # noqa: E501 return error_message, 500 + int(proc.returncode) # get certificate and assign value with open(cert_path, 'r') as cert_file: cert = cert_file.read() target_Certificate.cert = cert with open(fullchain_path, 'r') as fullchain_file: fullchain = fullchain_file.read() target_Certificate.fullchain = fullchain with open(key_path, 'r') as key_file: privkey = key_file.read() target_Certificate.privkey = privkey mtime = datetime.datetime.fromtimestamp( os.stat(cert_path).st_mtime) target_Certificate.mtime = mtime return target_Certificate except Exception as e: logger.exception(e) error_message.message = e return error_message, 501
def errorFromDBHook(self, dictionary): return Error.get_by_key_name(dictionary['errorCodeId'])
def get(self): listOfErrors = Error.all().fetch(None) self.response.headers["Content-Type"] = "application/json" theJsonResponse = map(lambda o: o.__dict__["_entity"], listOfErrors) self.response.write(json.dumps(theJsonResponse))
unpacker = msgpack.Unpacker() # serve! logging.info('Serving!') while True: try: data = socket.recv() logging.debug('received data') unpacker.feed(data) logging.debug('fed data to unpacker') for msg in unpacker: logging.debug('found message in unpacker') if type(msg) == dict: logging.debug('found object in message') msg['hash'] = ErrorHasher(msg).get_hash() if 'timestamp' not in msg: msg['timestamp'] = int(time()) Error.validate_and_upsert(msg) logging.debug('saved error') ErrorInstance.from_raw(msg).save(safe=False) HourlyOccurrence.from_msg(msg) DailyOccurrence.from_msg(msg) logging.debug('saved instance') except Exception, a: logging.exception('Failed to process error')