flask.request.data.decode

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

19 Examples 7

Example 1

Project: docker-registry Source File: index.py
Function: put_repository
@app.route('/v1/repositories/<path:repository>', methods=['PUT'])
@app.route('/v1/repositories/<path:repository>/images',
           defaults={'images': True},
           methods=['PUT'])
@toolkit.parse_repository_name
@toolkit.requires_auth
def put_repository(namespace, repository, images=False):
    data = None
    try:
        # Note(dmp): unicode patch
        data = json.loads(flask.request.data.decode('utf8'))
    except ValueError:
        return toolkit.api_error('Error Decoding JSON', 400)
    if not isinstance(data, list):
        return toolkit.api_error('Invalid data')
    update_index_images(namespace, repository, flask.request.data)
    headers = generate_headers(namespace, repository, 'write')
    code = 204 if images is True else 200
    return toolkit.response('', code, headers)

Example 2

Project: 21datamarket Source File: datamarket.py
Function: add_sensor
@app.route('/publish', methods=['POST'])
@payment.required(get_publish_price)
def add_sensor():
    """"Add sensor to sensor registry"""

    sensor = request.data.decode('utf-8')

    hours = int(request.args.get('hours'))

    expire_date = datetime.now() + timedelta(hours=hours)

    sensor = json.loads(sensor)
    sensor['expireAt'] = expire_date

    sensor_id = sensors.insert_one(sensor).inserted_id

    return json.dumps({'sensor_id' : str(sensor_id), 'expireAt': expire_date.strftime("%Y-%m-%d %H:%M:%S")})

Example 3

Project: PyMessager Source File: api.py
@app.route(API_ROOT + FB_WEBHOOK, methods=['POST'])
def fb_receive_message():
    message_entries = json.loads(request.data.decode('utf8'))['entry']
    for entry in message_entries:
        messagings = entry['messaging']
        for message in messagings:
            sender = message['sender']['id']
            if message.get('message'):
                text = message['message']['text']
                print("{} says {}".format(sender, text))
    return "Hi"

Example 4

Project: playground21 Source File: dns-server.py
def get_price_register(request):
    try:
        body = request.data.decode('utf-8')
        in_obj = json.loads(body)
        days = int(in_obj['days'])
    except:
        return 0

    return get_price_register_days(days)

Example 5

Project: machine Source File: webhooks.py
@webhooks.route('/hook', methods=['POST'])
@log_application_errors
@enforce_signature
def app_hook():
    github_auth = current_app.config['GITHUB_AUTH']
    gag_status = current_app.config['GAG_GITHUB_STATUS']
    webhook_payload = json.loads(request.data.decode('utf8'))

    with db_connect(current_app.config['DATABASE_URL']) as conn:
        queue = db_queue(conn, TASK_QUEUE)
        success, response = process_github_payload(queue, request.url, current_app.logger,
                                                   github_auth, webhook_payload, gag_status)
    
    if not success:
        return Response(json.dumps(response), 500, content_type='application/json')

    return jsonify(response)

Example 6

Project: hooks Source File: hooks.py
@app.route('/hook', methods=['POST'])
def hook_publish():
    raw = request.data.decode("utf-8")
    try:
        event = json.loads(raw)
    except:
        return "Hook rejected: invalid JSON", 400
    repository = "{}/{}".format(event["repository"]["owner"]["name"], event["repository"]["name"])
    matches = [h for h in hooks if h.repository == repository]
    if len(matches) == 0:
        return "Hook rejected: unknown repository {}".format(repository)
    hook = matches[0]

    allow = False
    remote = request.remote_addr
    if remote == "127.0.0.1" and "X-Real-IP" in request.headers:
        remote = request.headers.get("X-Real-IP")
    for ip in hook.valid_ips.split(","):
        parts = ip.split("/")
        range = 32
        if len(parts) != 1:
            range = int(parts[1])
        addr = networkMask(parts[0], range)
        if addressInNetwork(dottedQuadToNum(remote), addr):
            allow = True
    if not allow:
        return "Hook rejected: unauthorized IP", 403

    if any("[noupdate]" in c["message"] for c in event["commits"]):
        return "Hook ignored: commit specifies [noupdate]"

    if "refs/heads/" + hook.branch == event["ref"]:
        print("Executing hook for " + hook.name)
        p=Popen(hook.command.split(), stdin=PIPE)
        p.communicate(input=raw.encode())
        return "Hook accepted"

    return "Hook ignored: wrong branch"

