Python flask.request 模块,data() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用flask.request.data()

项目:HBCTF    作者:osteth    | 项目源码 | 文件源码
def Player_Checkin():
    '''Accepts json formatted request containing the teams TeamID, IP, and Port and pushes the info over to CheckinUpdate to be stored in the DB
    json data should be in format {"TeamID": "Mudkips","IP": "192.168.0.1","Port": "5001"}
    Example: 
    curl -H "Content-Type: application/json" -X POST -d '{"TeamID": "Mudkips","IP": "192.168.0.1","Port": "5001"}' http://localhost:5001/checkin/
    '''
    try:
        checkin_resp = request.data
        IP = checkin_resp.get('IP')
        Port  = checkin_resp.get('Port')
        TeamID  = checkin_resp.get('TeamID')
        if IP and Port and TeamID is not None:
            Token, key = CheckinUpdate(IP, Port, TeamID)
            return {'Score Token': Token,
                    'Key': key}
        else:
            return {'Invalid': 'request'}
    except:
        return {'Invalid': 'request'}
项目:HBCTF    作者:osteth    | 项目源码 | 文件源码
def STS():
    '''Accepts players score submitions and passes its info over to ServiceScore funtion to validate the token and then update the teams score when its valid.
    json data should be in format {"TeamID": "Highlander","Token": "therecanbeonlyone"}
    Example: 
    curl -H "Content-Type: application/json" -X POST -d '{"TeamID": "Highlander","Token": "therecanbeonlyone"}' http://localhost:5001/ScoreTokentSubmit/
    '''
    try:
        sts_resp = request.data
        Token = sts_resp.get('Token')
        TeamID  = sts_resp.get('TeamID')
        if Token and TeamID is not None:
            print('Team ' + TeamID + 'has scored service points!')
            ServiceScore(TeamID, Token)
            return {'request data': request.data}
        else:
            return {'Invalid': 'request'}
    except:
        return {'Invalid': 'request'}
项目:FRG-Crowdsourcing    作者:97amarnathk    | 项目源码 | 文件源码
def post(self):
        """Post an item to the DB with the request.data JSON object.

        :arg self: The class of the object to be inserted
        :returns: The JSON item stored in the DB

        """
        try:
            self.valid_args()
            data = self._file_upload(request)
            if data is None:
                data = json.loads(request.data)
            self._forbidden_attributes(data)
            inst = self._create_instance_from_request(data)
            repo = repos[self.__class__.__name__]['repo']
            save_func = repos[self.__class__.__name__]['save']
            getattr(repo, save_func)(inst)
            self._log_changes(None, inst)
            return json.dumps(inst.dictize())
        except Exception as e:
            return error.format_exception(
                e,
                target=self.__class__.__name__.lower(),
                action='POST')
项目:FRG-Crowdsourcing    作者:97amarnathk    | 项目源码 | 文件源码
def _update_instance(self, oid):
        repo = repos[self.__class__.__name__]['repo']
        query_func = repos[self.__class__.__name__]['get']
        existing = getattr(repo, query_func)(oid)
        if existing is None:
            raise NotFound
        ensure_authorized_to('update', existing)
        data = json.loads(request.data)
        self._forbidden_attributes(data)
        # Remove hateoas links
        data = self.hateoas.remove_links(data)
        # may be missing the id as we allow partial updates
        data['id'] = oid
        self.__class__(**data)
        old = self.__class__(**existing.dictize())
        for key in data:
            setattr(existing, key, data[key])
        self._update_attribute(existing, old)
        update_func = repos[self.__class__.__name__]['update']
        self._validate_instance(existing)
        getattr(repo, update_func)(existing)
        self._log_changes(old, existing)
        return existing
项目:PokeAlarm    作者:PokeAlarm    | 项目源码 | 文件源码
def accept_webhook():
    try:
        log.debug("POST request received from {}.".format(request.remote_addr))
        data = json.loads(request.data)
        if type(data) == dict: # older webhook style
            data_queue.put(data)
        else:   # For RM's frame
            for frame in data:
                data_queue.put(frame)
    except Exception as e:
        log.error("Encountered error while receiving webhook ({}: {})".format(type(e).__name__, e))
        abort(400)
    return "OK"  # request ok


# Thread used to distribute the data into various processes (for RocketMap format)
项目:gke-gobang-app-example    作者:GoogleCloudPlatform    | 项目源码 | 文件源码
def put_stone_api(id):
    request_body = json.loads(request.data)
    try:
        x, y = int(request_body['x']), int(request_body['y'])
        player = int(request_body['player'])
        auto = int(request_body['auto'])
    except:
        response = jsonify({'result': 'error'})
        response.status_code = 500
        return response

    result = _put_stone(id, x, y, player, auto)
    if result == -1:
        response = jsonify({'result': 'error'})
        response.status_code = 500
    elif result == 1:
        response = jsonify({'result': 'win'})
        response.status_code = 200
    elif result == 99:
        response = jsonify({'result': 'end'})
        response.status_code = 200
    else:
        response = jsonify({'result': 'next'})
        response.status_code = 200
    return response
