def __call__(self, req): try: if req.path in ('/', '/RPC2', '/server'): if req.method == 'POST': # XML-RPC if req.content_type != 'text/xml': return BadRequest('XML-RPC requests must be text/xml') result = self.xmlrpc_dispatcher._marshaled_dispatch( req.data) return Response(response=result, content_type='text/xml') elif req.method in ('GET', 'HEAD'): # XML-RPC docs return Response(response=self.xmlrpc_dispatcher. generate_html_documentation(), content_type='text/html') else: return MethodNotAllowed() else: (obj, attr), args = self.url_map.bind_to_environ( req.environ).match() if obj is self.proxy: # pseudo-XML-RPC result = getattr(obj, attr)(**args) return Response(response=repr(result), content_type='text/plain') else: return getattr(obj, attr)(req, **args) except HTTPException, e: return e
def login(): form = LoginForm() if flask.request.method == 'POST': with connection.cursor(buffered=True) as cursor: try: results = cursor.execute( "SELECT * FROM account WHERE email='%s'" % flask.request.values['email'], multi=True) response = [] for cur in results: if cur.with_rows: response.append(str(cur.fetchall())) return Response(status=200, response=response) except Exception as e: return Response(status=500, response=e.msg) if flask.request.method == 'GET': return render_template('login.jinja2', form=form, title='Log in.', template='login-page', body="Log in with your User account.")
def add_product(): """ Add new product """ if request.method == 'POST' and request.is_json: try: req = request.get_json() product = product_catalog.Product(name=req['name'], description=req['description'], image=req['image'], labels=req['labels'], price=req['price'], created_at=int(time.time())) product_id = product_catalog.add_product(product) product_img = req['image'] publish_image(product_id, product_img) msg = { 'result': 'Product added successfully!', 'product_id': product_id } response = Response(response=json.dumps(msg), status=201, mimetype='application/json') return response except: msg = {'error': 'Sorry! We were not able to add your product'} response = Response(response=json.dumps(msg), status=400, mimetype='application/json') return response
def frames(img_key): frame = redis.get(request.path) if frame is None: response = Response(f'{img_key} not found', status=404) else: response = Response(frame, mimetype="image/jpeg") return response
def api_report_json(idC): summary = Reporter().reportSummary(idC) if summary == 404: return Response(status=404) elif summary == 412: return Response(status=412) return jsonify(summary)
def api_report_raw(idC): data = Reporter().reportRawData(idC) if data == 404: return Response(status=404) elif data == 412: return Response(status=412) return jsonify(data)
def _process_error(exception): """Decomposition of the webservice fn handler. returns 400 if the exception occurred in the input validation :param exception: The Exception which occured as a part of processing the request :return: a flask Response that more specifically identifies the cause of the problem. """ if "input" in exception.args[0]: return Response(response=exception, status=400) return Response(status=500, response=exception)
def delete_user(user_name): if g.user.access_id == 1: user = User.query.filter_by(user_name = user_name).first() if user is None: return(Response('404: user not found')) else: db.session.delete(user) db.session.commit() return(Response('200: user deleted')) else: return(Response('401: unauthorized user'))
def api_logger(): if 'Content-Type' in request.headers.keys(): if request.headers[ 'Content-Type'] == 'application/x-www-form-urlencoded': co.saveLog(request.form, "TEST") return Response(status=200) else: return Response(status=400) else: return Response(status=400)
def work_cancel(self, action_instance_id): pid_file = StoreService.check_for_pidfile(action_instance_id) if pid_file is not None: try: base_name = basename(pid_file) psutil.Process(int(base_name.split('-')[-1])).kill() return Response(json.dumps({"message": "Killed process."}), 200) except Exception: pass return Response(json.dumps({"message": "Failed to kill process"}), 501)
def sales_route(): if request.method == "GET": return jsonify(sales.get_list_sales()) elif request.method == "POST": data = json.loads(request.data) vals = (data["saleID"], data["custID"], data["emplID"], data["prodID"], data["num"], data["date"], 0) success = sales.into_sales(vals) if success: return Response(status=204) else: return Response(status=500)
def send_message(): data = request.json if not isinstance(data, dict): return Response({'error': 'not JSON'}, 400) text = data.get('text') author = data.get('author') if isinstance(text, str) and isinstance(author, str): db.append({'text': text, 'author': author, 'time': time.time()}) return Response('ok') else: return Response('wrong format', 400)
def post(self): # Utils.getLogger(__name__).debug("Request recebido /csvServices/storePassagem. Header: " + request.headers['Content-Type']) if request.headers['Content-Type'] != "application/json": return Response(status=415) #Unsupported Media Type jsonContent = request.json if (jsonContent): passagensStorage = PassagensStorage() passagensStorage.validateAndInsert(jsonContent) resp = Response(status=201) #Created resp.headers['Content-Type'] = 'application/json' return resp return Response(status=422) #Unprocessable Entity
def suggest_items(): """ Get spelling suggestions for a given search term. """ if request.method == "POST": # Post request payload = request.get_json(silent=True) if not payload: # Bad payload, return with user error return Response( "Missing or ill-formatted query. For POST requests, payload of format {'query': '<word>'} and correct headers ('Content-Type': 'application/json') are required.", 400) else: # Get request payload = request.args # Get parameters of request query = payload.get("query") or payload.get("q") mixin = payload.get("mixin") max_hits = payload.get("max") include_products = payload.get( "products") == 'true' if "products" in payload else False if not query: return Response("Empty query", 204) # Get search results max_h = max_hits or 10 search_response = search_term(query, max_hits=max_h, mixin=mixin) # Do spelling check # suggestions = [] suggestions = spelling_suggestions(query, search_response, best_guess=False) spelling_correct = len(suggestions) == 0 # Format response if include_products: response = { 'results': search_response, 'spelling_suggestions': suggestions, 'spelling_correct': spelling_correct } else: response = { 'spelling_suggestions': suggestions, 'spelling_correct': spelling_correct } response['metadata'] = {'request': request.url, 'version': api_version} return Response(json.dumps(response), 200, headers=json_headers)
def update_user(): if g.user.access_id == 1: user_data = request.get_json() # Extracting JSON object from request body if len(user_data['user_name']) == 0 or len(user_data['email']) == 0 or len(user_data['country']) == 0: abort(Response('400: missing arguments')) user = User.query.filter_by(user_name = user_data['user_name']).first() if user is None: abort(Response('404: user not found')) user.email = user_data['email'] user.country = user_data['country'] db.session.commit() return(Response('204: user updated')) else: return(Response('401: unauthorized user'))
def add_user(): user_data = request.get_json() # Extracting JSON object from request body if len(user_data['user_name']) == 0 or len(user_data['email']) == 0 or len(user_data['country']) == 0 or len(user_data['password']) == 0: abort(Response('400: missing arguments')) if User.query.filter_by(user_name = user_data['user_name']).first() is not None: abort(Response('400: user already exists')) user = User(user_name=user_data['user_name'], email=user_data['email'], country=user_data['country'], access_id=user_data['access_id']) user.hash_password(user_data['password']) db.session.add(user) db.session.commit() return(Response('201: user added'))
def post(self): jsonContent = request.json #Verifica se o json tem o nome do arquivo e dados. if not ((jsonContent) and jsonContent.get("extArquivo") and jsonContent.get("dadosArquivo")): return Response(status=400) try: submissionCode = self.vparManager.submitImage( jsonContent.get("extArquivo"), jsonContent.get("dadosArquivo")) return jsonify(codigoLeituraOCR=submissionCode) except: OCRUtils.getLogger(__name__).debug( '*** Exceção no método POST de ABOCRServices ***') return Response(status=500)
def get(self, imgPath='/tmp/B0064GK.BMP'): if (imgPath[0:1] != "/"): imgPath = "/" + str(imgPath) if (not OCRUtils.allowed_OCR_file(imgPath)): return Response(status=400) else: print("Imagem = %s" % imgPath) result = Vpar.ocrReadImg(imgPath) if result == None: return Response(status=404) else: return jsonify(placa=string_at(result.strResult), tempoProcessamento=result.lProcessingTime, confiancaGlobal=result.vlGlobalConfidence[0])
def work_request(self): current_work = StoreService.get_executors() current_work = current_work + self.__get_quarantined_items() work = { 'current_work': current_work, 'hostname': self.app.rapid_config.hostname } if self.can_work_on() and self.check_version(request): return Response(json.dumps(work), content_type='application/json', headers={Version.HEADER: Version.get_version()}) return Response(json.dumps(work), status=423, content_type='application/json', headers={Version.HEADER: Version.get_version()})
def api_logger_id(): if 'Content-Type' in request.headers.keys(): if request.headers['Content-Type'] == 'application/json': logJson = request.json print(logJson) try: co.saveLog(logJson, 'aaa') return Response(status=200) except: return Response(400) else: return Response(400) else: return Response(status=400)
def plain_response(): return Response( "{'response': 'Hello World'}", status=200, headers=dict(), content_type="test/plain" )
def get_face_preview(faceid: str): print('get_face_preview(faceid:{})'.format(faceid)) try: images: List[Mapping[str, Any]] = face_table_client.get_face_images( faceid)['Images'] best_image = images[-1] except Exception as error: print('Unable to best_image metadata') raise error try: content = image_client.fetch_image(best_image['s3_uri']) bbox = BoundingBox(best_image['bounding_box']) if bbox.is_usable: content = image_client.cut_bounding_box(content, bbox) content = image_client.resize_image(content, (64, 64)) else: content = image_client.resize_image(content, (64, 64)) except Exception as error: print('Unable to fetch/crop best_image[{}]'.format( best_image['s3_uri'])) raise error try: return Response(response=content.read(), mimetype='image/png', content_type='image/png') except Exception as error: print('Unable to return best_image[{}]'.format(best_image['s3_uri'])) raise error
def post(self, command): request.get_json(force=True) if command == "getTree": type = request.json['type'] if type == "Mob" or type == "Character" or type == "Map": tmp = [] rows = dao.select( "SELECT * from Folder where type=? and parent IS NULL", (type,)) for row in rows: tmp.append(Folder( row[0], row[1], opened=True )) tmp = Arbo(tmp, type) ret = [] for elem in tmp: ret.append(elem.getJSON()) path = './file/tree/' + type + '.json' file = open('../Client/' + path[2:], 'w+') file.write(json.dumps(ret)) file.close() return {"code": 200, "data": ret} else: return {"code": 400, "message": "Bad Request: This type doesn't exist"} elif command == "getFolderById": rows = dao.select("SELECT * FROM Folder WHERE id=?", (request.json['id'],)) folder = [] type = "" for row in rows: folder.append(Folder(row[0], row[1])) type = row[2] folder = Arbo(folder, type) return Response(response=json.dumps(folder[0].getJSON()), status=200, mimetype="application/json")
def prepare_response(data=None, code=200) -> Response: """ Sets the necessary headers and status code on the response :param data: The data to be returned to the client :param code: the status code. 200 by default :return: The Response object with the headers set according to the input data """ response = Response() headers = response.headers if _is_allowed_origin(): headers['Access-Control-Allow-Origin'] = request.headers['Origin'] headers['Access-Control-Allow-Methods'] = "GET,POST,PUT,DELETE,OPTIONS" headers[ 'Access-Control-Allow-Headers'] = "Content-Type, Authorization, X-Requested-With" headers['Access-Control-Allow-Credentials'] = "true" headers['Access-Control-Max-Age'] = 1000 if data is not None: if isinstance(data, dict) or isinstance(data, list): response.set_data(json.dumps(data)) headers['Content-Type'] = 'application/json' else: response.set_data(data) headers['Content-Type'] = 'text/plain; charset=utf-8' response.status_code = code return response
def report(userid, reportid): try: query = { '_id': ObjectId(userid), 'reports': { '$elemMatch': { 'id': ObjectId(reportid) } } } except bson.errors.InvalidId as e: return jsonify(ok=False, msg=f'invalid userid provided\n\n{e}') if request.method == 'GET': data = col.find_one({**query}, {'_id': 0, 'reports.$': 1}) if data == None: return jsonify(ok=False, msg='no such report found') return Response(response=dumps(data['reports'][0]), mimetype='application/json') elif request.method == 'DELETE': data = col.find_one_and_update( {'_id': ObjectId(userid)}, {'$pull': { 'reports': { 'id': ObjectId(reportid) } }}, return_document=ReturnDocument.AFTER) if data == None: return jsonify(ok=False, msg='no such report found') return jsonify(ok=True, msg='report deleted')
def triples(collection_id): require(request.authz.can_stream()) log.debug("Stream triples [%r] begins... (coll: %s)", request.authz, collection_id) collection = get_db_collection(collection_id, request.authz.READ) record_audit(Audit.ACT_COLLECTION, id=collection_id) return Response(export_collection(collection), mimetype='text/plain')
def triples(collection_id): """ --- get: summary: Linked data stream of the collection description: >- This will return a list of triples that describe each entity in the given collection. The format is `ntriples`. parameters: - in: path name: collection_id required: true schema: type: integer responses: '200': description: OK content: text/plain: schema: type: string tags: - Entity """ require(request.authz.can_stream()) log.debug("Stream triples [%r] begins... (coll: %s)", request.authz, collection_id) collection = get_db_collection(collection_id, request.authz.READ) return Response(export_collection(collection), mimetype='text/plain')
def get_support_cost(): data = dict(cost=15000) resp = Response(response=json.dumps(data), status=200, mimetype="application/json") return resp
def upload(): if flask.request.method == 'POST': # get the file f = flask.request.files['file'] # save to ./uploads basepath = os.path.dirname(__file__) file_path = os.path.join(basepath, 'uploads', secure_filename(f.filename)) f.save(file_path) if str(file_path).endswith('.png'): model_dir = DIR result = generate_img(model=model, model_dir=model_dir, model_name=MODEL_NAME, image_name=file_path) else: new_model_dir = 'mSRGAN/epochs_msrgan_celeba/' result = generate_img(model=model, model_dir=new_model_dir, model_name=MODEL_NAME_CELEBA, image_name=file_path) try: return Response(response=result, status=200, mimetype='image/png') except FileNotFoundError: os.abort(404)
def table(): response = table_create() resp = Response(response=json.dumps(response), status=200, mimetype="application/json") return resp