Python flask.request.get_data() Examples
The following are 30
code examples of flask.request.get_data().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
flask.request
, or try the search function
.
Example #1
Source File: app.py From pluralsight with MIT License | 8 votes |
def predict_image_handler(): try: imageData = None if ('imageData' in request.files): imageData = request.files['imageData'] else: imageData = io.BytesIO(request.get_data()) #img = scipy.misc.imread(imageData) img = Image.open(imageData) results = predict_image(img) return json.dumps(results) except Exception as e: print('EXCEPTION:', str(e)) return 'Error processing image', 500 # Like the CustomVision.ai Prediction service /url route handles url's # in the body of hte request of the form: # { 'Url': '<http url>'}
Example #2
Source File: scan_directory.py From JAVOneStop with MIT License | 6 votes |
def rename_path_on_json(): req_data = json.loads(request.get_data() or '{}') file_objs = req_data['file_objs'] path = req_data['path'] # handle usual error if not os.path.exists(path): return jsonify({'response': [{'file_name': f'{path} does not exist'}]}), 400 if not os.path.isdir(path): return jsonify({'response': [{'file_name': f'{path} is not a valid directory for scan'}]}), 400 def long_process(): for each_file_process in EmbyFileStructure.rename_directory(path, file_objs): yield json.dumps({'log': each_file_process})+'\n' return Response(long_process(), mimetype='text/event-stream')
Example #3
Source File: app-amd64.py From Custom-vision-service-iot-edge-raspberry-pi with MIT License | 6 votes |
def predict_image_handler(project=None, publishedName=None): try: imageData = None if ('imageData' in request.files): imageData = request.files['imageData'] elif ('imageData' in request.form): imageData = request.form['imageData'] else: imageData = io.BytesIO(request.get_data()) img = Image.open(imageData) results = predict_image(img) return jsonify(results) except Exception as e: print('EXCEPTION:', str(e)) return 'Error processing image', 500 # Like the CustomVision.ai Prediction service /url route handles url's # in the body of hte request of the form: # { 'Url': '<http url>'}
Example #4
Source File: post_template.py From notifications-api with MIT License | 6 votes |
def post_template_preview(template_id): # The payload is empty when there are no place holders in the template. _data = request.get_data(as_text=True) if not _data: _data = {} else: _data = get_valid_json() _data['id'] = template_id data = validate(_data, post_template_preview_request) template = templates_dao.dao_get_template_by_id_and_service_id( template_id, authenticated_service.id) template_object = template._as_utils_template_with_personalisation( data.get('personalisation') ) check_placeholders(template_object) resp = create_post_template_preview_response(template=template, template_object=template_object) return jsonify(resp), 200
Example #5
Source File: app.py From Custom-vision-service-iot-edge-raspberry-pi with MIT License | 6 votes |
def predict_image_handler(project=None, publishedName=None): try: imageData = None if ('imageData' in request.files): imageData = request.files['imageData'] elif ('imageData' in request.form): imageData = request.form['imageData'] else: imageData = io.BytesIO(request.get_data()) img = Image.open(imageData) results = predict_image(img) return jsonify(results) except Exception as e: print('EXCEPTION:', str(e)) return 'Error processing image', 500 # Like the CustomVision.ai Prediction service /url route handles url's # in the body of hte request of the form: # { 'Url': '<http url>'}
Example #6
Source File: views_default_to_current_conversation.py From python-slackclient with MIT License | 6 votes |
def slack_app(): if not signature_verifier.is_valid_request(request.get_data(), request.headers): return make_response("invalid request", 403) if "command" in request.form \ and request.form["command"] == "/view": trigger_id = request.form["trigger_id"] return open_modal(trigger_id) elif "payload" in request.form: payload = json.loads(request.form["payload"]) if payload["type"] == "view_submission" \ and payload["view"]["callback_id"] == "modal-id": submitted_data = payload["view"]["state"]["values"] print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} return make_response("", 200) if payload["type"] == "shortcut" \ and payload["callback_id"] == "view-test": return open_modal(payload["trigger_id"]) return make_response("", 404)
Example #7
Source File: main.py From SSRFTest with MIT License | 6 votes |
def hit(link): if '.' in link: link, ext = link.split('.', 1) else: ext = '' req = '%s %s HTTP/1.1\r\n' % (request.method, request.url) for k, v in request.headers: req += '%s: %s\r\n' % (k, v) req += '\r\n' req += request.get_data() createLocalSession() try: ret = handlers.target.hit(link, ext, req) except: closeLocalSession(True) raise else: closeLocalSession(False) return ret
Example #8
Source File: web_endpoint_query_autocomplete.py From cellphonedb with MIT License | 6 votes |
def post(self): parameters = json.loads(request.get_data(as_text=True)) partial_element = parameters['partial_element'] if len(partial_element) < 2: return flask.jsonify({'success': True, 'result': []}) try: interactions = cellphonedb_app.cellphonedb.query.autocomplete_launcher(partial_element) response = { 'success': True, 'result': interactions.to_dict(orient='records') } except: response = { 'success': False } print(traceback.print_exc(file=sys.stdout)) return flask.jsonify(response)
Example #9
Source File: web_endpoint_query_complex_deconvoluted.py From cellphonedb with MIT License | 6 votes |
def post(self): parameters = json.loads(request.get_data(as_text=True)) complex_name = parameters['complex_name'] deconvoluted = cellphonedb_app.cellphonedb.query.get_complex_deconvoluted(complex_name) if deconvoluted.empty: self.attach_error( {'code': 'element_not_found', 'title': '%s is not CellPhoneDB Complex' % complex_name, 'details': '%s is not present in CellPhoneDB complex table' % complex_name}) else: self._attach_csv(deconvoluted.to_csv(index=False, sep=','), 'result') self._commit_attachments() return Response(self._msg.as_string(), mimetype='multipart/form-data; boundary="%s"' % self._msg.get_boundary())
Example #10
Source File: web_endpoint_query_find_interactions_by_element.py From cellphonedb with MIT License | 6 votes |
def post(self): parameters = json.loads(request.get_data(as_text=True)) receptor = parameters['receptor'] interactions = cellphonedb_app.cellphonedb.query.find_interactions_by_element(receptor) if interactions.empty: self.attach_error( {'code': 'result_not_found', 'title': '%s is not CellPhoneDB interactor' % receptor, 'details': '%s is not present in CellPhoneDB interactor enabled table' % receptor}) else: self._attach_csv(interactions.to_csv(index=False, sep=','), 'ligands') self._commit_attachments() return Response(self._msg.as_string(), mimetype='multipart/form-data; boundary="%s"' % self._msg.get_boundary())
Example #11
Source File: views.py From FXTest with MIT License | 6 votes |
def post(self): id = request.get_data('id') project = id.decode('utf-8') if not project: return jsonify({'msg': u'没有发送数据', 'code': 38, 'data': ''}) project_is = Project.query.filter_by(project_name=project).first() if not project_is: return jsonify(({'msg': u'成功', 'code': 200, 'data': []})) testreport = TestResult.query.filter_by(projects_id=project_is.id, status=False).order_by('-id').all() testreportlist = [] for test in testreport: testreportlist.append({'test_num': test.test_num, 'pass_num': test.pass_num, 'fail_num': test.fail_num, 'hour_time': str(test.hour_time), 'test_rep': test.test_rep, 'test_log': test.test_log, 'Exception_num': test.Exception_num, 'can_num': test.can_num, 'wei_num': test.wei_num, 'test_time': str(test.test_time), 'Test_user_id': test.users.username, 'id': test.id, 'fenshu': test.pass_num / test.test_num}) return jsonify(({'msg': u'成功', 'code': 200, 'data': (testreportlist)}))
Example #12
Source File: app.py From imagery with GNU Affero General Public License v3.0 | 6 votes |
def handle(): try: url_data = request.get_data() print(url_data) '''Slacks interactive message request payload is in the form of application/x-www-form-urlencoded JSON string. Getting first actions parameter from it.''' url_data = json.loads(parse_qs(url_data.decode('utf-8'))['payload'][0])['actions'][0] eph_value = True if url_data['value'] == "yes" else False print(url_data['name'] + " : " + url_data['value'] + " : " + str(eph_value)) if eph_value: params = url_data['name'].split('|') user_id = params[1] channel_id = params[2] file_id = params[3] file_permalink = params[4] comment = params[5] timestamp = params[6] i = pool.apply_async(download_file, [file_permalink, file_id, channel_id, comment, user_id, timestamp]) else: print('---No chosen---') except Exception as err: print(err) finally: return jsonify({"response_type": "ephemeral", "replace_original": "true", "delete_original": "true", "text": ""})
Example #13
Source File: test_flask.py From sentry-python with BSD 2-Clause "Simplified" License | 6 votes |
def test_flask_large_json_request(sentry_init, capture_events, app): sentry_init(integrations=[flask_sentry.FlaskIntegration()]) data = {"foo": {"bar": "a" * 2000}} @app.route("/", methods=["POST"]) def index(): assert request.get_json() == data assert request.get_data() == json.dumps(data).encode("ascii") assert not request.form capture_message("hi") return "ok" events = capture_events() client = app.test_client() response = client.post("/", content_type="application/json", data=json.dumps(data)) assert response.status_code == 200 (event,) = events assert event["_meta"]["request"]["data"]["foo"]["bar"] == { "": {"len": 2000, "rem": [["!limit", "x", 509, 512]]} } assert len(event["request"]["data"]["foo"]["bar"]) == 512
Example #14
Source File: test_flask.py From sentry-python with BSD 2-Clause "Simplified" License | 6 votes |
def test_flask_medium_formdata_request(sentry_init, capture_events, app): sentry_init(integrations=[flask_sentry.FlaskIntegration()]) data = {"foo": "a" * 2000} @app.route("/", methods=["POST"]) def index(): assert request.form["foo"] == data["foo"] assert not request.get_data() assert not request.get_json() capture_message("hi") return "ok" events = capture_events() client = app.test_client() response = client.post("/", data=data) assert response.status_code == 200 (event,) = events assert event["_meta"]["request"]["data"]["foo"] == { "": {"len": 2000, "rem": [["!limit", "x", 509, 512]]} } assert len(event["request"]["data"]["foo"]) == 512
Example #15
Source File: webhook.py From Matrix-NEB with Apache License 2.0 | 6 votes |
def do_POST(self, service=""): log.debug("NebHookServer: Plugin=%s : Incoming request from %s", service, request.remote_addr) if service.split("/")[0] not in self.plugin_mappings: return ("", 404, {}) plugin = self.plugin_mappings[service.split("/")[0]] try: # tuple (body, status_code, headers) response = plugin.on_receive_webhook( request.url, request.get_data(), request.remote_addr, request.headers ) if response: return response return ("", 200, {}) except Exception as e: log.exception(e) return ("", 500, {})
Example #16
Source File: server.py From sato with MIT License | 6 votes |
def index(): print(port) data = json.loads(request.get_data().decode('utf-8')) # FETCH THE CRYPTO NAME crypto_name = data["nlp"]["entities"]["crypto_name"][0]["raw"] crypto_ticker = crypto_name.upper() # FETCH BTC/USD/EUR PRICES r = requests.get("https://min-api.cryptocompare.com/data/price?fsym="+crypto_ticker+"&tsyms=BTC,USD,EUR") return jsonify( status=200, replies=[{ 'type': 'text', 'content': 'The price of %s is :\n%f BTC, \n%f USD, and \n%f EUR.' % (crypto_ticker, r.json()['BTC'], r.json()['USD'], r.json()['EUR']) }] )
Example #17
Source File: javlib_browser.py From JAVOneStop with MIT License | 6 votes |
def update_db_jav(): req_data = json.loads(request.get_data() or '{}') jav_pk = req_data.get('pk') update_data = req_data.get('data') if not jav_pk: return jsonify({'error': 'no pk found in posted json'}), 400 db_conn = JavManagerDB() try: current_jav_obj = dict(db_conn.get_by_pk(jav_pk)) except DoesNotExist: current_jav_obj = {'car': jav_pk} current_jav_obj.update(update_data) db_conn.upcreate_jav(current_jav_obj) return jsonify({'success': dict(current_jav_obj)})
Example #18
Source File: security.py From ob2 with BSD 2-Clause "Simplified" License | 6 votes |
def get_request_validity(): # GitHub signature will suffice for CSRF check github_signature = request.headers.get("X-Hub-Signature") if github_signature: payload_bytes = request.get_data() for github_webhook_secret in config.github_webhook_secrets: digest = hmac.new(github_webhook_secret, payload_bytes, sha1).hexdigest() expected_signature = "sha1=%s" % digest if expected_signature == github_signature: return True # Normal CSRF form tokens work too token = request.form.get("_csrf_token") expected_token = session.get("_csrf_token", None) if expected_token and expected_token == token: return True return False
Example #19
Source File: switch_api.py From netman with Apache License 2.0 | 6 votes |
def set_port_mode(self, switch, interface_id): """ Sets the port mode of an interface :arg str hostname: Hostname or IP of the switch :arg str interface_id: Interface name (ex. ``FastEthernet0/1``, ``ethernet1/11``) :body: ``trunk`` or ``access`` """ mode = request.get_data().lower() if mode == 'trunk': switch.set_trunk_mode(interface_id) elif mode == 'access': switch.set_access_mode(interface_id) else: raise BadRequest('Unknown port mode detected {}'.format(mode)) return 204, None
Example #20
Source File: switch_api.py From netman with Apache License 2.0 | 6 votes |
def set_bond_port_mode(self, switch, bond_number): """ Sets the port mode of a bond :arg str hostname: Hostname or IP of the switch :arg int bond_number: Bond number :body: ``trunk`` or ``access`` """ mode = request.get_data().lower() if mode == 'trunk': switch.set_bond_trunk_mode(bond_number) elif mode == 'access': switch.set_bond_access_mode(bond_number) else: raise BadRequest('Unknown port mode detected {}'.format(mode)) return 204, None
Example #21
Source File: local_manager.py From JAVOneStop with MIT License | 6 votes |
def update_jav_dict(): # update db jav dict, also rewrite nfo and images req_data = json.loads(request.get_data() or '{}') update_dict = req_data['update_dict'] # update db db_conn = JavManagerDB() db_conn.upcreate_jav(update_dict) file_writer = EmbyFileStructure(return_default_config_string('file_path')) # file structure operations try: jav_obj = file_writer.create_folder_for_existing_jav(update_dict) except KeyError as e: _car = update_dict.get('car', 'Unknown') update_dict.append(json.dumps({'log': f'error: {e}, skipping {_car}'})) # write images file_writer.write_images(jav_obj) # write nfo file_writer.write_nfo(jav_obj) # move video file jav_obj = file_writer.move_existing_file(jav_obj) return jsonify({'success': jav_obj}) # post updated jav_obj back to UI
Example #22
Source File: bento_api_server.py From BentoML with Apache License 2.0 | 6 votes |
def feedback_view_func(bento_service): """ User send feedback along with the request Id. It will be stored and ready for further process. """ if request.content_type != "application/json": return Response( response="Incorrect content format, require JSON", status=400 ) data = json.loads(request.get_data().decode("utf-8")) if "request_id" not in data.keys(): return Response(response="Missing request id", status=400) if len(data.keys()) <= 1: return Response(response="Missing feedback data", status=400) data["service_name"] = bento_service.name data["service_version"] = bento_service.version feedback_logger.info(data) return Response(response="success", status=200)
Example #23
Source File: local_manager.py From JAVOneStop with MIT License | 6 votes |
def restructure_jav(): req_data = json.loads(request.get_data() or '{}') update_dict = req_data['update_dict'] file_writer = EmbyFileStructure(return_default_config_string('file_path')) # file structure operations try: jav_obj = file_writer.create_folder_for_existing_jav(update_dict) except KeyError as e: _car = update_dict.get('car', 'Unknown') update_dict.append(json.dumps({'log': f'error: {e}, skipping {_car}'})) # write images file_writer.write_images(jav_obj) # write nfo file_writer.write_nfo(jav_obj) # move video file jav_obj = file_writer.move_existing_file(jav_obj) return jsonify({'success': 'good'})
Example #24
Source File: server_self_run.py From sato with MIT License | 6 votes |
def index(): data = json.loads(request.get_data().decode('utf-8')) # FETCH THE CRYPTO NAME crypto_name = data[“nlp”][“entities”][“crypto_name”][0][“raw”] # FETCH BTC/USD/EUR PRICES r = requests.get("https://min-api.cryptocompare.com/data/price?fsym="+crypto_name+"&tsyms=BTC,USD,EUR") return jsonify( status=200, replies=[{ 'type': 'text', 'content': 'The price of %s is %f BTC and %f USD' % (crypto_name, r.json()['BTC'], r.json()['USD']) }] )
Example #25
Source File: test_flask.py From sentry-python with BSD 2-Clause "Simplified" License | 6 votes |
def test_flask_empty_json_request(sentry_init, capture_events, app, data): sentry_init(integrations=[flask_sentry.FlaskIntegration()]) @app.route("/", methods=["POST"]) def index(): assert request.get_json() == data assert request.get_data() == json.dumps(data).encode("ascii") assert not request.form capture_message("hi") return "ok" events = capture_events() client = app.test_client() response = client.post("/", content_type="application/json", data=json.dumps(data)) assert response.status_code == 200 (event,) = events assert event["request"]["data"] == data
Example #26
Source File: __init__.py From quay with Apache License 2.0 | 5 votes |
def max_json_size(max_size): def wrapper(func): @wraps(func) def wrapped(self, *args, **kwargs): if request.is_json and len(request.get_data()) > max_size: raise InvalidRequest() return func(self, *args, **kwargs) return wrapped return wrapper
Example #27
Source File: index.py From python-flask-template with MIT License | 5 votes |
def __init__(self): self.body = request.get_data() self.headers = request.headers self.method = request.method self.query = request.args self.path = request.path
Example #28
Source File: index.py From python-flask-template with MIT License | 5 votes |
def __init__(self): self.body = request.get_data() self.headers = request.headers self.method = request.method self.query = request.args self.path = request.path
Example #29
Source File: ajax_api.py From sparrow with GNU General Public License v3.0 | 5 votes |
def webssh_exec(): try: db_webssh = db_op.webssh_records info = str(request.get_data(),encoding='utf8').split('&') msg_id = info[1].split('=')[-1] dst_ip = info[2].split('=')[-1] ssh_port = info[3].split('=')[-1] exec = info[0].split('=')[-1] Key = 'op_webssh_exec_%s:%s' %(dst_ip,ssh_port) if exec != '%0D': exec = urllib.parse.unquote(exec,encoding='utf-8') RC.rpush(Key,exec) else: exec = ''.join(RC.lrange(Key,0,-1)).replace('+',' ') RC.delete(Key) user = RC.hget('op_webssh_session',msg_id) if not user: user = '' c = db_webssh(date=time.strftime('%Y-%m-%d',time.localtime()), time=time.strftime('%H:%M:%S',time.localtime()), msg_id=msg_id,user=user,dst_ip=dst_ip,sshport=ssh_port,exec=exec) db_op.DB.session.add(c) db_op.DB.session.commit() except Exception as e: logging.error(e) finally: return jsonify({'stats':200})
Example #30
Source File: krnnt_serve.py From krnnt with GNU Lesser General Public License v3.0 | 5 votes |
def maca(): text = request.get_data() # print(text.decode('utf-8').split('\n\n')) results = maca_analyzer._maca(text.decode('utf-8').split('\n\n')) results = list(results) return str(results)