项目:pyldn    作者:albertmeronyo    | 项目源码 | 文件源码
def get_inbox():
    pyldnlog.debug("Requested inbox data of {} in {}".format(request.url, request.headers['Accept']))
    if not request.headers['Accept'] or request.headers['Accept'] == '*/*' or 'text/html' in request.headers['Accept']:
        resp = make_response(inbox_graph.serialize(format='application/ld+json'))
        resp.headers['Content-Type'] = 'application/ld+json'
    elif request.headers['Accept'] in ACCEPTED_TYPES:
        resp = make_response(inbox_graph.serialize(format=request.headers['Accept']))
        resp.headers['Content-Type'] = request.headers['Accept']
    else:
        return 'Requested format unavailable', 415

    resp.headers['X-Powered-By'] = 'https://github.com/albertmeronyo/pyldn'
    resp.headers['Allow'] = "GET, HEAD, OPTIONS, POST"
    resp.headers['Link'] = '<http://www.w3.org/ns/ldp#Resource>; rel="type", <http://www.w3.org/ns/ldp#RDFSource>; rel="type", <http://www.w3.org/ns/ldp#Container>; rel="type", <http://www.w3.org/ns/ldp#BasicContainer>; rel="type"'
    resp.headers['Accept-Post'] = 'application/ld+json, text/turtle'

    return resp
项目:pyldn    作者:albertmeronyo    | 项目源码 | 文件源码
def get_notification(id):
    pyldnlog.debug("Requested notification data of {}".format(request.url))
    pyldnlog.debug("Headers: {}".format(request.headers))

    # Check if the named graph exists
    pyldnlog.debug("Dict key is {}".format(pyldnconf._inbox_url + id))
    if pyldnconf._inbox_url + id not in graphs:
        return 'Requested notification does not exist', 404

    if 'Accept' not in request.headers or request.headers['Accept'] == '*/*' or 'text/html' in request.headers['Accept']:
        resp = make_response(graphs[pyldnconf._inbox_url + id].serialize(format='application/ld+json'))
        resp.headers['Content-Type'] = 'application/ld+json'
    elif request.headers['Accept'] in ACCEPTED_TYPES:
        resp = make_response(graphs[pyldnconf._inbox_url + id].serialize(format=request.headers['Accept']))
        resp.headers['Content-Type'] = request.headers['Accept']
    else:
        return 'Requested format unavailable', 415

    resp.headers['X-Powered-By'] = 'https://github.com/albertmeronyo/pyldn'
    resp.headers['Allow'] = "GET"

    return resp
项目:drift    作者:dgnorth    | 项目源码 | 文件源码
def register_extension(app):
    @app.before_request
    def add_correlation_id(*args, **kw):
        correlation_id = request.headers.get(CORRELATION_ID)
        log.debug("%s %s", request.method, request.url)
        if not correlation_id:
            correlation_id = str(uuid.uuid4())
            if request.method != "GET":
                """
                TODO: remove sensitive information such as username/password
                """
                log.debug({
                    "message": "Tracking request",
                    "correlation_id": correlation_id,
                    "method": request.method,
                    "uri": request.url,
                    "data": request.data,
                })
        request.correlation_id = correlation_id

    @app.after_request
    def save_correlation_id(response):
        if CORRELATION_ID not in response.headers:
            response.headers[CORRELATION_ID] = getattr(request, "correlation_id", None)
        return response
项目:QuitStore    作者:AKSW    | 项目源码 | 文件源码
def checkrequest(request):
    """Analyze RDF data contained in a POST request.

    Args:
        request: A Flask HTTP Request.
    Returns:
        data: A list with RDFLib.quads object and the rdflib.ConjunciveGraph object
    Raises:
        Exception: I contained data is not valid nquads.

    """
    data = []
    reqdata = request.data
    graph = ConjunctiveGraph()

    try:
        graph.parse(data=reqdata, format='nquads')
    except Exception as e:
        raise e

    quads = graph.quads((None, None, None, None))
    data = splitinformation(quads, graph)

    return data
项目:eagle    作者:saga92    | 项目源码 | 文件源码
def stop_instance():
    res = {}
    if request.method == 'POST':
        req_data = json.loads(request.data)
        db_session = db.Session()
        instance_query_result = db_session.query(Instance).filter(\
            Instance.container_serial == req_data['container_serial']).first()
        if instance_query_result is not None:
            policy = {}
            policy['operate'] = app.config['STOP']
            policy['container_serial'] = req_data['container_serial']
            policy['container_name'] = instance_query_result.container_name
            policy['user_name'] = req_data['user_name']
            message = json.dumps(policy)
            ui_mq = UiQueue()
            worker_res = ui_mq.send(message)
            worker_res_dict = json.loads(worker_res)
            res['code'] = worker_res_dict['code']
            res['message'] = worker_res_dict['message']
            res['container_serial'] = worker_res_dict['container_serial']
            eagle_logger.info(res['message'])
        else:
            res['code'] = '0x9'
            res['message'] = 'container not exist'
    return jsonify(**res)
