Python flask.request.json() Examples

The following are 30 code examples of flask.request.json(). 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: validators.py    From jbox with MIT License 8 votes vote down vote up
def __call__(self, form, field):
        if current_app.testing:
            return True

        if request.json:
            response = request.json.get('g-recaptcha-response', '')
        else:
            response = request.form.get('g-recaptcha-response', '')
        remote_ip = request.remote_addr

        if not response:
            raise ValidationError(field.gettext(self.message))

        if not self._validate_recaptcha(response, remote_ip):
            field.recaptcha_error = 'incorrect-captcha-sol'
            raise ValidationError(field.gettext(self.message)) 
Example #2
Source File: views.py    From comport with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def complaints():
    username = request.authorization.username
    extractor = Extractor.query.filter_by(username=username).first()
    department = extractor.first_department()
    request_json = request.json
    added_rows = 0
    updated_rows = 0

    complaint_class = getattr(importlib.import_module("comport.data.models"), "CitizenComplaint{}".format(department.short_name))

    for incident in request_json['data']:
        added = complaint_class.add_or_update_incident(department, incident)
        if added is True:
            added_rows += 1
        elif added is False:
            updated_rows += 1

    extractor.next_month = None
    extractor.next_year = None
    extractor.save()
    return json.dumps({"added": added_rows, "updated": updated_rows}) 
Example #3
Source File: api.py    From cascade-server with Apache License 2.0 6 votes vote down vote up
def query_job(job, user=None):
    """
    :type job: Job
    :type user: User
    """
    job = Job.objects.with_id(job), httplib.OK
    if job is None:
        return None, httplib.NOT_FOUND

    if request.method == 'GET':
        return job, httplib.OK

    elif request.method == 'POST':
        return job.modify(**request.json), httplib.OK

    elif job and request.method == 'DELETE':
        job.delete()
        return None, httplib.OK 
Example #4
Source File: app.py    From botbuilder-python with MIT License 6 votes vote down vote up
def messages():
    # Main bot message handler.
    if "application/json" in request.headers["Content-Type"]:
        body = request.json
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = (
        request.headers["Authorization"] if "Authorization" in request.headers else ""
    )

    try:
        task = LOOP.create_task(
            ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
        )
        LOOP.run_until_complete(task)
        return Response(status=201)
    except Exception as exception:
        raise exception 
Example #5
Source File: main.py    From botbuilder-python with MIT License 6 votes vote down vote up
def messages():
    """Main bot message handler."""
    if "application/json" in request.headers["Content-Type"]:
        body = request.json
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = (
        request.headers["Authorization"] if "Authorization" in request.headers else ""
    )

    async def aux_func(turn_context):
        await BOT.on_turn(turn_context)

    try:
        task = LOOP.create_task(
            ADAPTER.process_activity(activity, auth_header, aux_func)
        )
        LOOP.run_until_complete(task)
        return Response(status=201)

    except Exception as exception:
        raise exception 
Example #6
Source File: app.py    From botbuilder-python with MIT License 6 votes vote down vote up
def messages():
    # Main bot message handler.
    if "application/json" in request.headers["Content-Type"]:
        body = request.json
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = (
        request.headers["Authorization"] if "Authorization" in request.headers else ""
    )

    try:
        task = LOOP.create_task(
            ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
        )
        LOOP.run_until_complete(task)
        return Response(status=201)
    except Exception as exception:
        raise exception 
Example #7
Source File: app.py    From botbuilder-python with MIT License 6 votes vote down vote up
def messages():
    # Main bot message handler.
    if "application/json" in request.headers["Content-Type"]:
        body = request.json
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = (
        request.headers["Authorization"] if "Authorization" in request.headers else ""
    )

    async def aux_func(turn_context):
        await BOT.on_turn(turn_context)

    try:
        task = LOOP.create_task(
            ADAPTER.process_activity(activity, auth_header, aux_func)
        )
        LOOP.run_until_complete(task)
        return Response(status=201)
    except Exception as exception:
        raise exception 
