Python flask.request.headers() Examples

The following are 30 code examples of flask.request.headers(). 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: server.py    From grlc with MIT License 8 votes vote down vote up
def query(user, repo, query_name, subdir=None, spec_url=None, sha=None, content=None):
    """Execute SPARQL query for a specific grlc-generated API endpoint"""
    glogger.info("-----> Executing call name at /{}/{}/{}/{} on commit {}".format(user, repo, subdir, query_name, sha))
    glogger.debug("Request accept header: " + request.headers["Accept"])

    requestArgs = request.args
    acceptHeader = request.headers['Accept']
    requestUrl = request.url
    formData = request.form

    query_response, status, headers = utils.dispatch_query(user, repo, query_name, subdir, spec_url,
                                                           sha=sha, content=content, requestArgs=requestArgs,
                                                           acceptHeader=acceptHeader,
                                                           requestUrl=requestUrl, formData=formData)
    if isinstance(query_response, list):
        query_response = jsonify(query_response)

    return make_response(query_response, status, headers)

### Server routes ### 
Example #2
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 #3
Source File: user_info.py    From app with MIT License 6 votes vote down vote up
def user_info():
    """
    Call by client to get user information
    Usually bearer token is used.
    """
    if "AUTHORIZATION" in request.headers:
        access_token = request.headers["AUTHORIZATION"].replace("Bearer ", "")
    else:
        access_token = request.args.get("access_token")

    oauth_token: OauthToken = OauthToken.get_by(access_token=access_token)
    if not oauth_token:
        return jsonify(error="Invalid access token"), 400
    elif oauth_token.is_expired():
        LOG.d("delete oauth token %s", oauth_token)
        OauthToken.delete(oauth_token.id)
        db.session.commit()
        return jsonify(error="Expired access token"), 400

    client_user = ClientUser.get_or_create(
        client_id=oauth_token.client_id, user_id=oauth_token.user_id
    )

    return jsonify(client_user.get_user_info()) 
Example #4
Source File: views.py    From PyOne with Mozilla Public License 2.0 6 votes vote down vote up
def redirect_file(user,fileid):
    filename=GetName(fileid)
    downloadUrl,play_url=GetDownloadUrl(fileid,user)
    req = browser.get(play_url, stream = True)
    headers = dict([(name, value) for (name, value) in req.raw.headers.items()])
    cache_root=os.path.join(GetConfig('config_dir'),'cache')
    if not os.path.exists(cache_root):
        os.mkdir(cache_root)
    filepath=os.path.join(cache_root,filename)
    if not os.path.exists(filepath):
        with open(filepath,'wb') as f:
            for chunk in req.iter_content(1024):
                if chunk:
                    f.write(chunk)
                    f.flush()
    resp=send_file(filepath,conditional=True)
    return resp 
Example #5
Source File: webhook.py    From Matrix-NEB with Apache License 2.0 6 votes vote down vote up
def do_POST(self, service=""):
        log.debug("NebHookServer: Plugin=%s : Incoming request from %s",
                  service, request.remote_addr)
        if service.split("/")[0] not in self.plugin_mappings:
            return ("", 404, {})

        plugin = self.plugin_mappings[service.split("/")[0]]

        try:
            # tuple (body, status_code, headers)
            response = plugin.on_receive_webhook(
                request.url,
                request.get_data(),
                request.remote_addr,
                request.headers
            )
            if response:
                return response
            return ("", 200, {})
        except Exception as e:
            log.exception(e)
            return ("", 500, {}) 
Example #6
Source File: run.py    From cloud-asr with Apache License 2.0 6 votes vote down vote up
def recognize_batch():
    data = {
        "model": request.args.get("lang", "en-GB"),
        "lm": request.args.get("lm", "default"),
        "wav": request.data
    }

    def generate(response):
        for result in response:
            yield json.dumps(result)

    try:
        worker = create_frontend_worker(os.environ['MASTER_ADDR'])
        response = worker.recognize_batch(data, request.headers)
        worker.close()

        return Response(stream_with_context(generate(response)))
    except MissingHeaderError:
        return jsonify({"status": "error", "message": "Missing header Content-Type"}), 400
    except NoWorkerAvailableError:
        return jsonify({"status": "error", "message": "No worker available"}), 503
    finally:
        worker.close() 
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 ""
    )

    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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
Source File: taxiipoll.py    From minemeld-core with Apache License 2.0 6 votes vote down vote up
def taxii_poll_service():
    taxiict = request.headers['X-TAXII-Content-Type']
    if taxiict == 'urn:taxii.mitre.org:message:xml:1.1':
        tm = libtaxii.messages_11.get_message_from_xml(request.data)
        if tm.message_type != libtaxii.constants.MSG_POLL_REQUEST:
            return 'Invalid message', 400

        cname = tm.collection_name
        excbegtime = tm.exclusive_begin_timestamp_label
        incendtime = tm.inclusive_end_timestamp_label

        if not current_user.check_feed(cname):
            return 'Unauthorized', 401

        return data_feed_11(tm.message_id, cname, excbegtime, incendtime)

    elif taxiict == 'urn:taxii.mitre.org:message:xml:1.0':
        # old TAXII 1.0 not supported yet
        return 'Invalid message', 400

    else:
        return 'Invalid message', 400 
