Python flask.request.get_json() Examples

The following are 30 code examples of flask.request.get_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: views.py    From beavy with Mozilla Public License 2.0 9 votes vote down vote up
def submit_story():
    if request.method == "POST":
        params = request.get_json()
        title, url = params['title'].strip(), params['url'].strip()
        text = params.get('text', "").strip()
        if not title:
            return abort(400, "You have to provide a 'title'")

        if url:
            link = Link(title=title, url=url, owner_id=current_user.id)
            db.session.add(link)
            db.session.commit()
            return link_schema.dump(link)
        elif text:
            topic = Topic(title=title, text=text, owner_id=current_user.id)
            db.session.add(topic)
            db.session.commit()
            return topic_schema.dump(topic)

        return abort(400, "You have to provide either 'url' or 'text', too")

    # Just render it
    return {} 
Example #2
Source File: server.py    From BASS with GNU General Public License v2.0 8 votes vote down vote up
def whitelist_add():
    log.info("whitelist_add called")
    try:
        file_ = request.files["file"]
        handle, filename = tempfile.mkstemp()
        os.close(handle)
        file_.save(filename)
        data = request.get_json()
        if data and "functions" in data:
            functions = data["functions"]
        else:
            functions = None
        bass.whitelist_add(filename, functions)
        os.unlink(filename)
    except KeyError:
        log.exception("")
        return make_response(jsonify(message = "Sample file 'file' missing in POST request"), 400)

    return jsonify(message = "OK") 
Example #3
Source File: reconng.py    From bounty_tools with MIT License 7 votes vote down vote up
def run():

    # Setup the jsonrpclib for the recon-ng RPC server, stop the API if it cannot connect to the RPC server.
    try:
        client = jsonrpclib.Server('http://localhost:4141')
        sid = client.init()

        # Get the configuration from JSON POST
        content = request.get_json()
        target_module = content['module']
        target_domain = content['domain']
        print(target_domain, target_module)

        # Set the target domain
        client.add('domains', target_domain, sid)
        print(client.show('domains', sid))
        client.use(target_module, sid)

        # Execute the requested module and return the results
        results = client.run(sid)

        return jsonify(results)

    except:
        return traceback.format_exc(), 500 
Example #4
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 #5
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 #6
Source File: user_info.py    From app with MIT License 6 votes vote down vote up
def create_api_key():
    """Used to create a new api key
    Input:
    - device

    Output:
    - api_key
    """
    data = request.get_json()
    if not data:
        return jsonify(error="request body cannot be empty"), 400

    device = data.get("device")

    api_key = ApiKey.create(user_id=g.user.id, name=device)
    db.session.commit()

    return jsonify(api_key=api_key.code), 201 
Example #7
Source File: routes.py    From dino with Apache License 2.0 6 votes vote down vote up
def update_channel_name(channel_uuid: str):
    form = request.get_json()
    name = form['name']

    try:
        channel_manager.rename(channel_uuid, name)
    except ChannelNameExistsException:
        return api_response(400, message='A channel with that name already exists')
    except EmptyChannelNameException:
        return api_response(400, message='Blank channel name is not allowed')

    return api_response(200) 
Example #8
Source File: views.py    From xcessiv with Apache License 2.0 6 votes vote down vote up
def create_new_ensemble():
    req_body = request.get_json()
    ensemble_name = req_body['ensemble_name']

    if os.path.exists(ensemble_name):
        return jsonify(message="File/folder already exists"), 400

    os.makedirs(ensemble_name)
    xcessiv_notebook_path = os.path.join(ensemble_name, app.config['XCESSIV_NOTEBOOK_NAME'])
    sqlite_url = 'sqlite:///{}'.format(xcessiv_notebook_path)
    engine = create_engine(sqlite_url)

    models.Base.metadata.create_all(engine)

    # Initialize
    extraction = models.Extraction()
    with functions.DBContextManager(ensemble_name) as session:
        session.add(extraction)
        session.commit()

    return jsonify(message="Xcessiv notebook created") 
Example #9
Source File: views.py    From xcessiv with Apache License 2.0 6 votes vote down vote up
def extraction_stacked_ensemble_cv():
    path = functions.get_path_from_query_string(request)

    if request.method == 'GET':
        with functions.DBContextManager(path) as session:
            extraction = session.query(models.Extraction).first()
            return jsonify(extraction.stacked_ensemble_cv)

    if request.method == 'PATCH':
        req_body = request.get_json()
        with functions.DBContextManager(path) as session:
            extraction = session.query(models.Extraction).first()
            for key, value in six.iteritems(req_body):
                extraction.stacked_ensemble_cv[key] = value
            session.add(extraction)
            session.commit()
            return jsonify(extraction.stacked_ensemble_cv) 