Example #8
Source File: api.py    From cascade-server with Apache License 2.0 6 votes vote down vote up
def automate_session(session, user=None):
    """
    :type session: cascade.session.Session
    :type user: User
    """
    session = Session.objects.with_id(session)
    if not session:
        return None, httplib.NOT_FOUND

    if isinstance(request.json, dict):
        if request.json.get('analytics') is not None:
            requested_analytics = request.json['analytics']

            for requested_analytic in requested_analytics:
                analytic = Analytic.objects.with_id(requested_analytic['_id'])
                if analytic:
                    mode = requested_analytic.get('mode', analytic.mode)
                    config = AnalyticConfiguration(analytic=analytic, mode=mode)
                    session.update(add_to_set__state__analytics=config)
                    job = AnalyticJob.update_existing(analytic=analytic, user=user, session=session, mode=mode)
                    job.submit()
            return len(requested_analytics), httplib.OK

    return 0, httplib.BAD_REQUEST 
Example #9
Source File: api.py    From cascade-server with Apache License 2.0 6 votes vote down vote up
def automate_session_custom(session, user=None):
    """
    :type session: cascade.session.Session
    :type user: User
    """
    session = Session.objects.with_id(session)
    if not session:
        return None, httplib.NOT_FOUND

    if not isinstance(request.json, dict):
        return None, httplib.BAD_REQUEST

    query = DataModelQuery._from_son(request.json['query'])
    job = CustomQueryJob.update_existing(session=session, event_query=query, user=user)
    job.submit()
    return None, httplib.OK 
Example #10
Source File: views.py    From comport with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def pursuits():
    username = request.authorization.username
    extractor = Extractor.query.filter_by(username=username).first()
    department = extractor.first_department()
    request_json = request.json
    added_rows = 0
    updated_rows = 0

    pursuit_class = getattr(importlib.import_module("comport.data.models"), "Pursuit{}".format(department.short_name))

    for incident in request_json['data']:
        added = pursuit_class.add_or_update_incident(department, incident)
        if added is True:
            added_rows += 1
        elif added is False:
            updated_rows += 1

    extractor.next_month = None
    extractor.next_year = None
    extractor.save()
    return json.dumps({"added": added_rows, "updated": updated_rows}) 
Example #11
Source File: views.py    From comport with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def officer_involved_shooting():
    username = request.authorization.username
    extractor = Extractor.query.filter_by(username=username).first()
    department = extractor.first_department()
    request_json = request.json
    added_rows = 0
    updated_rows = 0

    ois_class = getattr(importlib.import_module("comport.data.models"), "OfficerInvolvedShooting{}".format(department.short_name))

    for incident in request_json['data']:
        added = ois_class.add_or_update_incident(department, incident)
        if added is True:
            added_rows += 1
        elif added is False:
            updated_rows += 1

    extractor.next_month = None
    extractor.next_year = None
    extractor.save()
    return json.dumps({"added": added_rows, "updated": updated_rows}) 
Example #12
Source File: views.py    From comport with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def use_of_force():
    username = request.authorization.username
    extractor = Extractor.query.filter_by(username=username).first()
    department = extractor.first_department()
    request_json = request.json
    added_rows = 0
    updated_rows = 0

    uof_class = getattr(importlib.import_module("comport.data.models"), "UseOfForceIncident{}".format(department.short_name))

    for incident in request_json['data']:
        added = uof_class.add_or_update_incident(department, incident)
        if added is True:
            added_rows += 1
        elif added is False:
            updated_rows += 1

    extractor.next_month = None
    extractor.next_year = None
    extractor.save()
    return json.dumps({"added": added_rows, "updated": updated_rows}) 
Example #13
Source File: api.py    From cascade-server with Apache License 2.0 6 votes vote down vote up
def query_analytic_configuration(config_id, user=None):
    config = AnalyticConfigurationList.objects.with_id(config_id)
    if config is None and request.method != 'PUT':
        return None, httplib.NOT_FOUND

    if request.method == 'GET':
        return config, httplib.OK

    elif request.method == 'DELETE':
        config.delete()
        return None, httplib.OK

    elif request.method == 'PUT':
        if config is None:
            config = AnalyticConfigurationList(id=config_id)
        config = config.update(**request.json)
        return config.id, httplib.OK 
Example #14
Source File: api.py    From cascade-server with Apache License 2.0 6 votes vote down vote up
def make_query():
    try:
        query = parser.generate_query(request.json['query'])
        event_type, action = DataModelQueryLayer.get_data_model(query)
        return {'object': event_type.object_name, 'action': action, 'query': query}, httplib.OK

    except InvalidFieldError:
        return {'error': 'Invalid Data Model field in query'}, httplib.BAD_REQUEST

    except InvalidActionError:
        return {'error': 'Invalid Data Model action in query'}, httplib.BAD_REQUEST

    except InvalidObjectError:
        return {'error': 'Invalid Data Model object in query'}, httplib.BAD_REQUEST

    except parser.ParserError:
        return {'error': 'Unable to parse query'}, httplib.BAD_REQUEST 
