flask.request.data

Here are the examples of the python api flask.request.data taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

217 Examples 7

3 Source : service.py
with Apache License 2.0
from accelero-cloud

def _extract_dict_from_payload():
    if request.data and len(request.data) > 0:
        object_dict = request.json or json.loads(request.data)
    elif request.form and len(request.form) > 0:
        object_dict = _xtract_form()
    else:
        object_dict = {}
    return object_dict


def _xtract_form():

3 Source : wsgi.py
with Apache License 2.0
from accessai

def load():
    data = json.loads(request.data)
    project_name = data.get("project_name")
    resp = niu_app.load(project_name)

    return jsonify(resp)


@flask_app.route("/unload", methods=["OPTIONS", "POST"])

3 Source : wsgi.py
with Apache License 2.0
from accessai

def unload():
    data = json.loads(request.data)
    project_name = data.get("project_name")
    resp = niu_app.unload(project_name)

    return jsonify(resp)

3 Source : server.py
with Apache License 2.0
from AgentMaker

def predict_server():
    if not request.data:
        return json.dumps([], ensure_ascii=False)

    request_data = request.data.decode('utf-8')
    request_json = json.loads(request_data)

    if 'image' not in request_json:
        return json.dumps([], ensure_ascii=False)

    image_base64 = request_json.pop('image')
    image = base64_to_cv2(image_base64)
    results = clp(image, **request_json)

    return json.dumps(results, ensure_ascii=False)

3 Source : batch.py
with MIT License
from alexandermendes

    def delete(self):
        """Batch delete items."""
        if not request.data:
            abort(400)
        json_data = json.loads(request.data.decode('utf8'))
        if type(json_data) != list:
            abort(400)
        annotation_ids = [self._get_base_id(anno) for anno in json_data]
        try:
            repo.batch_delete(Annotation, annotation_ids)
        except (IntegrityError, ValueError) as err:
            abort(400, err)
        return self._jsonld_response(None, status_code=204)

3 Source : dashboard.py
with Apache License 2.0
from amundsen-io

    def put(self, id: str) -> Iterable[Union[Mapping, int, None]]:
        """
        Updates Dashboard description (passed as a request body)
        :param id:
        :return:
        """
        try:
            description = json.loads(request.data).get('description')
            self.client.put_dashboard_description(id=id, description=description)
            return None, HTTPStatus.OK

        except NotFoundException:
            return {'message': 'id {} does not exist'.format(id)}, HTTPStatus.NOT_FOUND


class DashboardBadgeAPI(Resource):

3 Source : table.py
with Apache License 2.0
from amundsen-io

    def put(self, id: str) -> Iterable[Any]:
        """
        Updates table description (passed as a request body)
        :param table_uri:
        :return:
        """
        try:
            description = json.loads(request.data).get('description')
            self.client.put_table_description(table_uri=id, description=description)
            return None, HTTPStatus.OK

        except NotFoundException:
            return {'message': 'table_uri {} does not exist'.format(id)}, HTTPStatus.NOT_FOUND


class TableTagAPI(Resource):

3 Source : wraps.py
with MIT License
from andrersp

def required_params(schema):
    def decorator(fn):
        @wraps(fn)
        def wrapper(*args, **kwargs):

            if not request.data:
                data = {}
            else:
                data = request.json

            v = CustonValidator(schema, lang="pt-BR")
            v.allow_unknown = False

            if not v.validate(data):
                return {"message": v.errors}, 400

            return fn(*args, **kwargs)
        return wrapper
    return decorator

3 Source : serve_http.py
with Apache License 2.0
from basisai

def explain(target):
    if not callable(getattr(current_app.model, "explain", None)):
        return "Model does not implement 'explain' method", 501
    features = current_app.model.pre_process(http_body=request.data, files=request.files)
    return current_app.model.explain(features=features, target=target)[0]


@app.route("/metrics", methods=["GET"])

3 Source : run.py
with MIT License
from bigbase-media

def task_func():
    inputs = request.data
    print(inputs)

    # 调用框架你自定义的函数
    ret = dict()
    ret['code'] = 0
    ret['message'] = "ok"
    ret['data'] = dict()

    resp = jsonify(ret)
    resp.status_code = 200
    return resp