Example #10
Source File: auth.py    From app with MIT License 6 votes vote down vote up
def forgot_password():
    """
    User forgot password
    Input:
        email
    Output:
        200 and a reset password email is sent to user
        400 if email not exist

    """
    data = request.get_json()
    if not data or not data.get("email"):
        return jsonify(error="request body must contain email"), 400

    email = data.get("email").strip().lower()

    user = User.get_by(email=email)

    if user:
        send_reset_password_email(user)

    return jsonify(ok=True) 
Example #11
Source File: views.py    From xcessiv with Apache License 2.0 6 votes vote down vote up
def extraction_meta_feature_generation():
    path = functions.get_path_from_query_string(request)

    if request.method == 'GET':
        with functions.DBContextManager(path) as session:
            extraction = session.query(models.Extraction).first()
            return jsonify(extraction.meta_feature_generation)

    if request.method == 'PATCH':
        req_body = request.get_json()
        with functions.DBContextManager(path) as session:
            extraction = session.query(models.Extraction).first()
            for key, value in six.iteritems(req_body):
                extraction.meta_feature_generation[key] = value
            session.add(extraction)
            session.commit()
            return jsonify(extraction.meta_feature_generation) 
Example #12
Source File: jsonapi-test.py    From py-flask-jsontools with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def testUpdate(self):
        """ Test PATCH /user/<id>: custom error codes, exceptions """
        with self.app.test_client() as c:
            # JSON error
            rv = c.patch('/user/1')
            self.assertEqual(rv.status_code, 403)
            self.assertIsInstance(rv, JsonResponse)
            self.assertEqual(rv.get_json(), {'error': 'Denied'})

            # JSON user
            rv = c.patch('/user/2', {'user': {'id': 2, 'name': 'bbb'}})
            self.assertEqual(rv.status_code, 200)
            self.assertIsInstance(rv, JsonResponse)
            self.assertEqual(rv.get_json(), {'id': 2, 'name': 'bbb'})

            # IndexError
            self.assertRaises(IndexError, c.patch, '/user/99', {'user': {}}) 
Example #13
Source File: views.py    From xcessiv with Apache License 2.0 6 votes vote down vote up
def extraction_test_dataset():
    path = functions.get_path_from_query_string(request)

    if request.method == 'GET':
        with functions.DBContextManager(path) as session:
            extraction = session.query(models.Extraction).first()
            return jsonify(extraction.test_dataset)

    if request.method == 'PATCH':
        req_body = request.get_json()
        with functions.DBContextManager(path) as session:
            extraction = session.query(models.Extraction).first()
            for key, value in six.iteritems(req_body):
                extraction.test_dataset[key] = value
            session.add(extraction)
            session.commit()
            return jsonify(extraction.test_dataset) 
Example #14
Source File: views.py    From xcessiv with Apache License 2.0 6 votes vote down vote up
def extraction_main_dataset():
    path = functions.get_path_from_query_string(request)

    if request.method == 'GET':
        with functions.DBContextManager(path) as session:
            extraction = session.query(models.Extraction).first()
            return jsonify(extraction.main_dataset)

    if request.method == 'PATCH':
        req_body = request.get_json()
        with functions.DBContextManager(path) as session:
            extraction = session.query(models.Extraction).first()
            for key, value in six.iteritems(req_body):
                extraction.main_dataset[key] = value
            session.add(extraction)
            session.commit()
            return jsonify(extraction.main_dataset) 
Example #15
Source File: app.py    From deepchem with MIT License 6 votes vote down vote up
def minimize():
  content = request.get_json(force=True)
  if not content or not 'X' in content:
    abort(400)
  X = np.array(content['X'])

  constraints = None

  if 'constraints' in content:
    constraints = content['constraints']
    print('setting constraints')

  num_atoms = X.shape[0]
  x0 = X[:, 1:]
  a0 = X[:, :1]

  res = webapp.model.minimize_structure(x0, a0, constraints)
  res = res.reshape((num_atoms, 3))
  y = webapp.model.pred_one(res, a0).tolist()[0]

  return flask.jsonify({'X': res.tolist(), 'y': y}), 200 
Example #16
Source File: views.py    From CTask with GNU General Public License v3.0 6 votes vote down vote up
def edit_job():
    '''修改作业'''
    response = {'status': '-1'}
    try:
        data = request.get_json(force=True)
        job_id = data.get('id')
        old_job = scheduler.get_job(job_id)
        if old_job:
            jobfromparm(scheduler,**data)
            response['status'] = 0
            response['message'] = "job[%s] edit success!"%job_id
        else:
            response['message'] = "job[%s] Not Found!"%job_id
    except Exception as e:
        response['message'] = str(e)
    return json.dumps(response) 