Example #15
Source File: app.py    From botbuilder-python with MIT License 6 votes vote down vote up
def messages():
    # Main bot message handler.
    if "application/json" in request.headers["Content-Type"]:
        body = request.json
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = (
        request.headers["Authorization"] if "Authorization" in request.headers else ""
    )

    try:
        task = LOOP.create_task(
            ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
        )
        LOOP.run_until_complete(task)
        return Response(status=201)
    except Exception as exception:
        raise exception 
Example #16
Source File: app.py    From botbuilder-python with MIT License 6 votes vote down vote up
def messages():
    # Main bot message handler.
    if "application/json" in request.headers["Content-Type"]:
        body = request.json
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = (
        request.headers["Authorization"] if "Authorization" in request.headers else ""
    )

    try:
        task = LOOP.create_task(
            ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
        )
        LOOP.run_until_complete(task)
        return Response(status=201)
    except Exception as exception:
        raise exception 
Example #17
Source File: app.py    From botbuilder-python with MIT License 6 votes vote down vote up
def messages():
    # Main bot message handler.
    if "application/json" in request.headers["Content-Type"]:
        body = request.json
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = (
        request.headers["Authorization"] if "Authorization" in request.headers else ""
    )

    try:
        task = LOOP.create_task(
            ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
        )
        LOOP.run_until_complete(task)
        return Response(status=201)
    except Exception as exception:
        raise exception 
Example #18
Source File: api.py    From cascade-server with Apache License 2.0 6 votes vote down vote up
def query_baselines(user=None):
    if request.method == 'GET':
        return AnalyticBaseline.objects(), httplib.OK

    elif request.method == 'POST':
        if isinstance(request.json, dict):
            if request.json.get('analytics') is not None and request.json.get('time') is not None:
                requested_analytics = request.json.get('analytics', [])
                time_range = DateRange.get_range(request.json['time'])

                count = 0
                for requested_analytic in requested_analytics:
                    analytic_id = requested_analytic.pop('_id', requested_analytic.get('id'))
                    analytic = Analytic.objects.with_id(analytic_id)

                    if analytic is None:
                        continue

                    job = TuningJob.update_existing(analytic=analytic, range=time_range, user=user)
                    job.submit()
                    count += 1
                return count, httplib.OK
    return [], httplib.BAD_REQUEST 
Example #19
Source File: api.py    From cascade-server with Apache License 2.0 6 votes vote down vote up
def create_user():
    if not settings.load()['config'].get('allow_account_creation', False):
        return JSONResponse(status=httplib.FORBIDDEN)

    """ This API route is used by the create new account template to add a new user into Mongo """
    if isinstance(request.json, dict):
        args = request.json
        if args.get('username') and args.get('password'):
            try:
                user = users.create_user(args['username'], args['password'], args.get('email'), args.get('full_name'))
            except users.PasswordPolicyError as error:
                regex, rules = error.args
                return JSONResponse({'violation': {'regex': regex, 'rules': rules}}, httplib.BAD_REQUEST)

            if user is not None:
                response = Response(status=httplib.CREATED)
                response.set_cookie('user-token', user.generate_token(), max_age=datetime.timedelta(days=7))
                return response
            else:
                return JSONResponse({'message': 'Username already exists!'}, status=httplib.BAD_REQUEST)

    return JSONResponse({'message': 'Username, email and password are required'}, status=httplib.BAD_REQUEST) 
Example #20
Source File: app.py    From dota2-predictor with MIT License 6 votes vote down vote up
def home():
    if request.method == "POST":
        #do back end things here and then return what we want, take it back in a success function in JS and update the page.
        heroes = [name.encode('UTF8') for name in request.json['heroes']]
        radiant = [get_hero_id(hero) for hero in heroes[:5] if get_hero_id(hero)]
        dire = [get_hero_id(hero) for hero in heroes[5:] if get_hero_id(hero)]
        mmr = int(request.json['mmr'])

        text = query(mmr, radiant, dire)

        if isinstance(text, list):
            text = ''.join([str(hero[0]) + ': ' + str(round(hero[1][0] * 100, 2))+'% win rate. <br>' for hero in text[:10]])

        return text

    hero_names = get_full_hero_list()
    radiant_heroes, dire_heroes = get_hero_factions()
    edited_names = [name.replace(" ", "_").replace("\'", "").lower() for name in hero_names]
    return render_template('main2.html', hero_names=sorted(hero_names), edited_names=sorted(edited_names), radiant_heroes=radiant_heroes, dire_heroes=dire_heroes) 
