def get_location_list(): fetched = Location.query.all() location_schema = LocationSchema( many=True, only=['id', 'name', 'date_created', 'date_updated', 'external_id']) locations, error = location_schema.dump(fetched) return response_with(resp.SUCCESS_200, value={"locations": locations})
def create_user(): try: data = request.get_json() if (User.find_by_email(data['email']) is not None or User.find_by_username(data['username']) is not None): return response_with(resp.INVALID_INPUT_422) data['password'] = User.generate_hash(data['password']) user_schmea = UserSchema() user = user_schmea.load(data) sendEmailToken(data['email']) result = user_schmea.dump(user.create()) return response_with(resp.SUCCESS_201) except Exception as e: print(e) return response_with(resp.INVALID_INPUT_422)
def get_user_activity(username): user = User.query.filter_by(username=username).first() if user: user_last_login = LoginHistory.query.filter_by(user_id=user.id).first() user_requests = RequestHistory.query.filter_by(user_id=user.id).order_by( RequestHistory.request_time.desc()).all() requests = [{str(req.request_time): req.description} for req in user_requests] if user_last_login: return response_with(resp.SUCCESS_200, value={f"last login of {username}": user_last_login.last_time_login, "history_of_requests": requests}) return response_with(resp.SUCCESS_200, value={f"last login of {username}": None, "history_of_requests": requests}) return response_with(resp.INVALID_FIELD_NAME_SENT_422, value={'help': f"user {username} not found"})
def delete_user(user_id): get_user = User.query.get_or_404(user_id) if get_user.username == 'root': return jsonify(msg="You can delate a root user!"), 403 db.session.delete(get_user) db.session.commit() return response_with(resp.SUCCESS_204)
def get_customer_list(): get_customers = Customer.query.all() customer_schema = CustomerSchema(many=True, only=['id','name', 'surname', 'email',\ 'last_modifier_user_id',\ 'creator_user_id']) customers = customer_schema.dump(get_customers) return response_with(resp.SUCCESS_200, value={"customers": customers})
def patch(cls, _id): data = request.get_json() post = Post.query.get_or_404(_id) post_schema = PostSchema() updated_post = post_schema.load(data, instance=post, partial=True) result = post_schema.dump(updated_post.save_to_db()) return response_with(resp.SUCCESS_200, value={"post": result})
def verify_email(token): try: email = confirm_verification_token(token) except: return response_with(resp.SERVER_ERROR_500) user = User.query.filter_by(email=email).first_or_404() if user.isVerified: return response_with(resp.INVALID_INPUT_422) else: user.isVerified = True db.session.commit() return response_with( resp.SUCCESS_200, value={ 'message': 'E-mail verified, you can proceed to login now.' })
def get_authors(): fetched = Author.query.all() author_schema = AuthorSchema(many=True, only=['id', 'first_name', 'last_name']) authors = author_schema.dump(fetched) return response_with(resp.SUCCESS_200, value={"authors": authors})
def get(cls): page = request.args.get("page", 1, type=int) pagination = Post.query.paginate( page, per_page=current_app.config["POSTS_PER_PAGE"], error_out=False) get_posts = pagination.items prev = None if pagination.has_prev: prev = url_for("post-list", page=page - 1) _next = None if pagination.has_next: _next = url_for("post-list", page=page + 1) posts_schema = PostSchema(many=True, exclude=["user_id", "body", "comments"]) posts = posts_schema.dump(get_posts) return response_with( resp.SUCCESS_200, value={"posts": posts}, pagination={ "prev": prev, "next": _next, "count": pagination.total }, )
def get_author_list(): """ Get author list --- responses: 200: description: Returns author list schema: id: AuthorList properties: code: type: string message: type: string authors: type: array items: schema: id: AuthorSummary properties: name: type: string surname: type: string """ fetched = Author.query.all() author_schema = AuthorSchema(many=True, only=['name', 'surname']) authors, error = author_schema.dump(fetched) return response_with(resp.SUCCESS_200, value={"authors": authors})
def get(cls): page = request.args.get("page", 1, type=int) pagination = User.query.paginate( page, per_page=current_app.config["USERS_PER_PAGE"], error_out=False) get_users = pagination.items prev = None if pagination.has_prev: prev = url_for("user-list", page=page - 1) _next = None if pagination.has_next: _next = url_for("user-list", page=page + 1) users_schema = UserSchema(many=True, exclude=("posts", )) users = users_schema.dump(get_users) return response_with( resp.SUCCESS_200, value={"users": users}, pagination={ "prev": prev, "next": _next, "count": pagination.total }, )
def post(self): if request.method == 'POST': try: params = { param: request.get_json().get(param) for param in [ "job_id", "file_id", "worksheet_id", "mapping_id", "domain_id", "is_transformed", "user_id" ] } modifications = request.get_json().get( "modifications") if params["job_id"] else None result = start_check_job(params["job_id"], params["file_id"], params["worksheet_id"], params["mapping_id"], params["domain_id"], params["is_transformed"], params["user_id"], modifications=modifications) return jsonify(result) except Exception as exp: print(exp) traceback.print_exc() return resp.response_with(resp.SERVER_ERROR_500)
def verify_email(token): try: email = confirm_verification_token(token) except Exception as e: print(e) return response_with(resp.UNAUTHORIZED_401) user = User.query.filter_by(email=email).first_or_404() if user.isVerified: return response_with(resp.INVALID_INPUT_422) else: user.isVerified = True db.session.add(user) db.session.commit() return response_with( resp.SUCCESS_200, value={'message': 'Email verified, you can proceed to login now.'})
def user_auth(): auth = request.authorization if auth.username is None: return response_with(resp.MISSING_PARAMETERS_422) try: user = db.session.query(User).filter_by(username=auth.username).first() if (check_password_hash(user.password, auth.password)): token = Token(user_uuid=user.uuid) token.create() return response_with(resp.SUCCESS_201, value={"data": token.get_as_dict()}) else: return response_with(resp.UNAUTHORIZED_403) except Exception as e: print(e) return response_with(resp.UNAUTHORIZED_403)
def create_user(): # try: data = request.get_json() data['password'] = User.generate_hash(data['password']) user = user_schema.load(data) result = user_schema.dump(user.create()) return response_with(resp.SUCCESS_201)
def create_favorite_product(client_id): try: data = request.get_json() response = requests.get('http://challenge-api.luizalabs.com/api/product/{}/'.format( data['id'])) if response.status_code == 404: return response_with(resp.SERVER_ERROR_PRODUCT_404) fetched = FavoriteProducts.query.filter_by(client_id=client_id).filter_by(id=data['id']).first() if fetched is not None: return response_with(resp.DUPLICATE_FAVORITE_PRODUCT_422) data['client_id'] = client_id favorite_products_schema = FavoriteProductsSchema() favorite_product = favorite_products_schema.load(data) result = favorite_products_schema.dump(favorite_product.create()) return response_with(resp.SUCCESS_201, value={'favorite_product': result}) except Exception as e: return response_with(resp.INVALID_FIELD_NAME_SENT_422)
def post(cls): jti = get_raw_jwt()[ "jti"] # jti is `JWT ID`, a unique identifier for a JWT. BLACKLIST.add(jti) username = get_jwt_identity() return response_with(resp.SUCCESS_200, message=USER_LOGGED_OUT.format(username))
def upload_author_avatar(author_id): try: file = request.files['avatar'] get_author = Author.query.get_or_404(author_id) if file and allowed_file(file.content_type): filename = secure_filename(file.filename) file.save(os.path.join(os.path.join(current_app.root_path, current_app.config['UPLOAD_FOLDER']), filename)) get_author.avatar = url_for('uploaded_file', filename=filename, _external=True) db.session.add(get_author) db.session.commit() author_schema = AuthorSchema() author = author_schema.dump(get_author) return response_with(resp.SUCCESS_200, value={"author": author}) except Exception as e: print(e) return response_with(resp.INVALID_INPUT_422)
def post(cls): author = get_current_user() data = request.get_json() data["user_id"] = author.id incoming_tags = None if data["tags"] is not None: incoming_tags = [{"name": tag} for tag in data["tags"]] del data["tags"] post_schema = PostSchema(exclude=["tags"], partial=True) post = post_schema.load(data) post.add_to_session() for _tag in incoming_tags: tag = TagSchema().load(_tag) tag_in_db = Tag.query.filter_by(name=tag.name).first() if tag_in_db: post.tags.append(tag_in_db) else: post.tags.append(tag) post.db_commit() result = PostSchema().dump(post) return response_with(resp.SUCCESS_201, value={"post": result})
def sch_tgt_status(): tdata_input = request.get_data() json_data = json.loads(tdata_input.decode("utf-8")) tgt = json_data.get('tgt') tcas_url = app_config.CAS_URL tcas_url = tcas_url + '/cas/v1/tickets/' + tgt try: rep = rq.get(tcas_url) trep_str = rep.text print('查询TGT状态返回', rep.status_code, rep.text) return response_with(resp.SUCCESS_200, value={'tgt': trep_str}) except: exc_type, exc_value, exc_traceback = sys.exc_info() error = str( repr(traceback.format_exception(exc_type, exc_value, exc_traceback))) # 将异常信息转为字符串 return response_with(resp.SERVER_ERROR_500, value={'tgt': error})
def get_all_videos(): try: data = request.get_json() if isinstance(data, dict): videos = db.session.query(Video) pager = [] output = [] if 'name' in data: if isinstance(data['name'], str): videos = videos.filter(Video.name.contains(data['name'])) else: return response_with(resp.INVALID_INPUT_422) if 'duration' in data: if isinstance(data['duration'], int): videos = videos.filter_by(duration=data['duration']) else: return response_with(resp.INVALID_INPUT_422) if 'user' in data: if isinstance(data['user'], str): if is_valid_uuid(data['user']): videos = videos.filter_by(user_uuid=(data['user'])) else: videos = videos.join(User).filter( User.username == data['user']) else: return response_with(resp.INVALID_INPUT_422) if 'perPage' in data and 'page' in data: if isinstance(data['perPage'], int) and isinstance( data['page'], int): videos = videos.paginate(page=data['page'], per_page=data['perPage']) for video in videos.items: output.append(video.get_as_dict()) else: return response_with(resp.INVALID_INPUT_422) pager = {"current": data['page'], "total": videos.pages} return response_with(resp.SUCCESS_200, value={ "data": output, "pager": pager }) else: video = videos.all() for video in videos: output.append(video.get_as_dict()) return response_with(resp.SUCCESS_200, value={"data": output}) else: return response_with(resp.MISSING_PARAMETERS_422) except Exception as e: print(e) return response_with(resp.SERVER_ERROR_500)
def wrapper(*args, **kwargs): verify_jwt_in_request() claims = get_jwt_claims() if claims.get("is_admin", None) is True: return fn(*args, **kwargs) else: return response_with(resp.FORBIDDEN_403, message="Admin permission required")
def authenticate_user(): try: data = request.get_json() current_user = User.find_by_username(data['username']) if not current_user: return response_with(resp.INVALID_INPUT_422) if User.verify_hash(data['password'], current_user.password): access_token = create_access_token(identity=data['username']) return response_with(resp.SUCCESS_200, value={ 'message': 'Successfully logged', 'access_toke': access_token }) else: return response_with(resp.UNAUTHORIZED_401) except Exception as e: return response_with(resp.INVALID_INPUT_422)
def create_director(): try: data = request.get_json() director_schema = DirectorSchema() director = director_schema.load(data) result = director_schema.dump(director.create()) return response_with(resp.SUCCESS_201, value={"director": result}) except Exception as e: return response_with(resp.INVALID_INPUT_422)
def create_comment(current_user, uuid): try: data = request.get_json() if 'body' in data: comment = Comment(body=data['body'], user_uuid=current_user.uuid, video_id=uuid) comment.create() return response_with(resp.SUCCESS_201, value={'data': comment.get_as_dict()}) else: return response_with(resp.MISSING_PARAMETERS_422) return except Exception as e: print(e) return response_with(resp.SERVER_ERROR_500)
def encoding_video_by_id(public_id): data = request.get_json() if "format" not in data: return response_with(resp.MISSING_PARAMETERS_422) if "file" not in data: return response_with(resp.MISSING_PARAMETERS_422) video = db.session.query(Video).filter_by(uuid=public_id).first() if video is None: return response_with(resp.SERVER_ERROR_404) video_format = VideoFormat(code=data['format'], uri=data['file'], video_uuid=public_id) video_format.create() return response_with(resp.SUCCESS_200, value={"data": video.get_as_dict()})
def create_feature(): try: ## store new feature data = request.get_json() feature_schema = FeatureSchema() feature, error = feature_schema.load(data) result = feature_schema.dump(feature.create()).data ## check if client id exist avail_client = Client.query.filter_by(id=data['client_id']) client_schema = ClientSchema(many=True) client, error = client_schema.dump(avail_client) ## reorder features of client by priority ## Can be extracted into another class if not (client is None): client_features = Feature.query.filter_by( client_id=data['client_id']).order_by(Feature.priority.asc()) feature_schema = FeatureSchema(many=True) cl_features, error = feature_schema.dump(client_features) if not (cl_features is None): for i, j in enumerate(cl_features): currentPriorityVal = j['priority'] nextIndex = i + 1 if (len(cl_features) != nextIndex): nextPriorityVal = cl_features[nextIndex]['priority'] if (nextPriorityVal == currentPriorityVal): increment = nextPriorityVal + 1 cl_features[nextIndex]['priority'] = increment client_features[nextIndex].priority = increment db.session.commit() if (bool(result)): client, error = querySpecificData('client', result['client_id']) result['client'] = client.pop()['name'] product_area, error = querySpecificData('product_area', result['product_area_id']) result['product_area'] = product_area.pop()['area_type'] return response_with(resp.SUCCESS_200, value={"feature": result}) except Exception: return response_with(resp.INVALID_INPUT_422)
def get_director_detail(director_id): fetched = Director.query.get_or_404(director_id) director_schema = DirectorSchema() director = director_schema.dump(fetched) return response_with(resp.SUCCESS_200, value={"director": director})
def update_customer(customer_id): try: data = request.get_json() get_customer = Customer.query.get_or_404(customer_id) for field in data: setattr(get_customer, field, data[field]) get_customer.last_modifier_user_id = get_jwt_identity() db.session.add(get_customer) db.session.commit() customer_schema = CustomerSchema(only=['id','name', 'surname', 'email',\ 'last_modifier_user_id',\ 'creator_user_id']) customer = customer_schema.dump(get_customer) return response_with(resp.SUCCESS_200, value={"customer": customer}) except Exception as e: print(e) return response_with(resp.INVALID_INPUT_422)
def validate_st(): tdata_input = request.get_data() json_data = json.loads(tdata_input.decode("utf-8")) tst = json_data.get('st') tsrv_url = json_data.get('service') tcas_url = app_config.CAS_URL tcas_url = tcas_url + '/cas/p3/serviceValidate?service=' + tsrv_url + '&ticket=' + tst try: rep = rq.get(tcas_url) trep_str = rep.text print('验证ST票据返回', rep.status_code, rep.text) return response_with(resp.SUCCESS_200, value={'tgt': trep_str}) except: exc_type, exc_value, exc_traceback = sys.exc_info() error = str( repr(traceback.format_exception(exc_type, exc_value, exc_traceback))) # 将异常信息转为字符串 return response_with(resp.SERVER_ERROR_500, value={'st': error})