Python flask.request() Examples

The following are 30 code examples of flask.request(). 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 , or try the search function .
Example #1
Source File: AC_PKCE_auth_server.py    From auth-server-sample with Apache License 2.0 6 votes vote down vote up
def auth():
  # Describe the access request of the client and ask user for approval
  client_id = request.args.get('client_id')
  redirect_url = request.args.get('redirect_url')
  code_challenge = request.args.get('code_challenge')

  if None in [ client_id, redirect_url, code_challenge ]:
    return json.dumps({
      "error": "invalid_request"
    }), 400

  if not verify_client_info(client_id, redirect_url):
    return json.dumps({
      "error": "invalid_client"
    })

  return render_template('AC_PKCE_grant_access.html',
                         client_id = client_id,
                         redirect_url = redirect_url,
                         code_challenge = code_challenge) 
Example #2
Source File: webserver_sub.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def drip():
    """Drip data over a duration."""
    duration = float(flask.request.args.get('duration'))
    numbytes = int(flask.request.args.get('numbytes'))
    pause = duration / numbytes

    def generate_bytes():
        for _ in range(numbytes):
            yield "*".encode('utf-8')
            time.sleep(pause)

    response = flask.Response(generate_bytes(), headers={
        "Content-Type": "application/octet-stream",
        "Content-Length": str(numbytes),
    })
    response.status_code = HTTPStatus.OK
    return response 
Example #3
Source File: banned.py    From dino with Apache License 2.0 6 votes vote down vote up
def do_get(self):
        is_valid, msg, json = self.validate_json(self.request, silent=True)
        if not is_valid:
            logger.error('invalid json: %s' % msg)
            return dict()

        if json is None:
            return environ.env.db.get_banned_users()

        if 'users' not in json:
            return dict()
        logger.debug('GET request: %s' % str(json))

        output = dict()
        for user_id in json['users']:
            output[user_id] = self.do_get_with_params(user_id)
        return output 
Example #4
Source File: roles.py    From dino with Apache License 2.0 6 votes vote down vote up
def do_get(self):
        is_valid, msg, json = self.validate_json()
        if not is_valid:
            logger.error('invalid json: %s' % msg)
            return dict()

        if json is None:
            return environ.env.db.get_banned_users()

        if 'users' not in json:
            return dict()
        logger.debug('GET request: %s' % str(json))

        output = dict()
        for user_id in json['users']:
            output[user_id] = self.do_get_with_params(user_id)
        return output 
Example #5
Source File: webserver_sub.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def redirect_later():
    """302 redirect to / after the given delay.

    If delay is -1, wait until a request on redirect-later-continue is done.
    """
    global _redirect_later_event
    delay = float(flask.request.args.get('delay', '1'))
    if delay == -1:
        _redirect_later_event = threading.Event()
        ok = _redirect_later_event.wait(timeout=30 * 1000)
        assert ok
        _redirect_later_event = None
    else:
        time.sleep(delay)
    x = flask.redirect('/')
    return x 
Example #6
Source File: full_history.py    From dino with Apache License 2.0 6 votes vote down vote up
def do_post(self):
        the_json = self.validate_json()
        logger.debug('POST request: %s' % str(the_json))

        user_id = the_json.get('user_id')
        from_time = the_json.get('from_time', None)
        to_time = the_json.get('to_time', None)

        try:
            messages = self.do_post_with_params(user_id, from_time, to_time)
            for message in messages:
                message['from_user_name'] = b64e(message['from_user_name'])
                message['body'] = b64e(message['body'])
                message['target_name'] = b64e(message['target_name'])
                message['channel_name'] = b64e(message['channel_name'])
            return messages
        except Exception as e:
            logger.error('could not get messages: %s' % str(e))
            raise e 
Example #7
Source File: acl.py    From dino with Apache License 2.0 6 votes vote down vote up
def _do_post(self, json_data: dict):
        logger.debug('POST request: %s' % str(json_data))

        room_id = json_data.get('room_id')
        action = json_data.get('action')
        acl_type = json_data.get('acl_type')
        acl_value = json_data.get('acl_value')

        try:
            channel_id = self.env.db.channel_for_room(room_id)
            self.acl_manager.update_room_acl(channel_id, room_id, action, acl_type, acl_value)
        except Exception as e:
            logger.error('could update acls in room {} with action={}, type={}, value="{}": {}'.format(
                room_id, action, acl_type, acl_value, str(e))
            )
            logger.exception(traceback.format_exc())
            self.env.capture_exception(sys.exc_info()) 