Example 7

Project: voltron Source File: core.py
    def __init__(self, *args, **kwargs):
        if 'server' in kwargs:
            self.server = kwargs['server']
            del kwargs['server']
        super(APIFlaskApp, self).__init__('voltron_api', *args, **kwargs)

        def api_post():
            res = self.server.handle_request(request.data.decode('UTF-8'))
            return Response(str(res), status=200, mimetype='application/json')

        def api_get():
            res = self.server.handle_request(str(api_request(request.path.split('/')[-1], **request.args.to_dict())))
            return Response(str(res), status=200, mimetype='application/json')

        # Handle API POST requests at /api/request
        api_post.methods = ["POST"]
        self.add_url_rule('/request', 'request', api_post)

        # Handle API GET requests at /api/<request_name> e.g. /api/version
        for plugin in voltron.plugin.pm.api_plugins:
            self.add_url_rule('/{}'.format(plugin), plugin, api_get)

Example 8

Project: docker-registry Source File: images.py
@app.route('/v1/images/<image_id>/json', methods=['PUT'])
@toolkit.requires_auth
@toolkit.valid_image_id
def put_image_json(image_id):
    data = None
    try:
        # Note(dmp): unicode patch
        data = json.loads(flask.request.data.decode('utf8'))
    except ValueError:
        pass
    if not data or not isinstance(data, dict):
        return toolkit.api_error('Invalid JSON')
    if 'id' not in data:
        return toolkit.api_error('Missing key `id\' in JSON')
    if image_id != data['id']:
        return toolkit.api_error('JSON data contains invalid id')
    if check_images_list(image_id) is False:
        return toolkit.api_error('This image does not belong to the '
                                 'repository')
    parent_id = data.get('parent')
    if parent_id and not store.exists(store.image_json_path(data['parent'])):
        return toolkit.api_error('Image depends on a non existing parent')
    elif parent_id and not toolkit.validate_parent_access(parent_id):
        return toolkit.api_error('Image depends on an unauthorized parent')
    json_path = store.image_json_path(image_id)
    mark_path = store.image_mark_path(image_id)
    if store.exists(json_path) and not store.exists(mark_path):
        return toolkit.api_error('Image already exists', 409)

    sender = flask.current_app._get_current_object()
    signal_result = signals.before_put_image_json.send(sender, image_json=data)
    for result_pair in signal_result:
        if result_pair[1] is not None:
            return toolkit.api_error(result_pair[1])

    # If we reach that point, it means that this is a new image or a retry
    # on a failed push
    store.put_content(mark_path, 'true')
    # We cleanup any old checksum in case it's a retry after a fail
    try:
        store.remove(store.image_checksum_path(image_id))
    except Exception:
        pass
    store.put_content(json_path, flask.request.data)
    layers.generate_ancestry(image_id, parent_id)
    return toolkit.response()

Example 9

Project: docker-registry Source File: tags.py
Function: set_properties
@app.route('/v1/repositories/<path:repository>/properties', methods=['PUT'])
@toolkit.parse_repository_name
@toolkit.requires_auth
def set_properties(namespace, repository):
    logger.debug("[set_access] namespace={0}; repository={1}".format(namespace,
                 repository))
    data = None
    try:
        # Note(dmp): unicode patch
        data = json.loads(flask.request.data.decode('utf8'))
    except ValueError:
        pass
    if not data or not isinstance(data, dict):
        return toolkit.api_error('Invalid data')
    private_flag_path = store.private_flag_path(namespace, repository)
    if (data['access'] == 'private'
       and not store.is_private(namespace, repository)):
        store.put_content(private_flag_path, '')
    elif (data['access'] == 'public'
          and store.is_private(namespace, repository)):
        # XXX is this necessary? Or do we know for sure the file exists?
        try:
            store.remove(private_flag_path)
        except Exception:
            pass
    return toolkit.response()