项目:eagle    作者:saga92    | 项目源码 | 文件源码
def restart_instance():
    res = {}
    if request.method == 'POST':
        req_data = json.loads(request.data)
        db_session = db.Session()
        instance_query_result = db_session.query(Instance).filter(\
            Instance.container_serial == req_data['container_serial']).first()
        if instance_query_result is not None:
            policy = {}
            policy['operate'] = app.config['RESTART']
            policy['container_serial'] = req_data['container_serial']
            policy['container_name'] = instance_query_result.container_name
            policy['user_name'] = req_data['user_name']
            message = json.dumps(policy)
            ui_mq = UiQueue()
            worker_res = ui_mq.send(message)
            worker_res_dict = json.loads(worker_res)
            res = worker_res_dict
            eagle_logger.info(res['message'])
        else:
            res['code'] = '0x9'
            res['message'] = 'container not exist'
    return jsonify(**res)
项目:eagle    作者:saga92    | 项目源码 | 文件源码
def remove_instance():
    res = {}
    if request.method == 'POST':
        req_data = json.loads(request.data)
        db_session = db.Session()
        instance_query_result = db_session.query(Instance).filter(\
            Instance.container_serial == req_data['container_serial']).first()
        if instance_query_result is not None:
            policy = {}
            policy['operate'] = app.config['REMOVE']
            policy['container_serial'] = req_data['container_serial']
            policy['user_name'] = req_data['user_name']
            message = json.dumps(policy)
            ui_mq = UiQueue()
            worker_res = ui_mq.send(message)
            worker_res_dict = json.loads(worker_res)
            res['code'] = worker_res_dict['code']
            res['message'] = worker_res_dict['message']
            res['container_serial'] = worker_res_dict['container_serial']
            eagle_logger.info(res['message'])
        else:
            res['code'] = '0x9'
            res['message'] = 'container not exist'
    return jsonify(**res)
项目:lite-python    作者:Paybook    | 项目源码 | 文件源码
def login():
    try:
        # Log call and get params:
        logger = logging.getLogger('app')
        logger.debug('\n/login')
        params = json.loads(request.data)
        logger.debug(params)
        username = params['username']
        password = params['password']
        logger.debug('Executing ... ')
        # Data base and paybook logic:
        db_user = _DB.User(username,password)
        logger.debug('DB authentication ... ')
        if db_user.login():
            id_user = db_user.get_id_user()
            logger.debug('Id user: ' + str(id_user))
            pb_user = paybook_sdk.User(id_user=id_user)
            session = paybook_sdk.Session(user=pb_user)
            login_response = _Utilities.Success(session.get_json()).get_response()
        else:
            login_response = _Utilities.Error('Invalid username or password',400).get_response()
    except paybook_sdk.Error as error:
        login_response = error.get_json()
    return login_response
项目:lite-python    作者:Paybook    | 项目源码 | 文件源码
def credentials():
    try:
        # Log call and get params:
        logger = logging.getLogger('app')
        logger.debug('\n/credentials')
        params = json.loads(request.data)
        logger.debug(params)
        token = params['token']
        id_site = params['id_site'] if 'id_site' in params else None
        credentials = params['credentials']
        logger.debug('Executing ... ')
        # Paybook logic:
        session = paybook_sdk.Session(token=token)
        logger.debug('Creating credentials ... ')
        logger.debug(credentials)
        credentials = paybook_sdk.Credentials(session=session,id_site=id_site,credentials=credentials)
        logger.debug('Id credential: ' + credentials.id_credential)
        logger.debug('Twofa: ' + credentials.twofa)
        logger.debug("curl -X POST -d '{\"twofa_key\":\"token\",\"token\":\"4f3e7fe982f18898f970e4805b4774a3\",\"twofa\":\"" + credentials.twofa + "\",\"twofa_value\":\"test\",\"id_credential\":\"" + credentials.id_credential + "\"}' http://localhost:5000/twofa --header \"Content-Type:application/json\"")
        logger.debug('Sending response ... ')
        credentials_response = _Utilities.Success(credentials.get_json()).get_response()
    except paybook_sdk.Error as error:
        credentials_response = _Utilities.Error(error.message,error.code).get_response()
    return credentials_response
项目:lite-python    作者:Paybook    | 项目源码 | 文件源码
def delete_credentials():
    try:
        logger = logging.getLogger('app')
        logger.debug('\n/credentials')
        params = json.loads(request.data)
        logger.debug(params)
        token = params['token']
        id_credential = params['id_credential']
        logger.debug('Executing ... ')
        session = paybook_sdk.Session(token=token)
        credentials_deleted = paybook_sdk.Credentials.delete(session=session,id_credential=id_credential)
        logger.debug('Sending response ... ')
        delete_response = _Utilities.Success(credentials_deleted).get_response()
    except paybook_sdk.Error as error:
        delete_response = _Utilities.Error(error.message,error.code).get_response()
    return delete_response