if __name__=='__main__':

3 Source : app.py
with MIT License
from briankaemingk

def index():
    api = habits.main()
    task_url = str(request.data)
    habits.increment_streak(api, task_url)
    return 'Completed increment streak.'

@app.route('/reset_streak')

3 Source : kakao_bot.py
with MIT License
from bzantium

def message():
    data = json.loads(request.data)
    content = data["content"]

    response = {
        "message": {
            "text": content
        }
    }

    response = json.dumps(response, ensure_ascii=False)
    return response


if __name__ == "__main__":

3 Source : kakao_bot.py
with MIT License
from bzantium

def message():
    data = json.loads(request.data)
    content = data["content"]
    translator = Translator()
    translated = translator.translate(content, dest="ko", src="en")

    response = {
        "message": {
            "text": translated.text
        }
    }

    response = json.dumps(response, ensure_ascii=False)
    return response


if __name__ == "__main__":

3 Source : kakao_bot.py
with MIT License
from bzantium

def message():
    data = json.loads(request.data)
    content = data["content"]

    text = get_response(content)

    response = {
        "message": {
            "text": text
        }
    }

    response = json.dumps(response, ensure_ascii=False)
    return response

if __name__ == "__main__":

3 Source : app.py
with Apache License 2.0
from capitalone

def create():
    if request.data:
        payload = json.loads(request.data)
        multiplier = payload.get('ec2_multiplier')
        pcf_config['particles'][0]['multiplier'] = multiplier
        ec2_route53_quasiparticle = EC2Route53(pcf_config)
        
    ec2_route53_quasiparticle.set_desired_state(State.running)

    try:
        ec2_route53_quasiparticle.apply(sync=True)
    except Exception as e:
        raise e

    return str(ec2_route53_quasiparticle.get_state())

#DELETE /pcf endpoint deletes the EC2 Route53 Quasiparticle
@app.route('/pcf', methods=['DELETE'])

3 Source : ServiceResource.py
with GNU General Public License v3.0
from cdsnlab

    def post(self, command):
        xml = request.data
        Logger().debug(xml)
        result = json.dumps(xmltodict.parse(xml)['service'])
        Logger().debug(result)

        if command == "start":
            self.serviceManager.receiveService(ServiceInstance(result))
        elif command == "stop":
            self.serviceManager.stopService(ServiceInstance(result))
        else:
            pass

3 Source : mock_backend.py
with MIT License
from coxwave

    def post(self):
        user = parse_user(request)

        team = ctx.create_team(userId=user.Id, isPersonal=False, **json.loads(request.data))
        ctx.set_team(team)

        return app.response_class(response=json.dumps({"Id": team.Id}), status=201, mimetype="application/json")


@api.route("/api/team/  <  team_id>/project")

3 Source : mock_backend.py
with MIT License
from coxwave

    def post(self, team_id: str):
        parse_user(request)

        team = ctx.get_team(team_id)
        if not team:
            raise ValueError("Team not found")

        project = Project(teamId=team_id, **json.loads(request.data))
        ctx.set_project(project)

        return app.response_class(response=json.dumps({"Id": project.Id}), status=201, mimetype="application/json")


@api.route("/api/project/  <  project_id>")

3 Source : mock_backend.py
with MIT License
from coxwave

    def post(self, project_id: str):
        user = parse_user(request)

        project = ctx.get_project(project_id)
        if not project:
            raise ValueError("Project not found")

        run = Run(userId=user.Id, teamId=project.teamId, projectId=project.Id, **json.loads(request.data))
        ctx.set_run(run)

        return app.response_class(response=json.dumps({"Id": run.Id}), status=201, mimetype="application/json")


@api.route("/api/run/  <  run_id>")

3 Source : mock_backend.py
with MIT License
from coxwave

    def post(self, run_id: str):
        parse_user(request)

        ctx.add_run_record(run_id, **json.loads(request.data or "{}"))

        return app.response_class(
            status=204,
        )


@api.route("/api/project/{project_id}/tuning")

