Python webapp2.Request() Examples

The following are 30 code examples of webapp2.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 webapp2 , or try the search function .
Example #1
Source File: handler.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def parse_body(self):
    """Parses JSON body and verifies it's a dict.

    webob.Request doesn't cache the decoded json body, this function does.
    """
    if self._json_body is None:
      if (self.CONTENT_TYPE_BASE and
          self.request.content_type != self.CONTENT_TYPE_BASE):
        msg = (
            'Expecting JSON body with content type \'%s\'' %
            self.CONTENT_TYPE_BASE)
        self.abort_with_error(400, text=msg)
      try:
        self._json_body = self.request.json
        if not isinstance(self._json_body, dict):
          raise ValueError()
      except (LookupError, ValueError):
        self.abort_with_error(400, text='Not a valid json dict body')
    return self._json_body.copy() 
Example #2
Source File: auth.py    From googleapps-message-recall with Apache License 2.0 6 votes vote down vote up
def get_auth(factory=Auth, key=_auth_registry_key, request=None):
    """Returns an instance of :class:`Auth` from the request registry.

    It'll try to get it from the current request registry, and if it is not
    registered it'll be instantiated and registered. A second call to this
    function will return the same instance.

    :param factory:
        The callable used to build and register the instance if it is not yet
        registered. The default is the class :class:`Auth` itself.
    :param key:
        The key used to store the instance in the registry. A default is used
        if it is not set.
    :param request:
        A :class:`webapp2.Request` instance used to store the instance. The
        active request is used if it is not set.
    """
    request = request or webapp2.get_request()
    auth = request.registry.get(key)
    if not auth:
        auth = request.registry[key] = factory(request)

    return auth 
Example #3
Source File: handler.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def parse_body(self):
    """Parses JSON body and verifies it's a dict.

    webob.Request doesn't cache the decoded json body, this function does.
    """
    if self._json_body is None:
      if (self.CONTENT_TYPE_BASE and
          self.request.content_type != self.CONTENT_TYPE_BASE):
        msg = (
            'Expecting JSON body with content type \'%s\'' %
            self.CONTENT_TYPE_BASE)
        self.abort_with_error(400, text=msg)
      try:
        self._json_body = self.request.json
        if not isinstance(self._json_body, dict):
          raise ValueError()
      except (LookupError, ValueError):
        self.abort_with_error(400, text='Not a valid json dict body')
    return self._json_body.copy() 
Example #4
Source File: sessions.py    From googleapps-message-recall with Apache License 2.0 6 votes vote down vote up
def __init__(self, request, config=None):
        """Initializes the session store.

        :param request:
            A :class:`webapp2.Request` instance.
        :param config:
            A dictionary of configuration values to be overridden. See
            the available keys in :data:`default_config`.
        """
        self.request = request
        # Base configuration.
        self.config = request.app.config.load_config(self.config_key,
            default_values=default_config, user_values=config,
            required_keys=('secret_key',))
        # Tracked sessions.
        self.sessions = {} 
Example #5
Source File: sessions.py    From googleapps-message-recall with Apache License 2.0 6 votes vote down vote up
def get_store(factory=SessionStore, key=_registry_key, request=None):
    """Returns an instance of :class:`SessionStore` from the request registry.

    It'll try to get it from the current request registry, and if it is not
    registered it'll be instantiated and registered. A second call to this
    function will return the same instance.

    :param factory:
        The callable used to build and register the instance if it is not yet
        registered. The default is the class :class:`SessionStore` itself.
    :param key:
        The key used to store the instance in the registry. A default is used
        if it is not set.
    :param request:
        A :class:`webapp2.Request` instance used to store the instance. The
        active request is used if it is not set.
    """
    request = request or webapp2.get_request()
    store = request.registry.get(key)
    if not store:
        store = request.registry[key] = factory(request)

    return store 
Example #6
Source File: sessions.py    From googleapps-message-recall with Apache License 2.0 6 votes vote down vote up
def set_store(store, key=_registry_key, request=None):
    """Sets an instance of :class:`SessionStore` in the request registry.

    :param store:
        An instance of :class:`SessionStore`.
    :param key:
        The key used to retrieve the instance from the registry. A default
        is used if it is not set.
    :param request:
        A :class:`webapp2.Request` instance used to retrieve the instance. The
        active request is used if it is not set.
    """
    request = request or webapp2.get_request()
    request.registry[key] = store