Example #8
Source File: test_oauth_models.py    From app with MIT License 6 votes vote down vote up
def test_get_response_types(flask_app):
    with flask_app.test_request_context("/"):
        response_types = get_response_types(flask.request)
        assert response_types == set()

    with flask_app.test_request_context("/?response_type=token&response_type=id_token"):
        response_types = get_response_types(flask.request)
        assert response_types == {ResponseType.TOKEN, ResponseType.ID_TOKEN}

    # a space as separator
    with flask_app.test_request_context("/?response_type=token%20id_token"):
        response_types = get_response_types(flask.request)
        assert response_types == {ResponseType.TOKEN, ResponseType.ID_TOKEN}

    # a comma as separator
    with flask_app.test_request_context("/?response_type=id_token,token"):
        response_types = get_response_types(flask.request)
        assert response_types == {ResponseType.TOKEN, ResponseType.ID_TOKEN}

    # non-existent response_type: raise ValueError
    with flask_app.test_request_context("/?response_type=abcd"):
        with pytest.raises(ValueError):
            get_response_types(flask.request) 
Example #9
Source File: AC_PKCE_auth_server.py    From auth-server-sample with Apache License 2.0 6 votes vote down vote up
def exchange_for_token():
  # Issues access token
  authorization_code = request.form.get('authorization_code')
  client_id = request.form.get('client_id')
  code_verifier = request.form.get('code_verifier')
  redirect_url = request.form.get('redirect_url')

  if None in [ authorization_code, client_id, code_verifier, redirect_url ]:
    return json.dumps({
      "error": "invalid_request"
    }), 400

  if not verify_authorization_code(authorization_code, client_id, redirect_url,
                                   code_verifier):
    return json.dumps({
      "error": "access_denied"
    }), 400

  access_token = generate_access_token()
  return json.dumps({ 
    "access_token": access_token,
    "token_type": "JWT",
    "expires_in": JWT_LIFE_SPAN
  }) 
Example #10
Source File: latest_history.py    From dino with Apache License 2.0 6 votes vote down vote up
def do_get(self):
        the_json = self.validate_json()
        logger.debug('GET request: %s' % str(the_json))

        room_id = the_json.get('room_id', '')
        limit = the_json.get('limit', 100)

        try:
            messages = self.do_get_with_params(room_id, limit)
            for message in messages:
                message['from_user_name'] = b64e(message['from_user_name'])
                message['body'] = b64e(message['body'])
                message['target_name'] = b64e(message['target_name'])
                message['channel_name'] = b64e(message['channel_name'])
            return messages
        except Exception as e:
            logger.error('could not get messages: %s' % str(e))
            raise e 
Example #11
Source File: history.py    From dino with Apache License 2.0 6 votes vote down vote up
def do_get(self):
        the_json = self.validate_json()
        logger.debug('GET request: %s' % str(the_json))

        room_id = the_json.get('room_id', '')
        user_id = the_json.get('user_id')
        from_time = the_json.get('from_time')
        to_time = the_json.get('to_time')

        try:
            messages = self.do_get_with_params(room_id, user_id, from_time, to_time)
            for message in messages:
                message['from_user_name'] = b64e(message['from_user_name'])
                message['body'] = b64e(message['body'])
                message['target_name'] = b64e(message['target_name'])
                message['channel_name'] = b64e(message['channel_name'])
            return messages
        except Exception as e:
            logger.error('could not get messages: %s' % str(e))
            raise e 
Example #12
Source File: Implicit_auth_server.py    From auth-server-sample with Apache License 2.0 6 votes vote down vote up
def auth():
  # Describe the access request of the client and ask user for approval
  client_id = request.args.get('client_id')
  redirect_url = request.args.get('redirect_url')

  if None in [ client_id, redirect_url ]:
    return json.dumps({
      "error": "invalid_request"
    }), 400

  if not verify_client_info(client_id, redirect_url):
    return json.dumps({
      "error": "invalid_client"
    })

  return render_template('Implicit_grant_access.html',
                         client_id = client_id,
                         redirect_url = redirect_url) 
Example #13
Source File: api_helpers.py    From everyclass-server with Mozilla Public License 2.0 6 votes vote down vote up
def token_required(func):
    """
    检查是否携带token,如果token未携带或无效将直接返回错误,否则将username保存到g.username中
    """
    from everyclass.server.user import service as user_service

    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        token = request.headers.get("X-API-Token")
        if not token:
            return generate_error_response(None, STATUS_CODE_TOKEN_MISSING)

        username = user_service.get_username_from_jwt(token)
        if not username:
            return generate_error_response(None, STATUS_CODE_INVALID_TOKEN)

        g.username = username
        return func(*args, **kwargs)

    return wrapped 