Example #15
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 #16
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 
Example #17
Source File: zmirror.py    From zmirror with MIT License 6 votes vote down vote up
def zmirror_enter(input_path='/'):
    """入口函数的壳, 只是包了一层异常处理, 实际是 main_function() """
    try:
        resp = main_function(input_path=input_path)

        # 加入额外的响应头
        for name, value in parse.extra_resp_headers.items():
            resp.headers.set(name, value)

        # 加入额外的cookies
        for name, cookie_string in parse.extra_cookies.items():
            resp.headers.add("Set-Cookie", cookie_string)

    except:  # coverage: exclude
        return generate_error_page(is_traceback=True)
    else:
        return resp


# noinspection PyUnusedLocal 
Example #18
Source File: views_default_to_current_conversation.py    From python-slackclient with MIT License 6 votes vote down vote up
def slack_app():
    if not signature_verifier.is_valid_request(request.get_data(), request.headers):
        return make_response("invalid request", 403)

    if "command" in request.form \
        and request.form["command"] == "/view":
        trigger_id = request.form["trigger_id"]
        return open_modal(trigger_id)

    elif "payload" in request.form:
        payload = json.loads(request.form["payload"])
        if payload["type"] == "view_submission" \
            and payload["view"]["callback_id"] == "modal-id":
            submitted_data = payload["view"]["state"]["values"]
            print(submitted_data)  # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}}
            return make_response("", 200)
        if payload["type"] == "shortcut" \
            and payload["callback_id"] == "view-test":
            return open_modal(payload["trigger_id"])

    return make_response("", 404) 
Example #19
Source File: zmirror.py    From zmirror with MIT License 6 votes vote down vote up
def request_remote_site():
    """
    请求远程服务器(high-level), 并在返回404/500时进行 domain_guess 尝试
    """

    # 请求被镜像的网站
    # 注意: 在zmirror内部不会处理重定向, 重定向响应会原样返回给浏览器
    parse.remote_response = send_request(
        parse.remote_url,
        method=request.method,
        headers=parse.client_header,
        data=parse.request_data_encoded,
    )

    if parse.remote_response.url != parse.remote_url:
        warnprint("requests's remote url", parse.remote_response.url,
                  'does no equals our rewrited url', parse.remote_url)

    if 400 <= parse.remote_response.status_code <= 599:
        # 猜测url所对应的正确域名
        dbgprint("Domain guessing for", request.url)
        result = guess_correct_domain()
        if result is not None:
            parse.remote_response = result 
Example #20
Source File: views.py    From oadoi with MIT License 6 votes vote down vote up
def after_request_stuff(resp):

    #support CORS
    resp.headers['Access-Control-Allow-Origin'] = "*"
    resp.headers['Access-Control-Allow-Methods'] = "POST, GET, OPTIONS, PUT, DELETE, PATCH"
    resp.headers['Access-Control-Allow-Headers'] = "origin, content-type, accept, x-requested-with"

    # remove session
    db.session.remove()

    # without this jason's heroku local buffers forever
    sys.stdout.flush()

    # log request for analytics
    log_request(resp)

    return resp 
Example #21
Source File: decorators.py    From papers with MIT License 6 votes vote down vote up
def login_required(f):
    '''
    This decorator checks the header to ensure a valid token is set
    '''
    @wraps(f)
    def func(*args, **kwargs):
        try:
            if 'authorization' not in request.headers:
                abort(404, message="You need to be logged in to access this resource")
            token = request.headers.get('authorization')
            payload = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])
            user_id = payload['id']
            g.user = User.find(user_id)
            if g.user is None:
               abort(404, message="The user id is invalid")
            return f(*args, **kwargs)
        except JWTError as e:
            abort(400, message="There was a problem while trying to parse your token -> {}".format(e.message))
    return func 
Example #22
Source File: auth.py    From SempoBlockchain with GNU General Public License v3.0 6 votes vote down vote up
def verify_slack_requests(f=None):
    """
    Verify the request signature of the request sent from Slack
    Generate a new hash using the app's signing secret and request data
    """
    @wraps(f)
    def wrapper(*args, **kwargs):
        signature = request.headers['X-Slack-Signature']
        timestamp = request.headers['X-Slack-Request-Timestamp']
        data = request.data.decode('utf-8')
        # data = urllib.parse.urlencode(urllib.parse.unquote(raw_string))

        format_req = str.encode(f"v0:{timestamp}:{data}")
        encoded_secret = str.encode(config.SLACK_SECRET)
        request_hash = hmac.new(encoded_secret, format_req, hashlib.sha256).hexdigest()
        calculated_signature = f"v0={request_hash}"
        if hmac.compare_digest(calculated_signature, signature):
            return f(*args, **kwargs)

        return make_response(jsonify({'message': 'Invalid auth'})), 401
    return wrapper 