# Don't need to import it. :) 
Example #7
Source File: handler.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def parse_body(self):
    """Parses JSON body and verifies it's a dict.

    webob.Request doesn't cache the decoded json body, this function does.
    """
    if self._json_body is None:
      if (self.CONTENT_TYPE_BASE and
          self.request.content_type != self.CONTENT_TYPE_BASE):
        msg = (
            'Expecting JSON body with content type \'%s\'' %
            self.CONTENT_TYPE_BASE)
        self.abort_with_error(400, text=msg)
      try:
        self._json_body = self.request.json
        if not isinstance(self._json_body, dict):
          raise ValueError()
      except (LookupError, ValueError):
        self.abort_with_error(400, text='Not a valid json dict body')
    return self._json_body.copy() 
Example #8
Source File: handler.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def parse_body(self):
    """Parses JSON body and verifies it's a dict.

    webob.Request doesn't cache the decoded json body, this function does.
    """
    if self._json_body is None:
      if (self.CONTENT_TYPE_BASE and
          self.request.content_type != self.CONTENT_TYPE_BASE):
        msg = (
            'Expecting JSON body with content type \'%s\'' %
            self.CONTENT_TYPE_BASE)
        self.abort_with_error(400, text=msg)
      try:
        self._json_body = self.request.json
        if not isinstance(self._json_body, dict):
          raise ValueError()
      except (LookupError, ValueError):
        self.abort_with_error(400, text='Not a valid json dict body')
    return self._json_body.copy() 
Example #9
Source File: adapter_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def test_proxy_routing(self):
    app = webapp2.WSGIApplication(
        [adapter.explorer_proxy_route('/api')], debug=True)
    request = webapp2.Request.blank('/api/static/proxy.html')
    request.method = 'GET'
    response = request.get_response(app).body
    self.assertIn('/api', response) 
Example #10
Source File: adapter_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def test_decode_message_get(self):
    request = webapp2.Request(
        {
          'QUERY_STRING': 's=a',
        },
        method='GET',
        route_kwargs={'s2': 'b'},
    )
    msg = adapter.decode_message(EndpointsService.get.remote, request)
    self.assertEqual(msg.s, 'a')
    self.assertEqual(msg.s2, 'b') 
Example #11
Source File: adapter_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def test_redirect_routing(self):
    app = webapp2.WSGIApplication(
        [adapter.explorer_redirect_route('/api')], debug=True)
    request = webapp2.Request.blank('/api/explorer')
    request.method = 'GET'
    response = request.get_response(app)
    self.assertEqual(response.status, '302 Moved Temporarily') 
Example #12
Source File: machine_auth_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def call(self, body=None, raw_token=None):
    if body:
      env = machine_token_pb2.MachineTokenEnvelope()
      env.token_body = body.SerializeToString()
      env.key_id = 'signing_key'
      env.rsa_sha256 = 'signature'
      raw_token = base64.b64encode(env.SerializeToString())
    req = webapp2.Request({})
    if raw_token:
      req.headers['X-Luci-Machine-Token'] = raw_token
    return machine_auth.machine_authentication(req) 
Example #13
Source File: handler.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def require_xsrf_token_request(f):
  """Use for handshaking APIs."""
  @functools.wraps(f)
  def hook(self, *args, **kwargs):
    if not self.request.headers.get('X-XSRF-Token-Request'):
      raise api.AuthorizationError('Missing required XSRF request header')
    return f(self, *args, **kwargs)
  return hook 
Example #14
Source File: adapter_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def test_proxy_routing(self):
    app = webapp2.WSGIApplication(
        [adapter.explorer_proxy_route('/api')], debug=True)
    request = webapp2.Request.blank('/api/static/proxy.html')
    request.method = 'GET'
    response = request.get_response(app).body
    self.assertIn('/api', response) 