项目:payments    作者:devops-s17-payments    | 项目源码 | 文件源码
def update_payments(id):
    try:
        if not request.is_json:
            raise DataValidationError('Invalid payment: Content Type is not json')
        data = request.get_json(silent=True)
        message = payment_service.update_payment(id,payment_replacement=data)
        rc = status.HTTP_200_OK
    except PaymentNotFoundError as e:
        message = e.message
        rc = status.HTTP_404_NOT_FOUND
    except DataValidationError as e:
        message = e.message
        rc = status.HTTP_400_BAD_REQUEST
    return make_response(jsonify(message), rc)

######################################################################
# UPDATE AN EXISTING PAYMENT PARTIALLY
######################################################################
项目:payments    作者:devops-s17-payments    | 项目源码 | 文件源码
def update_partial_payments(id):
    try:
        if not request.is_json:
            raise DataValidationError('Invalid payment: Content Type is not json')
        data = request.get_json(silent=True)
        message = payment_service.update_payment(id,payment_attributes=data)
        rc = status.HTTP_200_OK
    except PaymentNotFoundError as e:
        message = e.message
        rc = status.HTTP_404_NOT_FOUND
    except DataValidationError as e:
        message = e.message
        rc = status.HTTP_400_BAD_REQUEST
    return make_response(jsonify(message), rc)


######################################################################
# DELETE A PAYMENT
######################################################################
项目:microservices    作者:viatoriche    | 项目源码 | 文件源码
def render(self):
        if self.check_ignore_method():
            return self.data  # pragma: no cover
        response = {}
        self.update_by_name(response)
        self.update_by_info(response)
        self.update_by_request(response)
        self.update_by_status(response)
        self.update_by_status_code(response)
        self.update_by_headers(response)
        self.update_by_resource(response)
        self.update_by_methods(response)
        self.update_by_resources(response)
        self.update_by_update(response)
        self.update_by_data(response)
        return response
项目:Monzo-Meter    作者:d-Rickyy-b    | 项目源码 | 文件源码
def catch():
    j = json.loads(request.data)
    data = j['data']
    if mode == VARIABLE_MAX:
        if data['is_load']:
            # If you put money onto your account, save the amount of money as peak
            r.set("peak", int(data['amount']))
            r.set("balance", int(getRedisValue("balance")) + int(data['amount']))
        else:
            # If money is withdrawn OR in case of refunds or chargebacks the peak won't be set
            r.set("balance", int(getRedisValue("balance")) + int(data['amount']))

            if int(data['amount']) > int(getRedisValue("peak")):
                # Only if the current balance is greater than the saved peak, save it as peak
                r.set("peak", int(data['amount']))
    else:
        r.set("balance", int(getRedisValue("balance")) + int(data['amount']))
        r.set("peak", max_bal)

    notify_particle()
    return "{} | {}".format(r.get("balance"), r.get("peak"))
项目:Monzo-Meter    作者:d-Rickyy-b    | 项目源码 | 文件源码
def notify_particle():
    # The particle device gets notified about changes here
    peak_v = float(getRedisValue("peak"))
    balance_v = float(getRedisValue("balance"))

    # If the balance exceeds the peak/below 0, then the servo/needle might break.
    # Because of this, the angle's value gets checked before sending to particle.io
    if balance_v > peak_v:
        balance_v = peak_v
    elif balance_v < 0:
        balance_v = 0

    # Prevent division by zero
    if peak_v <= 0:
        peak_v = 1

    angle_v = angle(peak_v, balance_v)
    data = {"access_token": particle_token, "arg": angle_v}
    requests.post("https://api.particle.io/v1/devices/{}/gotoPos".format(device_id), data=data)
    return angle_v
项目:bitwrap-io    作者:bitwrap    | 项目源码 | 文件源码
def post(self):
        """ handle rpc calls """
        res = {}
        req = {}

        try:
            if request.data == '':
              payload = request.form.get('json')
            else:
              payload = request.data

            req = json.loads(payload)
            res['id'] = req.get('id')
            res['result'] = call(req['method'], req['params'])
            res['error'] = None
        except Exception as (ex):
            res = { 'id': req.get('id'), 'error': ex.message }

        return res, 200, None
项目:heroku-python-boilerplate    作者:chavli    | 项目源码 | 文件源码
def validate_jpeg_binary(func):
    """ checks the mimetype and the binary data to ensure it's a JPEG """
    @wraps(func)
    def wrapper(*args, **kwargs):
        if request.content_type != "image/jpeg":
            return ErrorResponseJson("invalid content type: {}".format(request.content_type)).make_response()
        if imghdr.test_jpeg(request.data, None) != "jpeg":
            return ErrorResponseJson("invalid jpeg data").make_response()
        return func(*args, **kwargs)
    return wrapper