Example #21
Source File: rest_connector.py    From thingsboard-gateway with Apache License 2.0 6 votes vote down vote up
def process_data(self, request):
        if not request.json:
            abort(415)
        endpoint_config = self.__endpoint['config']
        if request.method.upper() not in [method.upper() for method in endpoint_config['HTTPMethods']]:
            abort(405)
        try:
            log.info("CONVERTER CONFIG: %r", endpoint_config['converter'])
            converter = self.__endpoint['converter'](endpoint_config['converter'])
            converted_data = converter.convert(config=endpoint_config['converter'], data=request.get_json())
            self.send_to_storage(self.__name, converted_data)
            log.info("CONVERTED_DATA: %r", converted_data)
            return "OK", 200
        except Exception as e:
            log.exception("Error while post to anonymous handler: %s", e)
            return "", 500 
Example #22
Source File: rest_connector.py    From thingsboard-gateway with Apache License 2.0 6 votes vote down vote up
def process_data(self, request):
        if not request.json:
            abort(415)
        endpoint_config = self.__endpoint['config']
        if request.method.upper() not in [method.upper() for method in endpoint_config['HTTPMethods']]:
            abort(405)
        try:
            log.info("CONVERTER CONFIG: %r", endpoint_config['converter'])
            converter = self.__endpoint['converter'](endpoint_config['converter'])
            converted_data = converter.convert(config=endpoint_config['converter'], data=request.get_json())
            self.send_to_storage(self.__name, converted_data)
            log.info("CONVERTED_DATA: %r", converted_data)
            return "OK", 200
        except Exception as e:
            log.exception("Error while post to basic handler: %s", e)
            return "", 500 
Example #23
Source File: ws.py    From cascade-server with Apache License 2.0 6 votes vote down vote up
def session_stream(session_id):
    """
    Session specific notification stream
    :param session_id: the id of the current session
    """
    current_session = Session.objects.get(id=session_id)
    if isinstance(current_session, Session):
        # Open a new socket to stream messages to the server
        if request.method == 'GET':
            if request.environ.get(WSGI_WEBSOCKET):
                ws = request.environ[WSGI_WEBSOCKET]
                for message in current_session.queue.stream():
                    ws.send(message)

        # Add a new message to the stream
        elif request.method == 'POST':
            if isinstance(request.json, dict):
                current_session.queue.add(request.json)

    return "" 
Example #24
Source File: nlp_template.py    From tamil-lm2 with GNU General Public License v2.0 6 votes vote down vote up
def _predict():
           print(' requests incoming..')
           sentence = []
           try:
               input_string = word_tokenize(request.json["text"].lower())
               sentence.append([VOCAB[w] for w in input_string] + [VOCAB['EOS']])
               dummy_label = LongVar([0])
               sentence = LongVar(sentence)
               input_ = [0], (sentence,), (0, )
               output, attn = model(input_)
               #print(LABELS[output.max(1)[1]], attn)
               nwords = len(input_string)
               return jsonify({
                   "result": {
                       'sentence': input_string,
                       'attn': ['{:0.4f}'.format(i) for i in attn.squeeze().data.cpu().numpy().tolist()[:-1]],
                       'probs': ['{:0.4f}'.format(i) for i in output.exp().squeeze().data.cpu().numpy().tolist()],
                       'label': LABELS[output.max(1)[1].squeeze().data.cpu().numpy()]
                   }
               })
           
           except Exception as e:
               print(e)
               return jsonify({"result":"model failed"}) 
Example #25
Source File: service.py    From workload-collocation-agent with Apache License 2.0 6 votes vote down vote up
def _mutate_pod(self):
        annotations_key = "annotations"
        spec = request.json["request"]["object"]
        modified_spec = copy.deepcopy(spec)
        annotations = {}

        app_name = modified_spec["metadata"]["labels"]["app"]
        ratio = self._get_wss_to_mem_ratio(app_name)
        ratio_annotation = self._get_wss_to_mem_ratio_annotation(ratio)
        annotations.update(ratio_annotation)
        if ratio:
            memory_type_annotation = self._get_memory_type_annotation(float(ratio))
            annotations.update(memory_type_annotation)

        if not modified_spec["metadata"].get(annotations_key) and annotations:
            modified_spec["metadata"].update({annotations_key: {}})
        if annotations:
            modified_spec["metadata"][annotations_key].update(annotations)

        return self._create_patch(spec, modified_spec) 