Example #15
Source File: machine_auth_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def call(self, body=None, raw_token=None):
    if body:
      env = machine_token_pb2.MachineTokenEnvelope()
      env.token_body = body.SerializeToString()
      env.key_id = 'signing_key'
      env.rsa_sha256 = 'signature'
      raw_token = base64.b64encode(env.SerializeToString())
    req = webapp2.Request({})
    if raw_token:
      req.headers['X-Luci-Machine-Token'] = raw_token
    return machine_auth.machine_authentication(req) 
Example #16
Source File: adapter_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def test_redirect_routing(self):
    app = webapp2.WSGIApplication(
        [adapter.explorer_redirect_route('/api')], debug=True)
    request = webapp2.Request.blank('/api/explorer')
    request.method = 'GET'
    response = request.get_response(app)
    self.assertEqual(response.status, '302 Moved Temporarily') 
Example #17
Source File: handler.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def get_auth_methods(cls, conf):  # pylint: disable=unused-argument
    """Returns an enumerable of functions to use to authenticate request.

    The handler will try to apply auth methods sequentially one by one by until
    it finds one that works.

    Each auth method is a function that accepts webapp2.Request and can finish
    with 3 outcomes:

    * Return (None, ...): authentication method is not applicable to that
      request and next method should be tried (for example cookie-based
      authentication is not applicable when there's no cookies).

    * Returns (Identity, AuthDetails). It means the authentication method
      is applicable and the caller is authenticated as 'Identity'. All
      additional information extracted from the credentials (like if the caller
      is a GAE-level admin) is returned through AuthDetails tuple. It can be
      None if there are no extra information.

    * Raises AuthenticationError: authentication method is applicable, but
      request contains bad credentials or invalid token, etc. For example,
      OAuth2 token is given, but it is revoked.

    A chosen auth method function will be stored in request's auth_method field.

    Args:
      conf: components.auth GAE config, see config.py.
    """
    return (
        oauth_authentication,
        gae_cookie_authentication,
        service_to_service_authentication) 
Example #18
Source File: adapter_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def test_directory_routing(self):
    app = webapp2.WSGIApplication(
        [adapter.directory_service_route([EndpointsService], '/api')],
        debug=True)
    request = webapp2.Request.blank('/api/discovery/v1/apis')
    request.method = 'GET'
    response = json.loads(request.get_response(app).body)
    self.assertEqual(len(response.get('items', [])), 1)
    self.assertEqual(response['items'][0]['id'], 'Service:v1') 
Example #19
Source File: adapter_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def test_directory_routing(self):
    app = webapp2.WSGIApplication(
        [adapter.directory_service_route([EndpointsService], '/api')],
        debug=True)
    request = webapp2.Request.blank('/api/discovery/v1/apis')
    request.method = 'GET'
    response = json.loads(request.get_response(app).body)
    self.assertEqual(len(response.get('items', [])), 1)
    self.assertEqual(response['items'][0]['id'], 'Service:v1') 
Example #20
Source File: adapter_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def test_handle_403(self):
    app = webapp2.WSGIApplication(
        adapter.api_routes([EndpointsService], '/_ah/api'), debug=True)
    request = webapp2.Request.blank('/_ah/api/Service/v1/post_403')
    request.method = 'POST'
    response = request.get_response(app)
    self.assertEqual(response.status_int, 403)
    self.assertEqual(json.loads(response.body), {
      'error': {
        'message': 'access denied',
      },
    }) 
Example #21
Source File: adapter_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def test_decode_message_get_resource_container(self):
    request = webapp2.Request(
        {
          'QUERY_STRING': 's=a',
        },
        method='GET',
        route_kwargs={'s2': 'b', 'x': 'c'},
    )
    rc = adapter.decode_message(
        EndpointsService.get_container.remote, request)
    self.assertEqual(rc.s, 'a')
    self.assertEqual(rc.s2, 'b')
    self.assertEqual(rc.x, 'c') 
Example #22
Source File: handler_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def test_applicable_admin(self):
    os.environ.update({
      'USER_EMAIL': 'joe@example.com',
      'USER_ID': '123',
      'USER_IS_ADMIN': '1',
    })
    # Actual request is not used by CookieAuthentication.
    self.assertEqual(
        (
          model.Identity(model.IDENTITY_USER, 'joe@example.com'),
          api.new_auth_details(is_superuser=True),
        ),
        handler.gae_cookie_authentication(webapp2.Request({}))) 