Example 10

Project: docker-registry Source File: tags.py
@app.route('/v1/repositories/<path:repository>/tags/<tag>',
           methods=['PUT'])
@toolkit.parse_repository_name
@toolkit.requires_auth
def put_tag(namespace, repository, tag):
    logger.debug("[put_tag] namespace={0}; repository={1}; tag={2}".format(
                 namespace, repository, tag))
    if not RE_VALID_TAG.match(tag):
        return toolkit.api_error('Invalid tag name (must match {0})'.format(
            RE_VALID_TAG.pattern
        ))
    data = None
    try:
        # Note(dmp): unicode patch
        data = json.loads(flask.request.data.decode('utf8'))
    except ValueError:
        pass
    if not data or not isinstance(data, basestring):
        return toolkit.api_error('Invalid data')
    if not store.exists(store.image_json_path(data)):
        return toolkit.api_error('Image not found', 404)
    store.put_content(store.tag_path(namespace, repository, tag), data)
    sender = flask.current_app._get_current_object()
    signals.tag_created.send(sender, namespace=namespace,
                             repository=repository, tag=tag, value=data)
    # Write some meta-data about the repos
    ua = flask.request.headers.get('user-agent', '')
    data = create_tag_json(user_agent=ua)
    json_path = store.repository_tag_json_path(namespace, repository, tag)
    store.put_content(json_path, data)
    if tag == "latest":  # TODO(dustinlacewell) : deprecate this for v2
        json_path = store.repository_json_path(namespace, repository)
        store.put_content(json_path, data)
    return toolkit.response()

Example 11

Project: flask-graphql Source File: graphqlview.py
    def parse_body(self, request):
        content_type = self.get_content_type(request)
        if content_type == 'application/graphql':
            return {'query': request.data.decode()}

        elif content_type == 'application/json':
            try:
                request_json = json.loads(request.data.decode('utf8'))
                assert isinstance(request_json, dict)
                return request_json
            except:
                raise HttpError(BadRequest('POST body sent invalid JSON.'))

        elif content_type == 'application/x-www-form-urlencoded':
            return request.form

        elif content_type == 'multipart/form-data':
            return request.form

        return {}

Example 12

Project: playground21 Source File: causeway-server.py
Function: put
@app.route('/put', methods=['POST'])
def put():
    '''Store a key-value pair.'''
    # get size of file sent
    # Validate JSON body w/ API params
    try:
        body = request.data.decode('utf-8')
        in_obj = json.loads(body)
    except:
        return ("JSON Decode failed", 400, {'Content-Type':'text/plain'})

    k = in_obj['key']
    v = in_obj['value']
    o = in_obj['address']
    n = in_obj['nonce']
    s = in_obj['signature']
     
    # check signature
    owner = Owner.query.filter_by(address=o).first()
    if owner.nonce not in n or wallet.verify_bitcoin_message(k + v + o + n, s, o):
        body = json.dumps({'error': 'Incorrect signature.'})
        code = 401
    else:
        size = len(k) + len(v)

        # check if owner has enough free storage
        # get free space from each of owner's buckets
        result = db.engine.execute('select * from sale where julianday("now") - \
                    julianday(sale.created) < sale.term order by sale.created desc')
        # choose newest bucket that has enough space
        sale_id = None
        for row in result:
            if (row[7] + size) < (1024 * 1024):
                sale_id = row[0]
    
        if sale_id is None:     # we couldn't find enough free space
            body = json.dumps({'error': 'Insufficient storage space.'})
            code = 403 
        else:
            # check if key already exists and is owned by the same owner
            kv = db.session.query(Kv).filter_by(key=k).filter_by(owner=o).first()
                    
            if kv is None:
                kv = Kv(k, v, o, sale_id)
                db.session.add(kv)
                db.session.commit()
            else:
                kv.value = v
                db.session.commit()
    
            s = db.session.query(Sale).get(sale_id)
            s.bytes_used = s.bytes_used + size
            db.session.commit()
            body = json.dumps({'result': 'success'})
            code = 201
    
    return (body, code, {'Content-length': len(body),
                        'Content-type': 'application/json',
                        }
           )