Example #17
Source File: views.py    From CTask with GNU General Public License v3.0 6 votes vote down vote up
def reomve_jobs():
    '''删除作业'''
    response = {'status': '-1'}
    try:
        data = request.get_json(force=True)
        job_id = data.get('id')
        if job_id != 'all':
            scheduler.remove_job(job_id)
            response['msg'] = "job[%s] remove success!"%job_id
        else:
            scheduler.remove_all_jobs()
            response['msg'] = "job all remove success!"
        response['status'] = 0
    except Exception as e:
        response['msg'] = str(e)
    return json.dumps(response) 
Example #18
Source File: main.py    From flask-boilerplate with MIT License 6 votes vote down vote up
def create_person():
    data = request.get_json()

    logger.info("Data recieved: %s", data)
    if "name" not in data:
        msg = "No name provided for person."
        logger.info(msg)
        return create_response(status=422, message=msg)
    if "email" not in data:
        msg = "No email provided for person."
        logger.info(msg)
        return create_response(status=422, message=msg)

    # create SQLAlchemy Objects
    new_person = Person(name=data["name"])
    email = Email(email=data["email"])
    new_person.emails.append(email)

    # commit it to database
    db.session.add_all([new_person, email])
    db.session.commit()
    return create_response(
        message=f"Successfully created person {new_person.name} with id: {new_person._id}"
    ) 
Example #19
Source File: api.py    From vanguard-api with MIT License 5 votes vote down vote up
def register_security_answer():
    #request_data = request.get_json(force=True)

    try:
        user = auth()
    except AuthenticationFailed:
        return rAuthError

    try:
        params = get_from_request_data(["username","service_info"])
        service_info = params["service_info"]
    except MissingRequestParams:
        #Missing username is handled by auth()
        return rMissingServiceInfo

    service_name = service_info.get("service_name")
    question = service_info.get("question")
    answer = service_info.get("answer")
    if None in [service_name, question, answer]:
        return rMissingParams(["service_name", "question", "answer"])

    try:
        Users.register_security_answer(user['user'], service_name, question, answer)
    except RuntimeError as e:
        return rInternalServerError

    return "OK\n"

# Vanguard Routes 
Example #20
Source File: routes.py    From dino with Apache License 2.0 5 votes vote down vote up
def update_room_acl(channel_uuid: str, room_uuid: str, action: str, acl_type: str):
    form = request.get_json()
    value = form['value']
    
    try:
        acl_manager.update_room_acl(channel_uuid, room_uuid, action, acl_type, value)
    except InvalidAclValueException:
        return api_response(400, message='Invalid ACL value %s' % value)
    except InvalidAclTypeException:
        return api_response(400, message='Invalid ACL type %s' % acl_type)
    except ValidationException as e:
        return api_response(400, message='Invalid ACL: %s' % e.msg)
    except Exception as e:
        logger.exception(traceback.format_exc())
        return api_response(400, message='could not update acl for room %s: %s' % (room_uuid, str(e)))
    
    return api_response(200) 
Example #21
Source File: app.py    From deepchem with MIT License 5 votes vote down vote up
def potential():
  content = request.get_json(force=True)
  if not content or not 'X' in content:
    abort(400)
  X = np.array(content['X'])
  x0 = X[:, 1:]
  a0 = X[:, :1]
  result = webapp.model.pred_one(x0, a0)
  return flask.jsonify({'y': result.tolist()[0]}), 200 
Example #22
Source File: server.py    From web-document-scanner with MIT License 5 votes vote down vote up
def capture_status():
    global video_camera 

    if video_camera == None:
        video_camera = VideoCamera()

    json = request.get_json()

    status = json['status']

    if status == "true":
        video_camera.capture_frame()
        return jsonify(result="done") 
Example #23
Source File: routes.py    From dino with Apache License 2.0 5 votes vote down vote up
def send_broadcast():
    form = request.get_json()
    verb = form['verb']
    content = form['content']

    message = {}
    if is_blank(verb):
        message['verb'] = 'Verb may not be empty.'
    if is_blank(content):
        message['content'] = 'Content may not be empty.'

    if len(message):
        return api_response(400, message=message)

    try:
        content = utils.b64e(content)
        broadcast_manager.send(content, verb)
    except Exception as e:
        logger.error('Could not send broadcast: %s' % str(e))
        logger.exception(traceback.format_exc())
        return api_response(400, message='Could not send broadcast')
    return api_response(200) 
Example #24
Source File: routes.py    From dino with Apache License 2.0 5 votes vote down vote up
def add_to_blacklist():
    form = request.get_json()
    words = form['words']
    try:
        blacklist_manager.add_words(words)
    except Exception as e:
        logger.error('Could not add word to blacklist: %s' % str(e))
        return api_response(400, message='Could not add word to blacklist: %s' % str(e))
    return api_response(200) 