项目:cc-server    作者:curious-containers    | 项目源码 | 文件源码
def validation(schema):
    """function decorator"""
    def dec(func):
        def wrapper(self, *args, **kwargs):
            try:
                rawdata = request.data
                enc = chardet.detect(rawdata)
                data = rawdata.decode(enc['encoding'])
                json_input = json.loads(data)
                jsonschema.validate(json_input, schema)
                json_input = prepare_input(json_input)
            except:
                raise BadRequest('JSON input not valid: {}'.format(format_exc()))
            return func(self, json_input, *args, **kwargs)
        return wrapper
    return dec
项目:pia    作者:soasme    | 项目源码 | 文件源码
def builtin_jq():
    """
    Builtin program: `jq`.
    It will run a `jq` progress and return a json object.
    """
    program = request.args.get('program', ".")
    command = request.data
    try:
        data = jq(program, command)
        resp = make_response(data)
        resp.content_type = 'application/json'
        return resp
    except InvalidJQFilter as exception:
        return jsonify(message=str(exception)), 400
项目:bitcointalk-sentiment    作者:DolphinBlockchainIntelligence    | 项目源码 | 文件源码
def transform():
    if model is None:
        abort(500, 'Model is not initialized.')
    global maxSeqLength
    global numFeatures
    global model
    response = {}
    for item in request.data['texts']:
        try:
            id = item['id']
            vector_sequence = get_sequence_matrix(get_tokens(item['text']), maxSeqLength, numFeatures, model).tolist()
            response[id] = vector_sequence
        except KeyError as e:
            abort(400, 'Wrong JSON format, key %s' % e)
        except Exception as e:
            abort(500, 'Internal server error: %s' % str(e))
        return jsonify(response)
项目:son-emu    作者:sonata-nfv    | 项目源码 | 文件源码
def _calculate_placement(self, algorithm):
        """
        Do placement by adding the a field "dc" to
        each VNFD that points to one of our
        data center objects known to the gatekeeper.
        """
        assert(len(self.vnfds) > 0)
        assert(len(GK.dcs) > 0)
        # instantiate algorithm an place
        p = algorithm()
        p.place(self.nsd, self.vnfds, self.saps, GK.dcs)
        LOG.info("Using placement algorithm: %r" % p.__class__.__name__)
        # lets print the placement result
        for name, vnfd in self.vnfds.iteritems():
            LOG.info("Placed VNF %r on DC %r" % (name, str(vnfd.get("dc"))))
        for sap in self.saps:
            sap_dict = self.saps[sap]
            LOG.info("Placed SAP %r on DC %r" % (sap, str(sap_dict.get("dc"))))
项目:son-emu    作者:sonata-nfv    | 项目源码 | 文件源码
def put(self, src_vnf, src_intfs, dst_vnf, dst_intfs):
        """
        A put request to "/v1/chain/<src_vnf>/<src_intfs>/<dst_vnf>/<dst_intfs>"
        will create a chain between two interfaces at the specified vnfs.

        Note:
           Does not allow a custom path. Uses ``.post``
           Internally just makes a POST request with no POST data!

        :param src_vnf: Name of the source VNF
        :type src_vnf: ``str``
        :param src_intfs: Name of the source VNF interface to chain on
        :type src_intfs: ``str``
        :param dst_vnf: Name of the destination VNF
        :type dst_vnf: ``str``
        :param dst_intfs: Name of the destination VNF interface to chain on
        :type dst_intfs: ``str``
        :return: flask.Response 200 if set up correctly else 500 also returns the cookie as dict {'cookie': value}
         501 if one of the VNF / intfs does not exist
        :rtype: :class:`flask.Response`
        """
        return self.post(src_vnf, src_intfs, dst_vnf, dst_intfs)
项目:son-emu    作者:sonata-nfv    | 项目源码 | 文件源码
def post(self):
        logging.debug("API CALL: %s POST" % str(self.__class__.__name__))

        try:
            request_dict = json.loads(request.data).get("port_pair")
            name = request_dict["name"]

            ingress_port = self.api.compute.find_port_by_name_or_id(request_dict["ingress"])
            egress_port = self.api.compute.find_port_by_name_or_id(request_dict["egress"])

            port_pair = self.api.compute.create_port_pair(name)
            port_pair.ingress = ingress_port
            port_pair.egress = egress_port
            if "description" in request_dict:
                port_pair.description = request_dict["description"]
            if "service_function_parameters" in request_dict:
                port_pair.service_function_parameters = request_dict["service_function_parameters"]

            resp = {
                "port_pair": port_pair.create_dict(self.api.compute)
            }
            return Response(json.dumps(resp), status=201, mimetype='application/json')
        except Exception as ex:
            logging.exception("Neutron SFC: %s Exception." % str(self.__class__.__name__))
            return Response(ex.message, status=500, mimetype='application/json')
