def json_abort(status_code, message="", exception=None): if exception: # If the exception is already of type HTTPException, meaning from previous call to abort # collect the message and simply raise the abort again(do not call abort again, only reraise) if isinstance(exception, HTTPException): try: res = json.loads(exception.get_response().get_data().decode()) status_code = res.get('code') message = res.get('message') except Exception: logger.exception('Invalid response format') raise # To reraise the exception thrown from abort(..) call below else: # Note that if not isinstance(exception, HTTPException), then I simply have an exception, # meaning I should call abort, but before, remember, I'm inside except block # so I should call logger.exception, note that if isinstance(exception, HTTPException) # for now I simply want an info. logger.exception(message) else: logger.error('json_abort, no exception, message: ' + message) # We always want here call to abort abort( make_response(jsonify({ "message": message, "code": status_code }), status_code))
def exceptions(e): ts = strftime('[%Y-%b-%d %H:%M]') tb = traceback.format_exc() error = '{} {} {} {} {} {} 5xx INTERNAL SERVER ERROR\n{}'.format( ts, request.remote_addr, request.method, request.scheme, request.full_path, tb, str(e)) logger.error(error) logger_auth.error(error) return send_error(message='INTERNAL SERVER ERROR', code=500)
def after_request(response): # This IF avoids the duplication of registry in the log, # since that 500 is already logged via @app.errorhandler. ts = strftime('[%Y-%b-%d %H:%M]') logger.error('%s %s %s %s %s %s \nREQUEST Body: %s\nRESPONSE: %s', ts, request.remote_addr, request.method, request.scheme, request.full_path, response.status, json.dumps(request.get_json()), json.dumps(response.get_json())) return response
async def token_exception_handler(request: Request, exc: TokenAuthError): logger.error( f"参数查询异常\nURL:{request.url}\nHeaders:{request.headers}\n{traceback.format_exc()}" ) return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content={ "code": 400, "data": None, "message": exc.err_desc }, )
def after_request(response): # This IF avoids the duplication of registry in the log, # since that 500 is already logged via @app.errorhandler. if response.status_code != 500: ts = strftime('[%Y-%b-%d %H:%M]') logger.error('%s %s %s %s %s %s', ts, request.remote_addr, request.method, request.scheme, request.full_path, response.status) return response
async def all_exception_handler(request: Request, exc: Exception): logger.error( f"全局异常\nURL:{request.url}\nHeaders:{request.headers}\n{traceback.format_exc(exc)}" ) return JSONResponse( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content={ "code": 500, "data": { "tip": "服务器错误" }, "message": "fail" }, )
def login(): """ This is controller of the login api Requests Body: Returns: Examples:: """ params = { 'username': FieldString(), 'password': FieldString() } try: json_data = parse_req(params) username = json_data.get('username', None).strip() password = json_data.get('password') except Exception as ex: logger.error('{} Parameters error: '.format(get_datetime_now().strftime('%Y-%b-%d %H:%M:%S')) + str(ex)) return send_error(message='Invalid username or password.\nPlease try again') user = client.db.users.find_one({'username': username}) if user is None: return send_error(message='Invalid username or password.\nPlease try again') if not check_password_hash(user["password_hash"], password): return send_error(message='Invalid username or password.\nPlease try again') access_token = create_access_token(identity=user["_id"], expires_delta=ACCESS_EXPIRES) refresh_token = create_refresh_token(identity=user["_id"], expires_delta=REFRESH_EXPIRES) # Store the tokens in our store with a status of not currently revoked. add_token_to_database(access_token, user["_id"]) add_token_to_database(refresh_token, user["_id"]) data = { 'access_token': access_token, 'refresh_token': refresh_token, 'username': user["username"], 'is_admin': user["is_admin"], 'user_id': user["_id"], 'name': user["name"], } return send_result(data=data, message="Logged in successfully!")
def exceptions(e): ts = strftime('[%Y-%b-%d %H:%M]') tb = traceback.format_exc() error = '{} {} {} {} {} 5xx INTERNAL SERVER ERROR\n{}'.format \ ( ts, request.remote_addr, request.method, request.scheme, request.full_path, tb ) logger.error(error) return "Internal Server Error", 500
def change_password(): """ This api for all user change their password. Request Body: Returns: Examples:: """ user_id = get_jwt_identity() current_user = client.db.users.find_one({"_id": user_id}) try: json_data = request.get_json() # Check valid params validate(instance=json_data, schema=password_validator) current_password = json_data.get('current_password', None) new_password = json_data.get('new_password', None) except Exception as ex: logger.error('{} Parameters error: '.format(get_datetime_now().strftime('%Y-%b-%d %H:%M:%S')) + str(ex)) return send_error(message='Parse error ' + str(ex)) if not check_password_hash(current_user["password_hash"], current_password): return send_error(message="Current password incorrect!") if is_password_contain_space(new_password): return send_error(message='Password cannot contain spaces') new_value = { '$set': { 'password_hash': hash_password(new_password) } } try: client.db.users.update_many({'_id': user_id}, new_value) except Exception as ex: return send_error(message='Database error: ' + str(ex)) # revoke all token of current user from database except current token revoke_all_token2(user_id) return send_result(message="Change password successfully!")
def create_user(): """ This is api for the user management registers user. Request Body: Returns: Examples:: """ try: json_data = request.get_json() # Check valid params validate(instance=json_data, schema=user_validator) username = json_data.get('username', None).strip() password = json_data.get('password', None) except Exception as ex: logger.error('{} Parameters error: '.format(get_datetime_now().strftime('%Y-%b-%d %H:%M:%S')) + str(ex)) return send_error(message="Parameters error: " + str(ex)) user_duplicated = client.db.users.find_one({"username": username}) if user_duplicated: return send_error(message="The username has existed!") if is_password_contain_space(password): return send_error(message='Password cannot contain spaces') keys = ["username", "name", "gender", "phone", "email", "is_admin"] user_id = str(ObjectId()) new_user = { "_id": user_id, 'password_hash': hash_password(password) } for key in keys: if key in json_data: new_user[key] = json_data.get(key) try: client.db.users.insert_one(new_user) except Exception as ex: return send_error(message="Insert to database error: " + str(ex)) return send_result(data=new_user, message="Create user successfully!")
def send_error(data=None, message="Error", code=400, version=2, status=False): """ :param data: :param message: :param code: :param version: :param status: :return: """ res_error = { "status": status, "code": code, "message": message, "data": data, "version": get_version(version) } logger.error(res_error) return jsonify(res_error), code
def reset_password(user_id): """ This api for the user management resets the users password. Request Body: Returns: Examples:: """ user = client.db.users.find_one({"_id": user_id}) if user is None: return send_error(message="Not found user!") try: json_data = request.get_json() # Check valid params validate(instance=json_data, schema=password_validator) new_password = json_data.get('new_password', None) except Exception as ex: logger.error('{} Parameters error: '.format(get_datetime_now().strftime('%Y-%b-%d %H:%M:%S')) + str(ex)) return send_error(message='Parse error ' + str(ex)) if is_password_contain_space(new_password): return send_error(message='Password cannot contain spaces') new_value = { '$set': { 'password_hash': hash_password(new_password) } } try: client.db.users.update_many({'_id': user_id}, new_value) except Exception as ex: return send_error(message='Database error: ' + str(ex)) # revoke all token of reset user from database revoke_all_token(user_id) return send_result(data=None, message="Reset password successfully!")
async def query_params_exception_handler(request: Request, exc: PostParamsError): """ 捕获 自定义抛出的异常 :param request: :param exc: :return: """ logger.error( f"参数查询异常\nURL:{request.url}\nHeaders:{request.headers}\n{traceback.format_exc()}" ) return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content={ "code": 400, "data": { "tip": exc.err_desc }, "message": "fail" }, )
async def validation_exception_handler(request: Request, exc: RequestValidationError): """ 捕获请求参数 验证错误 :param request: :param exc: :return: """ logger.error( f"参数错误\nURL:{request.url}\nHeaders:{request.headers}\n{traceback.format_exc()}" ) return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content=jsonable_encoder({ "code": 400, "data": { "tip": exc.errors() }, "body": exc.body, "message": "fail" }), )
def process_data(rtsp_url, detection_id): for thread in information_threads: if detection_id == thread["detection_id"]: try: video_capture = cv2.VideoCapture(rtsp_url, cv2.CAP_FFMPEG) except Exception as e: logger.error("Can't connect to " + rtsp_url + "\n" + e) thread["status"] == STATUS_STOPPED success, image = video_capture.read() # check exist folder if os.path.exists(FOLDER_STORE_FRAME) is False: os.makedirs(FOLDER_STORE_FRAME) path_template = FOLDER_STORE_FRAME + FRAME_NAME count = 0 list_frame_paths = [] while success and thread["status"] == STATUS_RUNNING: # extract frame frame_path = path_template.format(count) cv2.imwrite(frame_path, image) list_frame_paths.append(frame_path) stack_path = [ list_frame_paths[index] for index in list( get_stack_frame_id( len(list_frame_paths) - 1, SKIP_FRAME)) ] # Get data infomation file_infomation = get_meta_data_file(frame_path, stack_path, BOX_PATH, detection_id) # Publish file_infomation frame_pub_client.publish(TOPIC_FRAME, file_infomation) # Pop first element if len(list_frame_paths) > MAX_FRAME: try: os.remove(list_frame_paths.pop(0)) except Exception as e: pass # logger.error('Error Remove Frame: ' + list_frame_paths[0]) count += 1 try: success, image = video_capture.read() except Exception as e: logger.error("Error read frame") logger.error(e) break thread["status"] = STATUS_STOPPED
from fastapi import APIRouter, Request, Body from fastapi.responses import FileResponse from app import models, schemas from app.core.config import env_api from app.extensions import logger import traceback logger.error(traceback.format_exc()) router = APIRouter() @router.post("/images", response_model=schemas.PageResponse) async def get_images_list( request: Request, page: schemas.PageRequest, ): """ According to params to get images list :param request: pony ORM :param page: page_num page_size To decide how many images return :return: List[image_url] """ with request.pony_session: images_list = models.Upload.select(lambda file: file.note == "image") images_size = len(images_list) page_num = page.page_num page_size = page.page_size # page_num = 1 # page.page_num
def err_handler(request, exception): logger.error(exception)
def except_error(e): logger.error('can not request emotion parameter') logger.error(e) return [0.23, 0.7, 0.8, 0.91]
def create_user(): """ This is api for the user management registers user. Request Body: username: string, require The username of the user. Max length accepted is 50 and minimum length is 1. password: string, require The password of the user wanted to log in. Max length accepted is 50 and minimum length is 1. Returns: username: string username of newly registered user. group_id: string group id of this new user. Examples:: curl --location --request POST 'http://<sv_address>:5013/api/v1/users' --header 'Authorization: Bearer <access_token>' """ params = { 'username': FieldString(requirement=True), 'password': FieldString(requirement=True), 'first_name': FieldString(requirement=True), 'last_name': FieldString(requirement=True), 'company': FieldString(), 'address': FieldString(), 'mobile': FieldString() } try: json_data = parse_req(params) # Check valid params validate(instance=json_data, schema=schema_user_create) username = json_data.get('username', None).lower().strip() password = json_data.get('password', None) first_name = json_data.get('first_name', None) last_name = json_data.get('last_name', None) company = json_data.get('company', None) address = json_data.get('address', None) mobile = json_data.get('mobile', None) except Exception as ex: logger.error('{} Parameters error: '.format( datetime.datetime.utcnow().strftime('%Y-%b-%d %H:%M:%S')) + str(ex)) return send_error(message="Registers user fail!") # log input fields # logger.debug(f"INPUT api create user: {json_data}") user = Users.find_by_user_name(user_name=username) if user: return send_error(message="User exist") if is_password_contain_space(password): return send_error(message='Password cannot contain spaces') create_date = datetime.datetime.utcnow().timestamp() _id = str(uuid.uuid1()) user = Users(id=_id, username=username, password_hash=hash_password(password), force_change_password=False, create_date=create_date, modified_date=create_date, is_active=True, firstname=first_name, lastname=last_name, company=company, address=address, mobile=mobile, modified_date_password=create_date) user.save_to_db() data = { 'id': _id, 'username': username, 'first_name': first_name, 'last_name': last_name, 'create_date': create_date } return send_result(data=data, message="Registers user successfully!")