def search(): db = g.restaurant_name try: status, data = search_food(request.args, db) if not status: return error_response(str(data)) return response(True, 'Foods search successful', data) except Exception as err: return error_response(str(err))
def view_orders(): db = g.restaurant_name status, missing_field = validate_body(request.args, ['phone']) if not status: return error_response(f'{missing_field} is missing from query params') try: status, res = view_individual_order(request.args, db) if not status: return error_response(str(res)) return response(True, 'Your Orders', res) except Exception as err: return error_response(str(err))
def delete(): db = g.restaurant_name food_id = request.args.get('id') if not food_id: return error_response('id is required') try: status, data = delete_food(food_id, db) if not status: return error_response(str(data)) return response(True, 'Food deleted successfully', None) except Exception as err: return error_response(str(err))
def create_restaurant(): if g.restaurant_name: return error_response('Invalid route', 'error', 'RO', 404) body = request.get_json() if 'name' not in body: return error_response("Field 'name' is required") try: create_restaurant_domain(body['name']) except Exception as err: return error_response(str(err)) domain = f'{body["name"]}.eatie.com' return response(True, f'{domain} created successfully', None)
def deliver(): body = request.get_json() db = g.restaurant_name status, missing_field = validate_body(body, ['phone']) if not status: return error_response(f'{missing_field} is required') try: status, res = deliver_orders(body, db) if not status: return error_response(str(res)) return response(True, 'Orders status updated', None) except Exception as err: return error_response(str(err))
def order(): db = g.restaurant_name body = request.get_json() status, missing_field = validate_body(body, ['phone', 'food_id']) if not status: return error_response(f'{missing_field} is required') try: status, res = create_order(body, db) if not status: return error_response(str(res)) return response(True, 'Order created successfully', None) except Exception as err: return error_response(str(err))
def update(): db = g.restaurant_name body = request.get_json() status, missing_field = validate_body(body, ['id']) if not status: return error_response(f'{missing_field} is required') try: status, data = update_food(body, db) if not status: return error_response(str(data)) return response(True, 'Food updated successfully', None) except Exception as err: return error_response(str(err))
def login(self, request): try: username = request.data['username'] password = request.data['password'] user = User.objects.filter(username=username, password=password).last() serializer = UserSerializer(user) if user: return success_response('登录成功', serializer.data) else: return error_response('账号或密码错误') except Exception as e: return error_response(str(e))
def cancel(): body = request.get_json() db = g.restaurant_name status, missing_field = validate_body(body, ['phone']) if not status: return error_response(f'{missing_field} is required') try: status, res = cancel_orders(body, db) if not status: return error_response(str(res)) return response(True, 'Orders canceled successfully', None) except Exception as err: return error_response(str(err))
def create(): body = request.get_json() db = g.restaurant_name status, missing_field = validate_body(body, ['name', 'picture_url', 'price']) if not status: return error_response(f'{missing_field} is required') try: status, res = insert_food(body, db) if not status: return error_response(str(res)) return response(True, 'Food created successfully', None) except Exception as err: return error_response(str(err))
def validate_request(): restaurant_name = g.restaurant_name if not restaurant_name: return error_response('Invalid route', 'error', 'RO', 404) auth_header = request.headers.get('Authorization') if not auth_header: return error_response('Authorization required', 'error', 'RO', 403) try: token = auth_header.split('Bearer')[-1].strip() body = decode_jwt(token) if body['restaurant'] != restaurant_name: return error_response('Invalid Auth token', 'error', 'RO', 403) except Exception as err: print(f'=====> Auth Error', err) return error_response('Invalid Auth token', 'error', 'RO', 403)
def list_runs(request: Request, project_id: int, experiment_id: Text) -> JSONResponse: """Get runs list. Args: project_id {int}: project id experiment_id {Text}: experiment id Returns: starlette.responses.JSONResponse """ log_request(request) project_manager = ProjectManager() url = project_manager.get_internal_tracking_uri(project_id) resp = requests.post(url=f'{url}/api/2.0/preview/mlflow/runs/search', json={'experiment_ids': [experiment_id]}) if resp.status_code != HTTPStatus.OK: return error_response(http_response_code=resp.status_code, message=resp.json().get('message')) runs = resp.json().get('runs', []) for run in runs: run['id'] = run.get('info', {}).get('run_id') return JSONResponse(runs)
def delete_experiment(request: Request, experiment_id: Text, project_id: int) -> JSONResponse: """Delete experiment. Args: experiment_id {Text}: experiment id project_id {int}: project id Returns: starlette.responses.JSONResponse """ log_request(request, { 'project_id': project_id, 'experiment_id': experiment_id }) project_manager = ProjectManager() url = project_manager.get_internal_tracking_uri(project_id) experiment_resp = requests.post( url=f'{url}/api/2.0/preview/mlflow/experiments/delete', json={'experiment_id': experiment_id}) if experiment_resp.status_code != HTTPStatus.OK: return error_response(http_response_code=experiment_resp.status_code, message=experiment_resp.json().get('message')) return JSONResponse({'experiment_id': experiment_id})
def view(): args = request.args db = g.restaurant_name try: if not args: status, data = all_orders(db) elif 'phone' in args: status, data = view_individual_order(args, db) else: return error_response( 'phone should be present in the query params') if not status: return error_response(str(data)) return response(True, 'Success', data) except Exception as err: return error_response(str(err))
def delete_model(request: Request, model_id: Text, project_id: int) -> JSONResponse: """Delete model. Args: model_id {Text}: model id (name) project_id {int}: project id Returns: starlette.responses.JSONResponse """ log_request(request, { 'project_id': project_id, 'model_id': model_id }) project_manager = ProjectManager() url = project_manager.get_internal_tracking_uri(project_id) model_resp = requests.delete( url=f'{url}/api/2.0/preview/mlflow/registered-models/delete', json={'registered_model': {'name': model_id}} ) if model_resp.status_code != HTTPStatus.OK: return error_response( http_response_code=model_resp.status_code, message=model_resp.json().get('message') ) return JSONResponse({'model_id': model_id})
def get_model(request: Request, model_id: Text, project_id: int) -> JSONResponse: """Get model. Args: model_id {Text}: model id (name) project_id {int}: project id Returns: starlette.responses.JSONResponse """ log_request(request) project_manager = ProjectManager() url = project_manager.get_internal_tracking_uri(project_id) model_resp = requests.post( url=f'{url}/api/2.0/preview/mlflow/registered-models/get-details', json={'registered_model': {'name': model_id}} ) if model_resp.status_code != HTTPStatus.OK: return error_response( http_response_code=model_resp.status_code, message=model_resp.json().get('message') ) registered_model_detailed = model_resp.json().get('registered_model_detailed', {}) model = { 'id': registered_model_detailed.get('registered_model', {}).get('name'), 'project_id': project_id, 'creation_timestamp': registered_model_detailed.get('creation_timestamp'), 'last_updated_timestamp': registered_model_detailed.get('last_updated_timestamp') } return JSONResponse(model)
def signin_staff(): body = request.get_json() db = g.restaurant_name status, missing_field = validate_body(body, ['username', 'password']) if not status: return error_response(f'{missing_field} missing') try: status, data = login_staff(body, db) if not status: raise Exception(str(data)) token = encode_jwt({'name': data['name'], 'restaurant': db}) return response(True, 'Staff login successful', { 'token': token, 'restaurant': db }) except Exception as err: return error_response(str(err))
def get_experiment(request: Request, experiment_id: Text, project_id: int) -> JSONResponse: """Get experiment. Args: experiment_id {Text}: experiment id project_id {int}: project id Returns: starlette.responses.JSONResponse """ log_request(request) project_manager = ProjectManager() url = project_manager.get_internal_tracking_uri(project_id) experiment_resp = requests.get( url= f'{url}/api/2.0/preview/mlflow/experiments/get?experiment_id={experiment_id}' ) if experiment_resp.status_code != HTTPStatus.OK: return error_response(http_response_code=experiment_resp.status_code, message=experiment_resp.json().get('message')) experiment = experiment_resp.json().get('experiment') experiment_id = experiment.get('experiment_id') runs_resp = requests.get( f'{url}/api/2.0/preview/mlflow/runs/search?experiment_ids=[{experiment_id}]' ) runs = runs_resp.json().get('runs', []) creation_time = '' last_update_time = '' """ if corresponding tags are empty then fields: * creation_time = start_time of the first run; * last_update_time = end_time of the last run. """ if len(runs) > 0: creation_time = runs[len(runs) - 1].get('info', {}).get('start_time') last_update_time = runs[0].get('info', {}).get('end_time') experiment['id'] = experiment.pop('experiment_id') tags = {tag['key']: tag['value'] for tag in experiment.pop('tags', [])} experiment['description'] = tags.get('mlflow.note.content', '') experiment['user_id'] = tags.get('user_id', '') experiment['project_id'] = tags.get('project_id', project_id) experiment['creation_time'] = tags.get('creation_time', creation_time) experiment['last_update_time'] = tags.get('last_update_time', last_update_time) return JSONResponse(experiment)
def list_artifacts(request: Request, project_id: int, run_id: Text) -> JSONResponse: """Get artifacts list. Args: project_id {int}: project id run_id {int}: run_id Returns: starlette.responses.JSONResponse """ log_request(request, {'project_id': project_id, 'run_id': run_id}) project_manager = ProjectManager() url = project_manager.get_internal_tracking_uri(project_id) runs_resp = requests.get( url=f'{url}/api/2.0/preview/mlflow/artifacts/list?run_id={run_id}') if runs_resp.status_code != HTTPStatus.OK: return error_response(http_response_code=runs_resp.status_code, message=runs_resp.json().get('message')) runs = runs_resp.json() root_uri = runs.get('root_uri') files = runs.get('files', []) runs_list = [] for i, file in enumerate(files): runs_resp = requests.get( url=f'{url}/api/2.0/preview/mlflow/runs/get?run_id={run_id}', ) run = runs_resp.json() run_info = run.get('run', {}).get('info', {}) experiment_id = run_info.get('experiment_id') runs_list.append({ 'id': f'{project_id}{experiment_id}{run_id}{i}', 'project_id': project_id, 'experiment_id': experiment_id, 'run_id': run_id, 'type': str(get_artifact_type(root_uri, file)), 'creation_timestamp': run_info.get('start_time'), 'root_uri': root_uri, 'path': file.get('path') }) return JSONResponse(runs_list)
def predict(deployment_id: int, data: Text = Form(...)) -> JSONResponse: """Predict data on deployment. Args: deployment_id {int}: deployment id data {Text}: data to predict Returns: starlette.responses.JSONResponse """ deploy_manager = DeployManager() response = deploy_manager.predict(deployment_id=deployment_id, data=data) if response.status_code != HTTPStatus.OK: return error_response( http_response_code=response.status_code, message=response.json().get('message') ) return JSONResponse({'prediction': response.text})
def run_project(request: Request, project_id: int) -> JSONResponse: # pylint: disable=invalid-name,redefined-builtin """Run project's tracking server. Args: project_id {int}: project id Returns: starlette.responses.JSONResponse """ log_request(request, {'project_id': project_id}) project_manager = ProjectManager() running = project_manager.run(project_id) if not running: return error_response( http_response_code=HTTPStatus.INTERNAL_SERVER_ERROR, message='Internal error, tracking server has terminated') project = project_manager.get_project(project_id) return JSONResponse(project, HTTPStatus.OK)
def get_run(request: Request, run_id: Text, project_id: int) -> JSONResponse: """Get run. Args: run_id {Text}: run id project_id {int}: project id Returns: starlette.responses.JSONResponse """ log_request(request) project_manager = ProjectManager() url = project_manager.get_internal_tracking_uri(project_id) resp = requests.get( url=f'{url}/api/2.0/preview/mlflow/runs/get?run_id={run_id}', ) if resp.status_code != HTTPStatus.OK: return error_response(http_response_code=resp.status_code, message=resp.json().get('message')) run = resp.json().get('run') run['id'] = run.get('info', {}).get('run_id') return JSONResponse(run)
def get_model_version(request: Request, version: Text, project_id: int, model_id: Text) -> JSONResponse: """Get model versions list. Args: project_id {int}: project id model_id {Text}: model id (name) Returns: starlette.responses.JSONResponse """ log_request(request) check_if_project_and_model_exist(project_id, model_id) model_versions = filter_model_versions(get_model_versions(project_id), model_id) for version_info in model_versions: model_version = version_info.get('model_version', {}) version_number = model_version.get('version') if version_number == version: return JSONResponse({ 'id': version_number, 'model_id': model_version.get('registered_model', {}).get('name'), 'project_id': project_id, 'version': version_number, 'creation_timestamp': version_info.get('creation_timestamp'), 'last_updated_timestamp': version_info.get('last_updated_timestamp'), 'run_id': version_info.get('run_id'), 'model_uri': version_info.get('source') }) return error_response( http_response_code=HTTPStatus.NOT_FOUND, message=f'Version {version} of model {model_id} in project {project_id} not found' )
def create_experiment( request: Request, project_id: int, user_id: Text = Form(''), name: Text = Form(''), description: Text = Form('') ) -> JSONResponse: """Create experiment Args: project_id {int}: project id user_id {Text}: user id (name) name {Text}: experiment name description {Text}: experiment description Returns: starlette.responses.JSONResponse """ log_request( request, { 'project_id': project_id, 'user_id': user_id, 'name': name, 'description': description }) project_manager = ProjectManager() url = project_manager.get_internal_tracking_uri(project_id) creation_resp = requests.post( url=f'{url}/api/2.0/preview/mlflow/experiments/create', json={'name': name}) creation_json = creation_resp.json() experiment_id = creation_json.get('experiment_id') if creation_resp.status_code != HTTPStatus.OK: return error_response(http_response_code=creation_resp.status_code, message=creation_json.get('message')) utc_timestamp = get_utc_timestamp() tags = { 'mlflow.note.content': description, 'user_id': user_id, 'project_id': str(project_id), 'creation_time': utc_timestamp, 'last_update_time': utc_timestamp } for key, value in tags.items(): requests.post( url=f'{url}/api/2.0/preview/mlflow/experiments/set-experiment-tag', json={ 'experiment_id': experiment_id, 'key': key, 'value': value }) experiment_request = requests.get( url= f'{url}/api/2.0/preview/mlflow/experiments/get?experiment_id={experiment_id}' ) experiment = experiment_request.json().get('experiment') tags = {tag['key']: tag['value'] for tag in experiment.pop('tags', [])} experiment['description'] = tags.get('mlflow.note.content', '') experiment['user_id'] = tags.get('user_id', '') experiment['project_id'] = tags.get('project_id', '') experiment['creation_time'] = tags.get('creation_time', '') experiment['last_update_time'] = tags.get('last_update_time', '') return JSONResponse(experiment, HTTPStatus.CREATED)
def validate_restaurant_name(): restaurant_name = g.restaurant_name if not restaurant_name: return error_response('Invalid route', 'error', 'RO', 404)