Example #26
Source File: developers.py    From jbox with MIT License 6 votes vote down vote up
def modificate_integration(dev_key, integration_id):
    if not request.json or not 'channel' in request.json:
        abort(400)
    developer = get_developer_with_devkey(dev_key)
    integration = Integration.query.filter_by(developer_id=developer.id, integration_id=integration_id).first()
    if integration is None:
        abort(400)
    integration.channel.channel = request.json['channel']
    if 'name' in request.json:
        integration.name = request.json['name']
    if 'description' in request.json:
        integration.description = request.json['description']
    if 'icon' in request.json:
        integration.icon = request.json['icon']
    db.session.add(integration)
    try:
        db.session.commit()
    except:
        db.session.rollback()
        abort(500)
    return jsonify({'modification': True}), 200


# 保存 github 集成,将所选的仓库与之前的仓库比较,新增则生成 webhook, 否则去掉之前的 webhook 
Example #27
Source File: developers.py    From jbox with MIT License 6 votes vote down vote up
def modify_developer(dev_key):
    developer = Developer.query.filter_by(dev_key=dev_key).first()
    if developer is None:
        abort(404)
    if 'name' in request.json:
        developer.username = request.json['name']
    if 'desc' in request.json:
        developer.description = request.json['desc']
    if 'avatar' in request.json:
        developer.avatar = request.json['avatar']
    if 'email' in request.json:
        developer.email = request.json['email']
    db.session.add(developer)
    try:
        db.session.commit()
        return jsonify({'modified': True}), 200
    except:
        db.session.rollback()
        abort(500)


# 在dev_key 下创建一个 channel 
Example #28
Source File: developers.py    From jbox with MIT License 6 votes vote down vote up
def create_developer():
    if not request.json or not 'platform_id' in request.json:
        abort(400)
    developer = Developer.query.filter_by(platform_id=request.json['platform_id'],
                                          platform=request.json['platform']).first()
    if 'desc' in request.json:
        desc = request.json['desc']
    else:
        desc = ''
    if developer is None:
        dev_key = generate_dev_key()
        developer = Developer(dev_key=dev_key,
                              platform=request.json['platform'],
                              platform_id=request.json['platform_id'],
                              username=request.json['dev_name'],
                              email=request.json['email'],
                              description=desc)
        developer.insert_to_db()
        return jsonify({'dev_key': developer.dev_key}), 201
    else:
        return jsonify({'created': False}), 304


# 通过 platform 和 platform_id 来获取用户信息 
Example #29
Source File: app.py    From corpus-to-graph-ml with MIT License 6 votes vote down vote up
def score():
    if request.headers['Content-Type'] != 'application/json':
        resp = Response('Unssuported content type, expected application/json', status=500);
        return resp
    if (not request.json.has_key('text')):
        resp = Response('Bad request: missing "text" field in JSON body', status=500);
        return resp
    if (not request.json.has_key('entities')):
        resp = Response('Bad request: missing "entities" field in JSON body', status=500);
        return resp
    
    text = request.json['text']
    entities = request.json['entities']
    try:
        scorerResult = scorer.evaluate_score(text, entities)
        resp = jsonify(scorer_result_to_response_format(scorerResult))
        resp.status_code = 200
        return resp
    except Exception as e:
        resp = Response("Internal Server Error: %s"%e, status = 500)
        return resp 
Example #30
Source File: app.py    From corpus-to-graph-ml with MIT License 6 votes vote down vote up
def update_model():
    if request.headers['Content-Type'] != 'application/json':
        resp = Response('Unssuported content type, expected application/json', status=500);
        return resp
    if (not request.json.has_key('path')):
        resp = Response('Bad request: missing "path" field in JSON body', status=500);
        return resp
    
    path = request.json['path']
    try:
        scorer.load_model_from_url(path)
        resp = Response("", status=200);
        return resp
    except Exception as e:
        resp = Response("Internal Server Error: %s"%e, status = 500)
        return resp