Example 13

Project: playground21 Source File: causeway-server.py
Function: delete
@app.route('/delete', methods=['POST'])
def delete():
    '''Delete a key-value pair.'''
    # Validate JSON body w/ API params
    try:
        body = request.data.decode('utf-8')
        in_obj = json.loads(body)
    except:
        return ("JSON Decode failed", 400, {'Content-Type':'text/plain'})

    k = in_obj['key']
    o = in_obj['address']
    n = in_obj['nonce']
    s = in_obj['signature']

    # check signature
    owner = Owner.query.filter_by(address=o).first()
    if owner.nonce not in n or wallet.verify_bitcoin_message(k + o + n, s, o):
        body = json.dumps({'error': 'Incorrect signature.'})
        code = 401
    else:
        # check if key already exists and is owned by the same owner
        kv = db.session.query(Kv).filter_by(key=k).filter_by(owner=o).first()
        if kv is None:
            body = json.dumps({'error': 'Key not found or not owned by caller.'})
            code = 404
        else:
            # free up storage quota and remove kv
            size = len(kv.value)
            sale_id = kv.sale
            s = db.session.query(Sale).get(sale_id)
            s.bytes_used = s.bytes_used - size
            db.session.delete(kv)
            db.session.commit()
            body = json.dumps({'result': 'success'})
            code = 200
    
    return (body, code, {'Content-length': len(body),
                         'Content-type': 'application/json',
                        }
           )

Example 14

Project: playground21 Source File: dns-server.py
@app.route('/dns/1/host.register', methods=['POST'])
@payment.required(get_price_register)
def cmd_host_register():

    # Validate JSON body w/ API params
    try:
        body = request.data.decode('utf-8')
        in_obj = json.loads(body)
    except:
        return http400("JSON Decode failed")

    try:
        if (not 'name' in in_obj or
            not 'domain' in in_obj):
            return http400("Missing name/domain")

        name = in_obj['name']
        domain = in_obj['domain']
        pkh = None
        days = 1
        if 'pkh' in in_obj:
            pkh = in_obj['pkh']
        if 'days' in in_obj:
            days = int(in_obj['days'])

        if not valid_name(name) or days < 1 or days > 365:
            return http400("Invalid name/days")
        if not db.valid_domain(domain):
            return http404("Domain not found")
        if pkh:
            base58.b58decode_check(pkh)
            if (len(pkh) < 20) or (len(pkh) > 40):
                return http400("Invalid pkh")
    except:
        return http400("JSON validation exception")

    # Check against reserved host name list
    if reserved_name(name):
        return http400("Reserved name.  Name not available for registration.")

    # Validate and collect host records for updating
    host_records = parse_hosts(name, domain, in_obj)
    if isinstance(host_records, str):
        return http400(host_records)

    return store_host(name, domain, days, pkh, host_records)

Example 15

Project: playground21 Source File: dns-server.py
@app.route('/dns/1/records.update', methods=['POST'])
@payment.required(int(USCENT / 5))
def cmd_host_update():

    # Validate JSON body w/ API params
    try:
        body = request.data.decode('utf-8')
        in_obj = json.loads(body)
    except:
        return http400("JSON Decode failed")

    # Validate JSON object basics
    try:
        if (not 'name' in in_obj or
            not 'domain' in in_obj or
            not 'hosts' in in_obj):
            return http400("Missing name/hosts")

        name = in_obj['name']
        domain = in_obj['domain']
        if not valid_name(name):
            return http400("Invalid name")
        if not db.valid_domain(domain):
            return http404("Domain not found")
    except:
        return http400("JSON validation exception")

    # Validate and collect host records for updating
    host_records = parse_hosts(name, domain, in_obj)
    if isinstance(host_records, str):
        return http400(host_records)

    # Verify host exists, and is not expired
    try:
        hostinfo = db.get_host(name, domain)
        if hostinfo is None:
            return http404("Unknown name")
    except:
        return http500("DB Exception")

    # Check permission to update
    pkh = hostinfo['pkh']
    if pkh is None:
        abort(403)
    sig_str = request.headers.get('X-Bitcoin-Sig')
    try:
        if not sig_str or not wallet.verify_bitcoin_message(body, sig_str, pkh):
            abort(403)
    except:
        abort(403)

    # Add to database.  Rely on db to filter out dups.
    try:
        if not nsupdate_exec(name, domain, host_records):
            http500("nsupdate failure")
        db.update_records(name, domain, host_records)
    except:
        return http400("DB Exception")

    return httpjson(True)