3 Source : mock_backend.py
with MIT License
from coxwave

    def get(self, project_id, controller_id):
        """
        create job, publish to agent
        """
        parse_user(request)
        controller = ctx.get_tune_controller(controller_id=controller_id)

        jobs = controller.create_jobs(request.data)
        return app.response_class(response=json.dumps({"result": jobs}), status=201, mimetype="applicatio/json")

    def patch(self, project_id, controller_id):

3 Source : mock_backend.py
with MIT License
from coxwave

    def patch(self, project_id, controller_id):
        """
        update metric, controller feed
        # TODO: metrics should come from run? or specified api?
        """
        parse_user(request)

        controller = ctx.get_tune_controller(controller_id=controller_id)
        # TODO: exceptions and success
        controller.tell_optuna(request.data)
        return app.response_class(response=json.dumps({"success": True}), status=201, mimetype="applicatio/json")

3 Source : genericapi.py
with GNU Affero General Public License v3.0
from D4-project

    def post(self, path=''):
        url = self._proxy_url()
        return requests.post(url, data=request.data).json()


# TODO: Add other parameters for asn_rank
asn_query_fields = api.model('ASNQueryFields', {

3 Source : api_server.py
with MIT License
from deeplook

def post_json_data() -> str:
    data = request.data
    print(data)
    return jsonify(data)


@app.route('/get_json_3d/')

3 Source : main.py
with Apache License 2.0
from dmfigol

def pnp_work_request():
    print(request.data)
    data = xmltodict.parse(request.data)
    correlator_id = data['pnp']['info']['@correlator']
    udi = data['pnp']['@udi']
    udi_match = SERIAL_NUM_RE.match(udi)
    serial_number = udi_match.group('serial_number')
    config_filename = DEVICES[serial_number]["config-filename"]
    jinja_context = {
        "udi": udi,
        "correlator_id": correlator_id,
        "config_filename": config_filename,
    }
    result_data = render_template('load_config.xml', **jinja_context)
    return Response(result_data, mimetype='text/xml')


@app.route('/pnp/WORK-RESPONSE', methods=['POST'])

3 Source : main.py
with Apache License 2.0
from dmfigol

def pnp_work_response():
    print(request.data)
    data = xmltodict.parse(request.data)
    correlator_id = data['pnp']['response']['@correlator']
    udi = data['pnp']['@udi']
    jinja_context = {
        "udi": udi,
        "correlator_id": correlator_id,
    }
    result_data = render_template('bye.xml', **jinja_context)
    return Response(result_data, mimetype='text/xml')

3 Source : app.py
with MIT License
from EliuX

def set_data_of(who):
    data[who] = json.loads(request.data)
    utils.log_remotely("Updated user %s with data {%s}" % (who, request.data))
    return json.dumps(data[who])


@app.route("/data/  <  who>", methods=['DELETE'])

3 Source : custom_colors_settings_routes.py
with GNU General Public License v3.0
from euphwes

def save_colors_settings():
    """ Saves the user's event preferences. """

    hidden_event_ids = [str(i) for i in loads(request.data)]
    new_settings = {SettingCode.HIDDEN_EVENTS: ','.join(hidden_event_ids)}
    set_new_settings_for_user(current_user.id, new_settings)

    return '', HTTPStatus.OK

3 Source : event_settings_routes.py
with GNU General Public License v3.0
from euphwes

def save_events_settings():
    """ Saves the user's event preferences. """

    hidden_event_ids = [str(i) for i in loads(request.data)]
    new_settings = {SettingCode.HIDDEN_EVENTS: ','.join(hidden_event_ids)}
    set_new_settings_for_user(current_user.id, new_settings)

    return ('', HTTPStatus.OK)

3 Source : __init__.py
with GNU General Public License v3.0
from euphwes

def save_settings():
    """ Saves the user's provided settings. """

    set_new_settings_for_user(current_user.id, loads(request.data))
    return '', HTTPStatus.OK


@app.route('/settings/toggle_timer_mode', methods=['POST'])

3 Source : worker.py
with Apache License 2.0
from fransking

def handle():
    response_data = handler.handle_sync(request.data)
    response = make_response(response_data)
    response.headers.set('Content-Type', 'application/octet-stream')
    return response



if __name__ == "__main__":

3 Source : main.py
with Apache License 2.0
from gojek

def verification():
	request.data = json.loads(request.data)
	if request.data['token'] == os.environ['VERIFICATION_TOKEN']:
		challenge = request.data.get('challenge')

		# Verify the challenge from slack
		if challenge is not None:
			return jsonify({"challenge":request.data['challenge']})

		# Spawn thread to process the data
		else:
			t = Thread(target=process_message, args=(json.dumps(request.data),))
			t.start()
			return jsonify({"status":"Success"})
		
	else:
		return jsonify({"status":"Fail", "reason":"Verification Failed!"})

if __name__ == '__main__':

3 Source : serve.py
with MIT License
from graphcore

def write_tmp_file():
    os.makedirs(tmp_dir, exist_ok=True)
    fd, path = tempfile.mkstemp(dir=tmp_dir)
    try:
      os.write(fd, flask.request.data)
    finally:
      os.close(fd)
    return flask.Response(path, mimetype='text/plain')


def main(unused_argv):

3 Source : app.py
with MIT License
from gwpicard

def delete():
    # create session to add and commit to
    s = db.session()

    card_id = int(request.data)

    s.query(Card).filter_by(id=card_id).delete()

    # commit deletion to database
    s.commit()
    return json.dumps({'success':True}), 200, {'ContentType':'application/json'}

# save all cards
@Kanban_app.route("/save", methods=['POST'])

3 Source : htx.py
with MIT License
from heartexlabs

def _predict():
    data = json.loads(request.data)
    tasks = data['tasks']
    project = data['project']
    schema = data.get('schema')
    model_version = data.get('model_version')
    params = data.get('params', {})

    logger.info(f'Request: predict {len(tasks)} tasks for project {project}')
    results, model_version = _model_manager.predict(tasks, project, schema, model_version, **params)
    response = {
        'results': results,
        'model_version': model_version
    }
    return jsonify(response)


@_server.route('/update', methods=['POST'])

3 Source : htx.py
with MIT License
from heartexlabs

def _update():
    task = json.loads(request.data)
    project = task.pop('project')
    schema = task.pop('schema')
    retrain = task.pop('retrain', False)
    params = task.pop('params', {})
    logger.info(f'Update for project {project} with retrain={retrain}')
    maybe_job = _model_manager.update(task, project, schema, retrain, params)
    response = {}
    if maybe_job:
        response['job'] = maybe_job.id
        return jsonify(response), 201
    return jsonify(response)


@_server.route('/train', methods=['POST'])

3 Source : htx.py
with MIT License
from heartexlabs

def _train():
    data = json.loads(request.data)
    tasks = data['tasks']
    project = data['project']
    schema = data['schema']
    params = data.get('params', {})
    if len(tasks) == 0:
        return jsonify({'status': 'error', 'message': 'No tasks found.'}), 400
    logger.info(f'Request: train for project {project} with {len(tasks)} tasks')
    job = _model_manager.train(tasks, project, schema, params)
    response = {'job': job.id}
    return jsonify(response), 201


@_server.route('/setup', methods=['POST'])

3 Source : htx.py
with MIT License
from heartexlabs

def _setup():
    data = json.loads(request.data)
    project = data['project']
    schema = data['schema']
    logger.info(f'Request: setup for project {project}')
    model_version = _model_manager.setup(project, schema)
    response = {'model_version': model_version}
    return jsonify(response)


@_server.route('/validate', methods=['POST'])

3 Source : htx.py
with MIT License
from heartexlabs

def _validate():
    data = json.loads(request.data)
    config = data['config']
    logger.info(f'Request: validate {request.data}')
    validated_schemas = _model_manager.validate(config)
    if validated_schemas:
        return jsonify(validated_schemas)
    else:
        return jsonify({'status': 'failed'}), 422


@_server.route('/job_status', methods=['POST'])

3 Source : htx.py
with MIT License
from heartexlabs

def _job_status():
    data = json.loads(request.data)
    job = data['job']
    logger.info(f'Request: job status for {job}')
    response = _model_manager.job_status(job)
    return jsonify(response or {})


@_server.route('/delete', methods=['POST'])

3 Source : htx.py
with MIT License
from heartexlabs

def _delete():
    data = json.loads(request.data)
    project = data['project']
    logger.info(f'Request: delete project {project}')
    result = _model_manager.delete(project)
    return jsonify(result or {})


@_server.route('/duplicate_model', methods=['POST'])

3 Source : htx.py
with MIT License
from heartexlabs

def _duplicate_model():
    data = json.loads(request.data)
    project_src = data['project_src']
    project_dst = data['project_dst']
    result = _model_manager.duplicate_model(project_src, project_dst)
    return jsonify(result or {})


@_server.route('/health', methods=['GET'])

3 Source : sourceserver.py
with MIT License
from jamespfennell

def put(path):
    if path not in path_to_content:
        return "", 404
    path_to_content[path] = request.data
    return "", 204


@app.route("/  <  path:path>", methods=["DELETE"], strict_slashes=False)

3 Source : predict.py
with MIT License
from jgbustos

    def post() -> FlaskApiReturnType:
        """
        Returns a prediction using the model.
        """
        if not trained_model_wrapper.ready():
            raise MLRestAPINotReadyException()
        data = dict(json.loads(request.data))
        ret = trained_model_wrapper.run(data)
        return ret, 200

3 Source : server.py
with MIT License
from jrwnter

def init_swarm():
    data = json.loads(request.data)
    optimizer = MPPSOOptimizerManualScoring.from_query(
        init_smiles=data["init_smiles"],
        num_part=data["num_part"],
        num_swarms=data["num_swarms"],
        inference_model=inferenceServer)
    output = [swarm.to_dict() for swarm in optimizer.swarms]
    return jsonify(output)

@app.route('/next_step/', methods=['POST'])

3 Source : server.py
with MIT License
from jrwnter

def next_step():
    data = json.loads(request.data)
    optimizer = MPPSOOptimizerManualScoring.from_swarm_dicts(
        swarm_dicts=data["swarm_dicts"],
        inference_model=inferenceServer,
        phi1=data["phi1"],
        phi2=data["phi2"],
        phi3=data["phi3"]
    )
    swarms = optimizer.run_one_iteration(data["fitness"])
    output = [swarm.to_dict() for swarm in swarms]
    return jsonify(output)


if __name__ == '__main__':

3 Source : main.py
with MIT License
from LibrePhotos

    def post(self):
        request_body = json.loads(request.data)

        user_id = request_body["user_id"]
        image_hashes = request_body["image_hashes"]
        image_embeddings = request_body["image_embeddings"]

        index.build_index_for_user(user_id, image_hashes, image_embeddings)

        return jsonify({"status": True, "index_size": index.indices[user_id].ntotal})


class SearchIndex(Resource):

3 Source : run_Recognize_Model.py
with MIT License
from lolimay

def flaskServer(PORT=4000):
    app = Flask(__name__)

    @app.route('/', methods=['POST'])
    def hello():
        base64 = request.data

        # Recognize
        if base64 != None:
            return json.dumps(recognize(base64))

    app.run(host='0.0.0.0', port=PORT)

if __name__ == "__main__":

3 Source : service.py
with MIT License
from lopezco

def preprocess():
    """Preporcess input data

    Get the preprocessed version of the input data. If the model does not
    include preprocessing steps, this method will return the same data as the
    input.

    """
    input = json.loads(flask.request.data or '{}')
    try:
        data = model.preprocess(input)
    except Exception as err:
        return flask.Response(str(err), status=500)
    else:
        return data


@application.route('/health')

3 Source : instance.py
with Apache License 2.0
from MaibornWolff

def update_instance(instance_id):
    """Updates the configuration for an instance. If needed a redeploy of the instance is triggered"""
    di.get(InstanceService).update_instance(instance_id, request.data["configuration"])
    return dict(instance_id=instance_id, status="updated"), 200


@instrumented_route('/api/instance/  <  instance_id>/restart', 'POST')

See More Examples