项目:son-emu    作者:sonata-nfv    | 项目源码 | 文件源码
def post(self):
        logging.debug("API CALL: %s POST" % str(self.__class__.__name__))

        try:
            request_dict = json.loads(request.data).get("port_pair_group")

            port_pair_group = self.api.compute.create_port_pair_group(request_dict["name"])
            port_pair_group.port_pairs = request_dict["port_pairs"]
            if "description" in request_dict:
                port_pair_group.description = request_dict["description"]
            if "port_pair_group_parameters" in request_dict:
                port_pair_group.port_pair_group_parameters = request_dict["port_pair_group_parameters"]

            resp = {
                "port_pair_group": port_pair_group.create_dict(self.api.compute)
            }
            return Response(json.dumps(resp), status=201, mimetype='application/json')
        except Exception as ex:
            logging.exception("Neutron SFC: %s Exception." % str(self.__class__.__name__))
            return Response(ex.message, status=500, mimetype='application/json')
项目:son-emu    作者:sonata-nfv    | 项目源码 | 文件源码
def put(self, group_id):
        logging.debug("API CALL: %s PUT" % str(self.__class__.__name__))

        try:
            request_dict = json.loads(request.data).get("port_pair_group")
            port_pair_group = self.api.compute.find_port_pair_group_by_name_or_id(group_id)
            if "name" in request_dict:
                port_pair_group.name = request_dict["name"]
            if "description" in request_dict:
                port_pair_group.description = request_dict["description"]
            if "port_pairs" in request_dict:
                port_pair_group.port_pairs = request_dict["port_pairs"]

            resp = {
                "port_pair_group": port_pair_group.create_dict(self.api.compute)
            }
            return Response(json.dumps(resp), status=200, mimetype='application/json')
        except Exception as ex:
            logging.exception("Neutron SFC: %s Exception." % str(self.__class__.__name__))
            return Response(ex.message, status=500, mimetype='application/json')
项目:son-emu    作者:sonata-nfv    | 项目源码 | 文件源码
def put(self, flow_classifier_id):
        logging.debug("API CALL: %s PUT" % str(self.__class__.__name__))

        try:
            request_dict = json.loads(request.data).get("flow_classifier")
            flow_classifier = self.api.compute.find_flow_classifier_by_name_or_id(flow_classifier_id)
            if "name" in request_dict:
                flow_classifier.name = request_dict["name"]
            if "description" in request_dict:
                flow_classifier.description = request_dict["description"]

            resp = {
                "flow_classifier": flow_classifier.create_dict(self.api.compute)
            }
            return Response(json.dumps(resp), status=200, mimetype='application/json')
        except Exception as ex:
            logging.exception("Neutron SFC: %s Exception." % str(self.__class__.__name__))
            return Response(ex.message, status=500, mimetype='application/json')
项目:son-emu    作者:sonata-nfv    | 项目源码 | 文件源码
def post(self):
        logging.debug("API CALL: %s POST" % str(self.__class__.__name__))

        try:
            request_dict = json.loads(request.data).get("port_chain")

            port_chain = self.api.compute.create_port_chain(request_dict["name"])
            port_chain.port_pair_groups = request_dict["port_pair_groups"]
            if "description" in request_dict:
                port_chain.description = request_dict["description"]
            if "flow_classifiers" in request_dict:
                port_chain.flow_classifiers = request_dict["flow_classifiers"]
            if "chain_parameters" in request_dict:
                port_chain.chain_parameters = request_dict["chain_parameters"]

            port_chain.install(self.api.compute)

            resp = {
                "port_chain": port_chain.create_dict(self.api.compute)
            }
            return Response(json.dumps(resp), status=201, mimetype='application/json')
        except Exception as ex:
            logging.exception("Neutron SFC: %s Exception." % str(self.__class__.__name__))
            return Response(ex.message, status=500, mimetype='application/json')
项目:son-emu    作者:sonata-nfv    | 项目源码 | 文件源码
def post(self):
        """
        Creates a network with the name, specified within the request under ['network']['name'].

        :return: * 400, if the network already exists.
            * 500, if any exception occurred while creation.
            * 201, if everything worked out.
        :rtype: :class:`flask.response`
        """
        LOG.debug("API CALL: %s POST" % str(self.__class__.__name__))
        try:
            network_dict = json.loads(request.data)
            name = network_dict['network']['name']
            net = self.api.compute.find_network_by_name_or_id(name)
            if net is not None:
                return Response('Network already exists.\n', status=400, mimetype='application/json')

            net = self.api.compute.create_network(name)
            return Response(json.dumps({"network": net.create_network_dict()}), status=201, mimetype='application/json')
        except Exception as ex:
            LOG.exception("Neutron: Create network excepiton.")
            return Response(ex.message, status=500, mimetype='application/json')