Example #14
Source File: test_oauth_models.py    From app with MIT License 6 votes vote down vote up
def test_get_scopes(flask_app):
    with flask_app.test_request_context("/"):
        scopes = get_scopes(flask.request)
        assert scopes == set()

    with flask_app.test_request_context("/?scope=email&scope=name"):
        scopes = get_scopes(flask.request)
        assert scopes == {Scope.NAME, Scope.EMAIL}

    # a space between email and name
    with flask_app.test_request_context("/?scope=email%20name"):
        scopes = get_scopes(flask.request)
        assert scopes == {Scope.NAME, Scope.EMAIL}

    # a comma between email and name
    with flask_app.test_request_context("/?scope=email,name"):
        scopes = get_scopes(flask.request)
        assert scopes == {Scope.NAME, Scope.EMAIL}

    # non-existent scope: raise ValueError
    with flask_app.test_request_context("/?scope=abcd"):
        with pytest.raises(ValueError):
            get_scopes(flask.request) 
Example #15
Source File: serve.py    From sagemaker-xgboost-container with Apache License 2.0 6 votes vote down vote up
def _parse_accept(request):
    """Get the accept type for a given request.

    Valid accept types are "application/json", "application/jsonlines", "application/x-recordio-protobuf",
    and "text/csv". If no accept type is set, use the value in SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT.

    :param request: flask request
    :return: parsed accept type
    """
    accept, _ = cgi.parse_header(request.headers.get("accept", ""))
    if not accept or accept == "*/*":
        return os.getenv(sm_env_constants.SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT, "text/csv")
    if accept.lower() not in SUPPORTED_ACCEPTS:
        raise ValueError("Accept type {} is not supported. Please use supported accept types: {}."
                         .format(accept, SUPPORTED_ACCEPTS))
    return accept.lower() 
Example #16
Source File: acl.py    From dino with Apache License 2.0 6 votes vote down vote up
def _validate_params(self):
        is_valid, msg, json_data = self.validate_json(self.request, silent=False)
        if not is_valid:
            raise RuntimeError('invalid json: %s' % msg)

        if json_data is None:
            raise RuntimeError('no json in request')
        if not isinstance(json_data, dict):
            raise RuntimeError('need a dict')

        if 'room_id' not in json_data:
            raise KeyError('missing parameter room_id for in request')
        if 'action' not in json_data:
            raise KeyError('missing parameter action for in request')
        if 'acl_type' not in json_data:
            raise KeyError('missing parameter acl_type for in request')
        if 'acl_value' not in json_data:
            raise KeyError('missing parameter acl_value for in request')

        return json_data 
Example #17
Source File: serve.py    From sagemaker-xgboost-container with Apache License 2.0 5 votes vote down vote up
def invocations():
    payload = flask.request.data
    if len(payload) == 0:
        return flask.Response(response="", status=http.client.NO_CONTENT)

    try:
        dtest, content_type = serve_utils.parse_content_data(payload, flask.request.content_type)
    except Exception as e:
        logging.exception(e)
        return flask.Response(response=str(e), status=http.client.UNSUPPORTED_MEDIA_TYPE)

    try:
        format = ScoringService.load_model()
    except Exception as e:
        logging.exception(e)
        return flask.Response(response="Unable to load model: %s" % e, status=http.client.INTERNAL_SERVER_ERROR)

    try:
        preds = ScoringService.predict(data=dtest, content_type=content_type, model_format=format)
    except Exception as e:
        logging.exception(e)
        return flask.Response(response="Unable to evaluate payload provided: %s" % e, status=http.client.BAD_REQUEST)

    if serve_utils.is_selectable_inference_output():
        try:
            accept = _parse_accept(flask.request)
        except Exception as e:
            logging.exception(e)
            return flask.Response(response=str(e), status=http.client.NOT_ACCEPTABLE)

        return _handle_selectable_inference_response(preds, accept)

    if SAGEMAKER_BATCH:
        return_data = "\n".join(map(str, preds.tolist())) + '\n'
    else:
        return_data = ",".join(map(str, preds.tolist()))

    return flask.Response(response=return_data, status=http.client.OK, mimetype="text/csv") 
Example #18
Source File: history.py    From dino with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        super(HistoryResource, self).__init__()
        self.last_cleared = datetime.utcnow()
        self.request = request 
Example #19
Source File: history.py    From dino with Apache License 2.0 5 votes vote down vote up
def validate_json(self):
        try:
            the_json = self.request.get_json(silent=True)
        except Exception as e:
            logger.error('error: %s' % str(e))
            logger.exception(traceback.format_exc())
            raise ValueError('invalid json')

        if the_json is None:
            logger.error('empty request body')
            raise ValueError('empty request body')

        return the_json 