Example 16

Project: playground21 Source File: dns-server.py
@app.route('/dns/1/host.delete', methods=['POST'])
def cmd_host_delete():

    # Validate JSON body w/ API params
    try:
        body = request.data.decode('utf-8')
        in_obj = json.loads(body)
    except:
        return http400("JSON Decode failed")

    # Validate JSON object basics
    try:
        if (not 'name' in in_obj or
            not 'domain' in in_obj or
            not 'pkh' in in_obj):
            return http400("Missing name/pkh")

        name = in_obj['name']
        domain = in_obj['domain']
        pkh = in_obj['pkh']
        if (not valid_name(name) or (len(pkh) < 10)):
            return http400("Invalid name")
        if not db.valid_domain(domain):
            return http404("Domain not found")
    except:
        return http400("JSON validation exception")

    # Verify host exists, and is not expired
    try:
        hostinfo = db.get_host(name, domain)
        if hostinfo is None:
            return http404("Unknown name")
    except:
        return http500("DB Exception - get host")

    # Check permission to update
    if (hostinfo['pkh'] is None) or (pkh != hostinfo['pkh']):
        abort(403)
    sig_str = request.headers.get('X-Bitcoin-Sig')
    try:
        if not sig_str or not wallet.verify_bitcoin_message(body, sig_str, pkh):
            abort(403)
    except:
        abort(403)

    # Remove from database.  Rely on db to filter out dups.
    try:
        if not nsupdate_exec(name, domain, []):
            http500("nsupdate failure")
        db.delete_host(name, domain)
    except:
        return http400("DB Exception - delete host")

    return httpjson(True)

Example 17

Project: playground21 Source File: turk-server.py
@app.route('/task', methods=['POST'])
@payment.required(USCENT * 1)
def cmd_task_submit():

    # Validate JSON body w/ API params
    try:
        body = request.data.decode('utf-8')
        in_obj = json.loads(body)
    except:
        return ("JSON Decode failed", 400, {'Content-Type':'text/plain'})

    # Validate JSON object basics
    try:
        if (not 'pkh' in in_obj or
            not 'id' in in_obj or
            not 'tstamp' in in_obj or
            not 'answers' in in_obj):
            return ("Missing params", 400, {'Content-Type':'text/plain'})

        sig_str = request.headers.get('X-Bitcoin-Sig')

        pkh = in_obj['pkh']
        id = in_obj['id']
        tstamp = int(in_obj['tstamp'])
        answers = in_obj['answers']

        base58.b58decode_check(pkh)
        if not check_timestamp(tstamp):
            return ("Clock drift", 403, {'Content-Type':'text/plain'})
    except:
        return ("JSON validation exception", 400, {'Content-Type':'text/plain'})

    # Validate signature
    try:
        if not sig_str or not wallet.verify_bitcoin_message(body, sig_str, pkh):
            return ("Permission denied", 403, {'Content-Type':'text/plain'})
    except:
        return ("Permission denied", 403, {'Content-Type':'text/plain'})

    # Validate known worker and task
    try:
        worker = db.worker_get(pkh)
        if worker is None:
            return ("Permission denied", 403, {'Content-Type':'text/plain'})

        task = db.task_get(id)
        if task is None:
            abort(404)
    except:
        abort(500)

    # Self-check work template
    wt = worktmp.WorkTemplate()
    wt.set(task['template'])
    if not wt.valid():
        return ("JSON template self-validation failed", 500, {'Content-Type':'text/plain'})

    # Validate answers match work template
    wt.set_answers(answers)
    if not wt.answers_valid():
        return ("JSON answers validation failed", 400, {'Content-Type':'text/plain'})

    # Store answer in db
    try:
        answers_json = json.dumps(answers)
        db.answer_add(id, pkh, answers_json)
        db.worker_inc_done(pkh)
    except:
        return ("Initial answer storage failed", 400, {'Content-Type':'text/plain'})

    # If we have enough answers, compare work and payout
    process_work(id, task)

    body = json.dumps(True, indent=2)
    return (body, 200, {
        'Content-length': len(body),
        'Content-type': 'application/json',
    })