Example #23
Source File: adapter_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def test_decode_message_post(self):
    request = webapp2.Request(
        {
          'QUERY_STRING': 's2=b',
        },
        method='POST',
        body='{"s": "a"}',
    )
    msg = adapter.decode_message(EndpointsService.post.remote, request)
    self.assertEqual(msg.s, 'a')
    self.assertEqual(msg.s2, None)  # because it is not a ResourceContainer. 
Example #24
Source File: gce_vm_auth_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def call(self, payload):
    def mocked_verify_jwt(token, certs):
      self.assertEqual(token, self.TOKEN)
      self.assertIs(certs, self.CERTS)
      if isinstance(payload, Exception):
        raise payload
      return None, payload
    self.mock(tokens, 'verify_jwt', mocked_verify_jwt)

    req = webapp2.Request({})
    if payload is not None:
      req.headers[gce_vm_auth.GCE_VM_TOKEN_HEADER] = self.TOKEN
    return gce_vm_auth.gce_vm_authentication(req) 
Example #25
Source File: handler_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def test_non_applicable(self):
    request = webapp2.Request({})
    self.assertEqual(
        (None, None),
        handler.service_to_service_authentication(request)) 
Example #26
Source File: handler_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def test_applicable_admin(self):
    os.environ.update({
      'USER_EMAIL': 'joe@example.com',
      'USER_ID': '123',
      'USER_IS_ADMIN': '1',
    })
    # Actual request is not used by CookieAuthentication.
    self.assertEqual(
        (
          model.Identity(model.IDENTITY_USER, 'joe@example.com'),
          api.new_auth_details(is_superuser=True),
        ),
        handler.gae_cookie_authentication(webapp2.Request({}))) 
Example #27
Source File: handler_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def test_applicable_non_admin(self):
    os.environ.update({
      'USER_EMAIL': 'joe@example.com',
      'USER_ID': '123',
      'USER_IS_ADMIN': '0',
    })
    # Actual request is not used by CookieAuthentication.
    self.assertEqual(
        (
          model.Identity(model.IDENTITY_USER, 'joe@example.com'),
          api.new_auth_details(is_superuser=False),
        ),
        handler.gae_cookie_authentication(webapp2.Request({}))) 
Example #28
Source File: handler_test.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def test_non_applicable(self):
    self.assertEqual(
        (None, None),
        handler.gae_cookie_authentication(webapp2.Request({}))) 
Example #29
Source File: rest_api.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def do_get(cls, name, request):  # pylint: disable=unused-argument
    """Returns an entity given its name or None if no such entity.

    Can be called in any mode (including on replicas).

    Args:
      name: name of the entity to fetch (use get_entity_key to convert to key).
      request: webapp2.Request object.
    """
    return cls.get_entity_key(name).get() 
Example #30
Source File: handler.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def get_auth_methods(cls, conf):  # pylint: disable=unused-argument
    """Returns an enumerable of functions to use to authenticate request.

    The handler will try to apply auth methods sequentially one by one by until
    it finds one that works.

    Each auth method is a function that accepts webapp2.Request and can finish
    with 3 outcomes:

    * Return (None, ...): authentication method is not applicable to that
      request and next method should be tried (for example cookie-based
      authentication is not applicable when there's no cookies).

    * Returns (Identity, AuthDetails). It means the authentication method
      is applicable and the caller is authenticated as 'Identity'. All
      additional information extracted from the credentials (like if the caller
      is a GAE-level admin) is returned through AuthDetails tuple. It can be
      None if there are no extra information.

    * Raises AuthenticationError: authentication method is applicable, but
      request contains bad credentials or invalid token, etc. For example,
      OAuth2 token is given, but it is revoked.

    A chosen auth method function will be stored in request's auth_method field.

    Args:
      conf: components.auth GAE config, see config.py.
    """
    return (
        oauth_authentication,
        gae_cookie_authentication,
        service_to_service_authentication)