Example #25
Source File: routes.py    From dino with Apache License 2.0 5 votes vote down vote up
def search_history():
    form = request.get_json()
    user_uuid = form['user']
    room_uuid = form['room']
    from_time = form['from']
    to_time = form['to']

    user_name = get_user_name(user_uuid)
    room_name = get_room_name(room_uuid)

    try:
        msgs, real_from_time, real_to_time = storage_manager.find_history(room_uuid, user_uuid, from_time, to_time)
    except Exception as e:
        logger.error('Could not get messages: %s' % str(e))
        logger.exception(traceback.format_exc())
        return api_response(400, message='Could not get message: %s' % str(e))

    try:
        clean_msgs = list()
        for message in msgs:
            try:
                json_body = message['body']
                json_body = json.loads(json_body)
                json_body = json_body.get('text')
                message['body'] = json_body
            except Exception:
                pass  # ignore, use original
            clean_msgs.append(message)
    except Exception as e:
        logger.error('Could not clean messages, will use original: %s' % str(e))
        clean_msgs = msgs

    return api_response(200, {
        'message': clean_msgs,
        'real_from_time': real_from_time,
        'real_to_time': real_to_time,
        'username': user_name,
        'room': room_name,
    }) 
Example #26
Source File: routes.py    From dino with Apache License 2.0 5 votes vote down vote up
def spam_set_settings():
    try:
        form = request.get_json()

        if form is None:
            return api_response(400, message='no json data in request')

        enabled = form.get('enabled', None)
        max_length = form.get('max_length', None)
        min_length = form.get('min_length', None)
        threshold = form.get('threshold', None)
        should_delete = form.get('should_delete', None)
        ignore_emoji = form.get('ignore_emoji', None)
        should_save = form.get('should_save', None)

        settings = spam_manager.set_settings(
            enabled, max_length, min_length,
            should_delete, should_save, threshold, ignore_emoji
        )
    except Exception as e:
        msg = 'Could not set settings: {}'.format(str(e))
        logger.error(msg)
        logger.exception(traceback.format_exc())
        environ.env.capture_exception(sys.exc_info())
        return api_response(400, message=msg)

    return api_response(200, settings) 
Example #27
Source File: routes.py    From dino with Apache License 2.0 5 votes vote down vote up
def create_super_user():
    form = request.get_json()
    user_name = str(form['name']).strip()
    user_uuid = str(form['uuid']).strip()

    message = {}
    if is_blank(user_name):
        message['name'] = 'Blank user name is not allowed.'
    if is_blank(user_uuid):
        message['uuid'] = 'Blank user id is not allowed.'

    if len(message):
        return api_response(400, message=message)
    user_manager.create_super_user(user_name, user_uuid)
    return api_response(200) 
Example #28
Source File: routes.py    From dino with Apache License 2.0 5 votes vote down vote up
def remove_ban(user_uuid: str):
    form = request.get_json()
    target = form['target']
    target_uuid = form['target_uuid']
    user_manager.remove_ban(user_uuid, target_uuid, target)
    return api_response(200)


####################################
#           Super Users            #
#################################### 
Example #29
Source File: routes.py    From dino with Apache License 2.0 5 votes vote down vote up
def ban_user():
    form = request.get_json()
    target = form['target']
    target_uuid = form['target_uuid']
    user_uuid = form['user_uuid']
    duration = form['duration']

    try:
        user_manager.ban_user(user_uuid, target_uuid, duration, target)
    except ValidationException as e:
        return api_response(400, message='invalid duration: %s' % str(e))
    except UnknownBanTypeException as e:
        return api_response(400, message='could not ban user: %s' % str(e))
    except Exception as e:
        logger.exception(traceback.format_exc())
        return api_response(400, message=str(e))

    try:
        user = user_manager.get_user(user_uuid)
        user['name'] = utils.b64d(user['name'])
        user['duration'] = duration
    except NoSuchUserException:
        return api_response(400, message="No such user.")

    if target == 'channel':
        user['channel'] = {
            'uuid': target_uuid,
            'name': channel_manager.name_for_uuid(target_uuid)
        }
    elif target == 'room':
        user['room'] = {
            'uuid': target_uuid,
            'name': room_manager.name_for_uuid(target_uuid)
        }
    return api_response(200, user) 
Example #30
Source File: inference_rest_api.py    From FARM with Apache License 2.0 5 votes vote down vote up
def post(self, model_id):
        model = INFERENCERS.get(model_id, None)
        if not model:
            return "Model not found", 404

        dicts = request.get_json().get("input", None)
        if not dicts:
            return {}
        results = model.inference_from_dicts(dicts=dicts, rest_api_schema=True)
        return results[0]