Example #23
Source File: views.py    From oadoi with MIT License 5 votes vote down vote up
def sources_endpoint_csv():
    objs = repository.get_sources_data()
    data_string = u'\n'.join([obj.to_csv_row() for obj in objs])
    data_string = data_string.encode("utf-8")
    output = make_response(data_string)
    output.headers["Content-Disposition"] = "attachment; filename=unpaywall_sources.csv"
    output.headers["Content-type"] = "text/csv; charset=UTF-8"
    return output 
Example #24
Source File: info.py    From appr with Apache License 2.0 5 votes vote down vote up
def pre_request_logging():
    jsonbody = request.get_json(force=True, silent=True)
    values = request.values.to_dict()
    if jsonbody:
        values.update(jsonbody)

    current_app.logger.info("request", extra={
        "remote_addr": request.remote_addr,
        "http_method": request.method,
        "original_url": request.url,
        "path": request.path,
        "data": values,
        "headers": dict(request.headers.to_list())}) 
Example #25
Source File: views.py    From oadoi with MIT License 5 votes vote down vote up
def get_ip():
    # from http://stackoverflow.com/a/12771438/596939
    if request.headers.getlist("X-Forwarded-For"):
       ip = request.headers.getlist("X-Forwarded-For")[0]
    else:
       ip = request.remote_addr
    return ip 
Example #26
Source File: webhook.py    From RastreioBot with GNU General Public License v3.0 5 votes vote down vote up
def secbox():
    jsonData = request.get_json()
    if webhook_key not in str(request.headers['X-Verification-Key']):
        return "Error"
    if jsonData['event_type'] == 'new_subscription':
        if not select_user('picpayid', jsonData['event']['subscriber']['username']):
            adduser('', jsonData['event']['subscriber']['username'].lower())
    return "Hello" 
Example #27
Source File: test_fixtures.py    From pytest-flask with MIT License 5 votes vote down vote up
def test_request_ctx_is_kept_around(self, client):
        client.get(url_for('index'), headers=[('X-Something', '42')])
        assert request.headers['X-Something'] == '42' 
Example #28
Source File: views.py    From oadoi with MIT License 5 votes vote down vote up
def print_ip():
    user_agent = request.headers.get('User-Agent')
    logger.info(u"calling from IP {ip}. User-Agent is '{user_agent}'.".format(
        ip=get_ip(),
        user_agent=user_agent
    ))


# this is the old way of expressing this endpoint.
# the new way is POST api.oadoi.org/
# you can give it an object that lists DOIs
# you can also give it an object that lists biblios.
# this is undocumented and is just for impactstory use now. 
Example #29
Source File: info.py    From appr with Apache License 2.0 5 votes vote down vote up
def index_discovery():
    host = request.url_root
    domain = request.headers['Host']
    return """<html lang="en">
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="appr-package" content="{domain}/{{name}} {host}/appr/api/v1/packages/{{name}}/pull">
    </head>
    <body>
    </body>
    </html>""".format(domain=domain, host=host) 
Example #30
Source File: __init__.py    From flask-oidc with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _get_token_info(self, token):
        # We hardcode to use client_secret_post, because that's what the Google
        # oauth2client library defaults to
        request = {'token': token}
        headers = {'Content-type': 'application/x-www-form-urlencoded'}

        hint = current_app.config['OIDC_TOKEN_TYPE_HINT']
        if hint != 'none':
            request['token_type_hint'] = hint

        auth_method = current_app.config['OIDC_INTROSPECTION_AUTH_METHOD'] 
        if (auth_method == 'client_secret_basic'):
            basic_auth_string = '%s:%s' % (self.client_secrets['client_id'], self.client_secrets['client_secret'])
            basic_auth_bytes = bytearray(basic_auth_string, 'utf-8')
            headers['Authorization'] = 'Basic %s' % b64encode(basic_auth_bytes).decode('utf-8')
        elif (auth_method == 'bearer'):
            headers['Authorization'] = 'Bearer %s' % token
        elif (auth_method == 'client_secret_post'):
            request['client_id'] = self.client_secrets['client_id']
            if self.client_secrets['client_secret'] is not None:
                request['client_secret'] = self.client_secrets['client_secret']

        resp, content = httplib2.Http().request(
            self.client_secrets['token_introspection_uri'], 'POST',
            urlencode(request), headers=headers)
        # TODO: Cache this reply
        return _json_loads(content)