项目:son-emu    作者:sonata-nfv    | 项目源码 | 文件源码
def post(self, id):
        LOG.debug("API CALL: %s POST" % str(self.__class__.__name__))
        data = json.loads(request.data).get("flavor")
        LOG.warning("Create Flavor: %s" % str(data))
        # add to internal dict
        f = self.api.compute.add_flavor(
            data.get("name"),
            data.get("vcpus"),
            data.get("ram"), "MB",
            data.get("disk"), "GB")
        # create response based on incoming data
        data["id"] = f.id
        data["links"] = [{'href': "http://%s:%d/v2.1/%s/flavors/%s" % (get_host(request),
                                                                       self.api.port,
                                                                       id,
                                                                       f.id)}]
        resp = {"flavor": data}
        return Response(json.dumps(resp), status=200, mimetype="application/json")
项目:son-emu    作者:sonata-nfv    | 项目源码 | 文件源码
def post(self, id):
        LOG.debug("API CALL: %s POST" % str(self.__class__.__name__))
        data = json.loads(request.data).get("flavor")
        LOG.warning("Create Flavor: %s" % str(data))
        # add to internal dict
        f = self.api.compute.add_flavor(
            data.get("name"),
            data.get("vcpus"),
            data.get("ram"), "MB",
            data.get("disk"), "GB")
        # create response based on incoming data
        data["id"] = f.id
        data["links"] = [{'href': "http://%s:%d/v2.1/%s/flavors/%s" % (get_host(request),
                                                                       self.api.port,
                                                                       id,
                                                                       f.id)}]
        resp = {"flavor": data}
        return Response(json.dumps(resp), status=200, mimetype="application/json")
项目:perseids-manifold    作者:RDACollectionsWG    | 项目源码 | 文件源码
def post(self, id=None):
        try:
            if id:
                raise NotFoundError()  # 404
            if app.service.enforcesAccess and not app.acl.get_permission(app.acl.get_user()).x:
                raise UnauthorizedError()
            objs = json.loads(request.data)
            if not isinstance(objs, list):
                raise ParseError()

            pids = app.db.get_service().providesCollectionPids
            if pids:
                    objs = [CollectionObject(**obj.update({'id': app.mint.get_id(CollectionObject)})) if isinstance(obj, dict) else obj for obj in objs]
            if app.db.ask_collection([obj.id for obj in objs]):
                raise ConflictError()
            app.db.set_collection(objs)
            return jsonify(objs), 201
        except (NotFoundError, DBError, UnauthorizedError, ConflictError):
            raise
        except:
            raise ParseError()  # 400
项目:perseids-manifold    作者:RDACollectionsWG    | 项目源码 | 文件源码
def put(self, id=None):
        try:
            if not id:
                raise NotFoundError()
            if app.service.enforcesAccess and not app.acl.get_permission(app.acl.get_user(),id).w:
                raise UnauthorizedError()
            c_obj = json.loads(request.data)
            if c_obj.id != id:
                raise ParseError()
            d_obj = app.db.get_collection(id)
            # todo: implement propertiesAreMutable check
            return jsonify(app.db.set_collection(c_obj)), 200
        except (NotFoundError, DBError, UnauthorizedError):
            raise
        except:
            raise ParseError()  # 400
项目:TFFRCNN    作者:InterVideo    | 项目源码 | 文件源码
def train_svm():
    data = json.loads(request.data)
    detections = data.get('detections', None)
    image = data.get('image', None)
    positive_crop = data.get('positive_crop', None)
    use_dense_sift = data.get('use_dense_sift', False)
    clustering = data.get('clustering', 'kmeans')
    augment_data = data.get('augment_data', True)

    if not (detections and image and positive_crop):
        return json.dumps({'error': 'Parameters error'})

    image = imread_from_base64(image)
    positive_crop = imread_from_base64(positive_crop)

    SVM_MODEL = train_exemplar_svm_on_sift_features(
        image, positive_crop,
        detections[0], detections[1],
        dense_sift=use_dense_sift,
        clustering=clustering,
        augment_data=augment_data
    )

    return json.dumps({'result': 'Success'})
项目:prayerbot    作者:c4tk    | 项目源码 | 文件源码
def post(self):
        """Facebook's API webhook."""
        print("Webhook request data: " + request.data)
        data = request.get_json()
        entry = data['entry'][0]
        messaging_events = entry['messaging']
        for event in messaging_events:
            sender_id = event['sender']['id']
            if 'message' in event:
                response_body = webhook.handle_message(sender_id, event['message'])
                if response_body:
                    self.api.post("/me/messages", response_body)
            elif 'postback' in event:
                response_callbacks = webhook.handle_postback(sender_id, event['postback'])
                for response_callback in response_callbacks:
                    self.api.post("/me/messages", response_callback)
        return "OK"