Example 18

Project: playground21 Source File: turk-server.py
Function: cmd_task_new
@app.route('/task.new', methods=['POST'])
@payment.required(USCENT * 10)
def cmd_task_new():

    # Validate JSON body w/ API params
    try:
        body = request.data.decode('utf-8')
        in_obj = json.loads(body)
    except:
        return ("JSON Decode failed", 400, {'Content-Type':'text/plain'})

    # Validate JSON object basics
    try:
        if (not 'pkh' in in_obj or
            not 'summary' in in_obj or
            not 'image' in in_obj or
            not 'image_ctype' in in_obj or
            not 'template' in in_obj or
            not 'min_workers' in in_obj or
            not 'reward' in in_obj):
            return ("Missing params", 400, {'Content-Type':'text/plain'})

        pkh = in_obj['pkh']
        summary = in_obj['summary']
        image = binascii.unhexlify(in_obj['image'])
        image_ctype = in_obj['image_ctype']
        template = in_obj['template']
        min_workers = int(in_obj['min_workers'])
        reward = int(in_obj['reward'])

        base58.b58decode_check(pkh)
    except:
        return ("JSON validation exception", 400, {'Content-Type':'text/plain'})

    # Check work template
    wt = worktmp.WorkTemplate()
    wt.set(template)
    if not wt.valid():
        return ("JSON template validation failed", 400, {'Content-Type':'text/plain'})

    # Generate unique id
    time_str = str(int(time.time()))
    md = hashlib.sha256()
    md.update(time_str.encode('utf-8'))
    md.update(body.encode('utf-8'))
    id = md.hexdigest()

    # Add worker to database.  Rely on db to filter out dups.
    try:
        template_json = json.dumps(template)
        db.task_add(id, summary, pkh, image, image_ctype, template_json, min_workers, reward)
    except:
        return ("DB Exception - add task", 400, {'Content-Type':'text/plain'})

    return (id, 200, {
        'Content-length': len(body),
        'Content-type': 'text/plain',
    })

Example 19

Project: playground21 Source File: turk-server.py
@app.route('/worker.new', methods=['POST'])
@payment.required(USCENT * 10)
def cmd_worker_new():

    # Validate JSON body w/ API params
    try:
        body = request.data.decode('utf-8')
        in_obj = json.loads(body)
    except:
        return ("JSON Decode failed", 400, {'Content-Type':'text/plain'})

    # Validate JSON object basics
    try:
        if (not 'payout_addr' in in_obj or
            not 'pkh' in in_obj):
            return ("Missing name/pkh", 400, {'Content-Type':'text/plain'})

        pkh = in_obj['pkh']
        payout_addr = in_obj['payout_addr']

        base58.b58decode_check(pkh)
        base58.b58decode_check(payout_addr)
    except:
        return ("JSON validation exception", 400, {'Content-Type':'text/plain'})

    # Add worker to database.  Rely on db to filter out dups.
    try:
        db.worker_add(pkh, payout_addr)
    except:
        return ("DB Exception - add worker", 400, {'Content-Type':'text/plain'})

    body = json.dumps(True, indent=2)
    return (body, 200, {
        'Content-length': len(body),
        'Content-type': 'application/json',
    })