Example #20
Source File: remove_admin.py    From dino with Apache License 2.0 5 votes vote down vote up
def do_post(self):
        is_valid, msg, json = self.validate_json()
        if not is_valid:
            logger.error('invalid json: %s' % msg)
            raise RuntimeError('invalid json')

        if json is None:
            raise RuntimeError('no json in request')
        if not isinstance(json, dict):
            raise RuntimeError('need a dict')
        logger.debug('POST request: %s' % str(json))

        if 'id' not in json:
            raise RuntimeError('no id parameter in request')

        user_id = json.get('id')
        try:
            environ.env.db.remove_global_moderator(user_id)
        except Exception as e:
            logger.error('could not remove global moderator with id "%s": %s' % (str(user_id), str(e)))
            logger.exception(traceback.format_exc())
            raise RuntimeError('could not remove global moderator with id "%s": %s' % (str(user_id), str(e))) 
Example #21
Source File: acl.py    From dino with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        super(AclResource, self).__init__()
        self.acl_manager = AclManager(environ.env)
        self.last_cleared = datetime.utcnow()
        self.executor = GreenPool()
        self.request = request
        self.env = environ.env 
Example #22
Source File: status.py    From dino with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        super(SetStatusResource, self).__init__()
        self.request = request 
Example #23
Source File: set_admin.py    From dino with Apache License 2.0 5 votes vote down vote up
def validate_json(self):
        try:
            return True, None, self.request.get_json(silent=False)
        except Exception as e:
            logger.error('error: %s' % str(e))
            logger.exception(traceback.format_exc())
            return False, 'invalid json in request', None 
Example #24
Source File: set_admin.py    From dino with Apache License 2.0 5 votes vote down vote up
def do_post(self):
        is_valid, msg, json = self.validate_json()
        if not is_valid:
            logger.error('invalid json: %s' % msg)
            raise RuntimeError('invalid json')

        if json is None:
            raise RuntimeError('no json in request')
        if not isinstance(json, dict):
            raise RuntimeError('need a dict')
        logger.debug('POST request: %s' % str(json))

        if 'id' not in json:
            raise RuntimeError('no id parameter in request')
        if 'name' not in json:
            raise RuntimeError('no name parameter in request')

        user_id = json.get('id')
        user_name = json.get('name')

        try:
            environ.env.db.create_user(user_id, user_name)
        except UserExistsException:
            pass

        try:
            environ.env.db.set_global_moderator(user_id)
        except Exception as e:
            logger.error('could not set user with id "%s" as global moderator: %s' % (str(user_id), str(e)))
            logger.exception(traceback.format_exc())
            raise RuntimeError('could not set user with id "%s" as global moderator: %s' % (str(user_id), str(e))) 
Example #25
Source File: set_admin.py    From dino with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        super(SetAdminResource, self).__init__()
        self.request = request 
Example #26
Source File: latest_history.py    From dino with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        super().__init__(cache_clear_interval=30)
        self.last_cleared = datetime.utcnow()
        self.request = request 
Example #27
Source File: heartbeat.py    From dino with Apache License 2.0 5 votes vote down vote up
def _do_post(self, json: dict):
        logger.debug('POST request: %s' % str(json))
        for user_id in json:
            try:
                self.heartbeat_user(user_id)
            except Exception as e:
                self.env.capture_exception(sys.exc_info())
                logger.error('could not auth user %s: %s' % (user_id, str(e))) 
Example #28
Source File: heartbeat.py    From dino with Apache License 2.0 5 votes vote down vote up
def _validate_params(self):
        is_valid, msg, json = self.validate_json(self.request, silent=False)
        if not is_valid:
            raise RuntimeError('invalid json: %s' % msg)

        if json is None:
            raise RuntimeError('no json in request')
        if not isinstance(json, list):
            raise RuntimeError('need a dict of user-room keys')

        return json 
Example #29
Source File: heartbeat.py    From dino with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        super(HeartbeatResource, self).__init__()
        self.user_manager = UserManager(environ.env)
        self.executor = GreenPool()
        self.request = request
        self.env = environ.env 
Example #30
Source File: web.py    From svviz with MIT License 5 votes vote down vote up
def display():
    req = request.args.get('req', 0)

    if req == "progress":
        return jsonify(result="done")

    if req in ["alt", "ref", "amb"]:
        allele = req
        results = []
        for name, sample in dataHub.samples.items():
            # svg = open("{}.{}.svg".format(req, name)).read()
            track = sample.tracks[allele]
            track.render()
            svg = track.svg.asString("web")
            results.append({"name":name, "svg":svg})

        for annotation in dataHub.alleleTracks[allele]:
            track = dataHub.alleleTracks[allele][annotation]
            track.render(spacing=5)
            annoSVG = track.svg.asString("web")
            results.append({"name":annotation, "svg":annoSVG})

        return jsonify(results=results)


    if req == "counts":
        return jsonify(result=dataHub.getCounts())

    return jsonify(result="unknown request: {}".format(req))