项目:Automate-it    作者:PacktPublishing    | 项目源码 | 文件源码
def hello():
    print request.data
    if request.method == 'GET':
        return request.args.get('hub.challenge')

    data = request.get_json()
    if data["object"] == "page":
        for entry in data["entry"]:
            for messaging_event in entry["messaging"]:
                if messaging_event.get("postback"):
                    sender_id = messaging_event["sender"]["id"]
                    payload = messaging_event["postback"]["payload"]
                    send_weburl(payload, sender_id)

                if messaging_event.get("message"):  # readers send us a message
                    sender_id = messaging_event["sender"]["id"]
                    send_postback(sender_id)


    return "ok", 200
项目:featkeeper    作者:ivansabik    | 项目源码 | 文件源码
def feature_request_add():
    data = request.data
    data_dict = json.loads(data)
    feature_requests_dict = {}
    feature_request = FeatureRequest(test=test_mode)
    feature_request.title = data_dict['title']
    feature_request.description = data_dict['description']
    feature_request.client_name = data_dict['client_name']
    feature_request.client_priority = data_dict['client_priority']
    feature_request.target_date = data_dict['target_date']
    feature_request.product_area = data_dict['product_area']
    feature_request.agent_name = data_dict['agent_name']
    feature_request.save()
    return jsonify({
        'status': 'success',
        'message': 'Feature request added',
        'feature_request': feature_request.to_dict()
    })

# Update existing feature request
项目:Python-scripts    作者:kojibhy    | 项目源码 | 文件源码
def home():
    valid = (request.data).decode()
    print(valid.__len__())
    print('HELOO NEW VISITOR:')
    if valid.__len__() != 0:

        #Place for Your PowerShell
        html = shell_generator()
        print('return: \n', html)
        print('Return powershell')

    else:
        html = 'error'
        print('Return error')

    return html
项目:microAuth    作者:Gingernaut    | 项目源码 | 文件源码
def login():
    try:
        res = json.loads(request.data) or None

        if not res:
            return custResponse(400, "data required for update")

        postEmail = res.get("emailAddress")
        postPass = res.get("password")

        if not utils.isValidEmail(postEmail):
            return custResponse(400, "Invalid email address.")

        if not utils.isValidPass(postPass):
            return custResponse(400, "Invalid password. Must be at least " + configFile["Security"]["minPassLength"] + " characters long.")

        accId = accFunctions.signin(postEmail, postPass)

        if not accId:
            return custResponse(400, "Login failed. Incorrect email or password")

        accData = accFunctions.getAccData(accId)
        accData["authToken"] =  accFunctions.genToken(accId)

        return custResponse(200, "Login Successful", accData)

    except Exception as e:

        if app.config["DEBUG"] == True:
            print("*-*-*-*")
            print(e)
            return custResponse(500,{"Err": str(e)})
        else:
            return custResponse(500, "An unknown error occured.")
项目:microAuth    作者:Gingernaut    | 项目源码 | 文件源码
def custResponse(code=404, message="Error: Not Found", data=None):

    message = {
        "status": code,
        "message": message
    }

    if data:
        for k, v in data.items():
            message[k] = v

    resp = jsonify(message)
    resp.status_code = code

    return resp
项目:HBCTF    作者:osteth    | 项目源码 | 文件源码
def dbconnect():
    with open('DBdata.json') as data_file:    
        data = json.load(data_file)
        ssl = data.get('ssl')
        username = data.get('username')
        password = data.get('password')
        host = data.get('host')
        port = data.get('port')
        data_file.close()
        if ssl is False:
            ssl = 'http://'
        else: 
            ssl = 'https://'
        couch = couchdb.Server(ssl + str(username) + ':' + str(password) + '@' + str(host) +':' + str(port) + '/')
        return(couch)
项目:HBCTF    作者:osteth    | 项目源码 | 文件源码
def CheckinUpdate(IP, Port, TeamID):
    '''Takes in data from Player_Checkin and udates the database.'''
    key = subcipher.generate_key()
    Token = RandomToken(64)
    encrypted = subcipher.encrypt(key, Token)
    return(Token, key)
项目:HBCTF    作者:osteth    | 项目源码 | 文件源码
def ServiceScore(TeamID, Token):
    '''takes in data from STS, checks token for validity and increases the teams score if valid.'''
    return()
项目:flask-apidoc    作者:ipconfiger    | 项目源码 | 文件源码
def gathering_body(data_type):
    """
    ??request.data ??post?json??
    :param data_type: 
    :type data_type: 
    :return: 
    :rtype: 
    """
    return data_type.from_json_dict(request.get_json())
项目:repository-gardener    作者:GoogleCloudPlatform    | 项目源码 | 文件源码
def webhook():
    webhook_helper.check_signature(
        request.headers['X-Hub-Signature'],
        request.data)
    logging.info('Delivery: {}'.format(
        request.headers.get('X-GitHub-Delivery')))
    result = webhook_helper.process(request)
    return jsonify(result)