Python webapp2.RequestHandler() Examples

The following are 30 code examples for showing how to use webapp2.RequestHandler(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module webapp2 , or try the search function .

Example 1
Project: pledgeservice   Author: MayOneUS   File: admin.py    License: Apache License 2.0 6 votes vote down vote up
def MakeCommandHandler(cmd_cls):
  """Takes a command class and returns a route tuple which allows that command
     to be executed.
  """
  class H(webapp2.RequestHandler):
    def get(self):
      self.response.write("""
      <h1>You are about to run command "{}". Are you sure?</h1>
      <form action="" method="POST">
      <button>Punch it</button>
      </form>""".format(self._get_cmd().NAME))

    def post(self):
      deferred.defer(self._get_cmd().run)
      self.response.write('Command started.')

    def _get_cmd(self):
      if 'cmds' not in self.app.registry:
        self.app.registry['cmds'] = {}
      if cmd_cls.SHORT_NAME not in self.app.registry['cmds']:
        self.app.registry['cmds'][cmd_cls.SHORT_NAME] = cmd_cls(self.app.config)
      return self.app.registry['cmds'][cmd_cls.SHORT_NAME]

  return ('/admin/command/' + cmd_cls.SHORT_NAME, H) 
Example 2
Project: aqua-monitor   Author: Deltares   File: appengine.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def _build_state_value(request_handler, user):
    """Composes the value for the 'state' parameter.

    Packs the current request URI and an XSRF token into an opaque string that
    can be passed to the authentication server via the 'state' parameter.

    Args:
        request_handler: webapp.RequestHandler, The request.
        user: google.appengine.api.users.User, The current user.

    Returns:
        The state value as a string.
    """
    uri = request_handler.request.url
    token = xsrfutil.generate_token(xsrf_secret_key(), user.user_id(),
                                    action_id=str(uri))
    return uri + ':' + token 
Example 3
Project: aqua-monitor   Author: Deltares   File: appengine.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def _create_flow(self, request_handler):
        """Create the Flow object.

        The Flow is calculated lazily since we don't know where this app is
        running until it receives a request, at which point redirect_uri can be
        calculated and then the Flow object can be constructed.

        Args:
            request_handler: webapp.RequestHandler, the request handler.
        """
        if self.flow is None:
            redirect_uri = request_handler.request.relative_url(
                self._callback_path)  # Usually /oauth2callback
            self.flow = OAuth2WebServerFlow(
                self._client_id, self._client_secret, self._scope,
                redirect_uri=redirect_uri, user_agent=self._user_agent,
                auth_uri=self._auth_uri, token_uri=self._token_uri,
                revoke_uri=self._revoke_uri, **self._kwargs) 
Example 4
Project: alfred-gmail   Author: fniephaus   File: appengine.py    License: MIT License 6 votes vote down vote up
def _build_state_value(request_handler, user):
    """Composes the value for the 'state' parameter.

    Packs the current request URI and an XSRF token into an opaque string that
    can be passed to the authentication server via the 'state' parameter.

    Args:
        request_handler: webapp.RequestHandler, The request.
        user: google.appengine.api.users.User, The current user.

    Returns:
        The state value as a string.
    """
    uri = request_handler.request.url
    token = xsrfutil.generate_token(xsrf_secret_key(), user.user_id(),
                                    action_id=str(uri))
    return uri + ':' + token 
Example 5
Project: alfred-gmail   Author: fniephaus   File: appengine.py    License: MIT License 6 votes vote down vote up
def _create_flow(self, request_handler):
        """Create the Flow object.

        The Flow is calculated lazily since we don't know where this app is
        running until it receives a request, at which point redirect_uri can be
        calculated and then the Flow object can be constructed.

        Args:
            request_handler: webapp.RequestHandler, the request handler.
        """
        if self.flow is None:
            redirect_uri = request_handler.request.relative_url(
                self._callback_path)  # Usually /oauth2callback
            self.flow = client.OAuth2WebServerFlow(
                self._client_id, self._client_secret, self._scope,
                redirect_uri=redirect_uri, user_agent=self._user_agent,
                auth_uri=self._auth_uri, token_uri=self._token_uri,
                revoke_uri=self._revoke_uri, **self._kwargs) 
Example 6
Project: luci-py   Author: luci   File: appengine.py    License: Apache License 2.0 6 votes vote down vote up
def _build_state_value(request_handler, user):
    """Composes the value for the 'state' parameter.

    Packs the current request URI and an XSRF token into an opaque string that
    can be passed to the authentication server via the 'state' parameter.

    Args:
        request_handler: webapp.RequestHandler, The request.
        user: google.appengine.api.users.User, The current user.

    Returns:
        The state value as a string.
    """
    uri = request_handler.request.url
    token = xsrfutil.generate_token(xsrf_secret_key(), user.user_id(),
                                    action_id=str(uri))
    return uri + ':' + token 
Example 7
Project: luci-py   Author: luci   File: appengine.py    License: Apache License 2.0 6 votes vote down vote up
def _create_flow(self, request_handler):
        """Create the Flow object.

        The Flow is calculated lazily since we don't know where this app is
        running until it receives a request, at which point redirect_uri can be
        calculated and then the Flow object can be constructed.

        Args:
            request_handler: webapp.RequestHandler, the request handler.
        """
        if self.flow is None:
            redirect_uri = request_handler.request.relative_url(
                self._callback_path)  # Usually /oauth2callback
            self.flow = OAuth2WebServerFlow(
                self._client_id, self._client_secret, self._scope,
                redirect_uri=redirect_uri, user_agent=self._user_agent,
                auth_uri=self._auth_uri, token_uri=self._token_uri,
                revoke_uri=self._revoke_uri, **self._kwargs) 
Example 8
Project: luci-py   Author: luci   File: ui.py    License: Apache License 2.0 6 votes vote down vote up
def forbid_ui_on_replica(method):
  """Decorator for methods that are not allowed to be called on Replica.

  If such method is called on a service in Replica mode, it would return
  HTTP 405 "Method Not Allowed".
  """
  @functools.wraps(method)
  def wrapper(self, *args, **kwargs):
    assert isinstance(self, webapp2.RequestHandler)
    if model.is_replica():
      primary_url = model.get_replication_state().primary_url
      self.abort(
          405,
          detail='Not allowed on a replica, see primary at %s' % primary_url)
    return method(self, *args, **kwargs)
  return wrapper 
Example 9
Project: luci-py   Author: luci   File: rest_api.py    License: Apache License 2.0 6 votes vote down vote up
def forbid_api_on_replica(method):
  """Decorator for methods that are not allowed to be called on Replica.

  If such method is called on a service in Replica mode, it would return
  HTTP 405 "Method Not Allowed".
  """
  @functools.wraps(method)
  def wrapper(self, *args, **kwargs):
    assert isinstance(self, webapp2.RequestHandler)
    if model.is_replica():
      self.abort(
          405,
          json={
            'primary_url': model.get_replication_state().primary_url,
            'text': 'Use Primary service for API requests',
          },
          headers={
            'Content-Type': 'application/json; charset=utf-8',
          })
    return method(self, *args, **kwargs)
  return wrapper 
Example 10
Project: luci-py   Author: luci   File: rest_api_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_forbidden_on_replica(self):
    calls = []

    class Handler(webapp2.RequestHandler):
      @rest_api.forbid_api_on_replica
      def get(self):
        calls.append(1)

    mock_replication_state('http://locahost:1234')
    response = call_get(Handler, status=405)

    self.assertEqual(0, len(calls))
    expected = {
      'primary_url': 'http://locahost:1234',
      'text': 'Use Primary service for API requests',
    }
    self.assertEqual(expected, json.loads(response.body)) 
Example 11
Project: luci-py   Author: luci   File: rest_api_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_forbidden_on_replica(self):
    calls = []

    class Handler(webapp2.RequestHandler):
      @ui.forbid_ui_on_replica
      def get(self):
        calls.append(1)

    mock_replication_state('http://locahost:1234')
    response = call_get(Handler, status=405)

    self.assertEqual(0, len(calls))
    self.assertEqual(
        '405 Method Not Allowed\n\n'
        'The method GET is not allowed for this resource. \n\n '
        'Not allowed on a replica, see primary at http://locahost:1234',
        response.body) 
Example 12
Project: luci-py   Author: luci   File: adapter.py    License: Apache License 2.0 6 votes vote down vote up
def directory_handler_factory(api_classes, base_path):
  """Returns a directory request handler which knows about the given services.

  Args:
    api_classes: A list of protorpc.remote.Service classes the handler should
      know about.
    base_path: The base path under which all service paths exist.

  Returns:
    A webapp2.RequestHandler.
  """
  class DirectoryHandler(webapp2.RequestHandler):
    """Returns a directory list for known services."""

    def get(self):
      host = self.request.headers['Host']
      self.response.headers['Content-Type'] = 'application/json'
      json.dump(
          discovery.directory(api_classes, host, base_path),
          self.response, indent=2, sort_keys=True, separators=(',', ':'))

  return DirectoryHandler 
Example 13
Project: luci-py   Author: luci   File: adapter.py    License: Apache License 2.0 6 votes vote down vote up
def explorer_redirect_route(base_path):
  """Returns a route to a handler which redirects to the API explorer.

  Args:
    base_path: The base path under which all service paths exist.

  Returns:
    A webapp2.Route.
  """
  class RedirectHandler(webapp2.RequestHandler):
    """Returns a handler redirecting to the API explorer."""

    def get(self):
      host = self.request.headers['Host']
      self.redirect('https://apis-explorer.appspot.com/apis-explorer'
                    '/?base=https://%s%s' % (host, base_path))

  return webapp2.Route('%s/explorer' % base_path, RedirectHandler) 
Example 14
Project: luci-py   Author: luci   File: appengine.py    License: Apache License 2.0 6 votes vote down vote up
def _build_state_value(request_handler, user):
    """Composes the value for the 'state' parameter.

    Packs the current request URI and an XSRF token into an opaque string that
    can be passed to the authentication server via the 'state' parameter.

    Args:
        request_handler: webapp.RequestHandler, The request.
        user: google.appengine.api.users.User, The current user.

    Returns:
        The state value as a string.
    """
    uri = request_handler.request.url
    token = xsrfutil.generate_token(xsrf_secret_key(), user.user_id(),
                                    action_id=str(uri))
    return uri + ':' + token 
Example 15
Project: luci-py   Author: luci   File: appengine.py    License: Apache License 2.0 6 votes vote down vote up
def _create_flow(self, request_handler):
        """Create the Flow object.

        The Flow is calculated lazily since we don't know where this app is
        running until it receives a request, at which point redirect_uri can be
        calculated and then the Flow object can be constructed.

        Args:
            request_handler: webapp.RequestHandler, the request handler.
        """
        if self.flow is None:
            redirect_uri = request_handler.request.relative_url(
                self._callback_path)  # Usually /oauth2callback
            self.flow = OAuth2WebServerFlow(
                self._client_id, self._client_secret, self._scope,
                redirect_uri=redirect_uri, user_agent=self._user_agent,
                auth_uri=self._auth_uri, token_uri=self._token_uri,
                revoke_uri=self._revoke_uri, **self._kwargs) 
Example 16
Project: luci-py   Author: luci   File: appengine.py    License: Apache License 2.0 6 votes vote down vote up
def _build_state_value(request_handler, user):
    """Composes the value for the 'state' parameter.

    Packs the current request URI and an XSRF token into an opaque string that
    can be passed to the authentication server via the 'state' parameter.

    Args:
        request_handler: webapp.RequestHandler, The request.
        user: google.appengine.api.users.User, The current user.

    Returns:
        The state value as a string.
    """
    uri = request_handler.request.url
    token = xsrfutil.generate_token(xsrf_secret_key(), user.user_id(),
                                    action_id=str(uri))
    return uri + ':' + token 
Example 17
Project: luci-py   Author: luci   File: ui.py    License: Apache License 2.0 6 votes vote down vote up
def forbid_ui_on_replica(method):
  """Decorator for methods that are not allowed to be called on Replica.

  If such method is called on a service in Replica mode, it would return
  HTTP 405 "Method Not Allowed".
  """
  @functools.wraps(method)
  def wrapper(self, *args, **kwargs):
    assert isinstance(self, webapp2.RequestHandler)
    if model.is_replica():
      primary_url = model.get_replication_state().primary_url
      self.abort(
          405,
          detail='Not allowed on a replica, see primary at %s' % primary_url)
    return method(self, *args, **kwargs)
  return wrapper 
Example 18
Project: luci-py   Author: luci   File: ui.py    License: Apache License 2.0 6 votes vote down vote up
def redirect_ui_on_replica(method):
  """Decorator for methods that redirect to Primary when called on replica.

  If such method is called on a service in Replica mode, it would return
  HTTP 302 redirect to corresponding method on Primary.
  """
  @functools.wraps(method)
  def wrapper(self, *args, **kwargs):
    assert isinstance(self, webapp2.RequestHandler)
    assert self.request.method == 'GET'
    if model.is_replica():
      primary_url = model.get_replication_state().primary_url
      protocol = 'http://' if utils.is_local_dev_server() else 'https://'
      assert primary_url and primary_url.startswith(protocol), primary_url
      assert self.request.path_qs.startswith('/'), self.request.path_qs
      self.redirect(primary_url.rstrip('/') + self.request.path_qs, abort=True)
    return method(self, *args, **kwargs)
  return wrapper


################################################################################
## Admin routes. The use cookies and GAE's "is_current_user_admin" for authn. 
Example 19
Project: luci-py   Author: luci   File: rest_api.py    License: Apache License 2.0 6 votes vote down vote up
def forbid_api_on_replica(method):
  """Decorator for methods that are not allowed to be called on Replica.

  If such method is called on a service in Replica mode, it would return
  HTTP 405 "Method Not Allowed".
  """
  @functools.wraps(method)
  def wrapper(self, *args, **kwargs):
    assert isinstance(self, webapp2.RequestHandler)
    if model.is_replica():
      self.abort(
          405,
          json={
            'primary_url': model.get_replication_state().primary_url,
            'text': 'Use Primary service for API requests',
          },
          headers={
            'Content-Type': 'application/json; charset=utf-8',
          })
    return method(self, *args, **kwargs)
  return wrapper 
Example 20
Project: luci-py   Author: luci   File: rest_api_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_forbidden_on_replica(self):
    calls = []

    class Handler(webapp2.RequestHandler):
      @rest_api.forbid_api_on_replica
      def get(self):
        calls.append(1)

    mock_replication_state('http://locahost:1234')
    response = call_get(Handler, status=405)

    self.assertEqual(0, len(calls))
    expected = {
      'primary_url': 'http://locahost:1234',
      'text': 'Use Primary service for API requests',
    }
    self.assertEqual(expected, json.loads(response.body)) 
Example 21
Project: luci-py   Author: luci   File: rest_api_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_forbidden_on_replica(self):
    calls = []

    class Handler(webapp2.RequestHandler):
      @ui.forbid_ui_on_replica
      def get(self):
        calls.append(1)

    mock_replication_state('http://locahost:1234')
    response = call_get(Handler, status=405)

    self.assertEqual(0, len(calls))
    self.assertEqual(
        '405 Method Not Allowed\n\n'
        'The method GET is not allowed for this resource. \n\n '
        'Not allowed on a replica, see primary at http://locahost:1234',
        response.body) 
Example 22
Project: luci-py   Author: luci   File: adapter.py    License: Apache License 2.0 6 votes vote down vote up
def directory_handler_factory(api_classes, base_path):
  """Returns a directory request handler which knows about the given services.

  Args:
    api_classes: A list of protorpc.remote.Service classes the handler should
      know about.
    base_path: The base path under which all service paths exist.

  Returns:
    A webapp2.RequestHandler.
  """
  class DirectoryHandler(webapp2.RequestHandler):
    """Returns a directory list for known services."""

    def get(self):
      host = self.request.headers['Host']
      self.response.headers['Content-Type'] = 'application/json'
      json.dump(
          discovery.directory(api_classes, host, base_path),
          self.response, indent=2, sort_keys=True, separators=(',', ':'))

  return DirectoryHandler 
Example 23
Project: luci-py   Author: luci   File: adapter.py    License: Apache License 2.0 6 votes vote down vote up
def explorer_proxy_route(base_path):
  """Returns a route to a handler which serves an API explorer proxy.

  Args:
    base_path: The base path under which all service paths exist.

  Returns:
    A webapp2.Route.
  """
  class ProxyHandler(webapp2.RequestHandler):
    """Returns a proxy capable of handling requests from API explorer."""

    def get(self):
      self.response.write(template.render(
          'adapter/proxy.html', params={'base_path': base_path}))

  template.bootstrap({
      'adapter': os.path.join(THIS_DIR, 'templates'),
  })
  return webapp2.Route('%s/static/proxy.html' % base_path, ProxyHandler) 
Example 24
Project: luci-py   Author: luci   File: adapter.py    License: Apache License 2.0 6 votes vote down vote up
def explorer_redirect_route(base_path):
  """Returns a route to a handler which redirects to the API explorer.

  Args:
    base_path: The base path under which all service paths exist.

  Returns:
    A webapp2.Route.
  """
  class RedirectHandler(webapp2.RequestHandler):
    """Returns a handler redirecting to the API explorer."""

    def get(self):
      host = self.request.headers['Host']
      self.redirect('https://apis-explorer.appspot.com/apis-explorer'
                    '/?base=https://%s%s' % (host, base_path))

  return webapp2.Route('%s/explorer' % base_path, RedirectHandler) 
Example 25
Project: luci-py   Author: luci   File: ui.py    License: Apache License 2.0 6 votes vote down vote up
def forbid_ui_on_replica(method):
  """Decorator for methods that are not allowed to be called on Replica.

  If such method is called on a service in Replica mode, it would return
  HTTP 405 "Method Not Allowed".
  """
  @functools.wraps(method)
  def wrapper(self, *args, **kwargs):
    assert isinstance(self, webapp2.RequestHandler)
    if model.is_replica():
      primary_url = model.get_replication_state().primary_url
      self.abort(
          405,
          detail='Not allowed on a replica, see primary at %s' % primary_url)
    return method(self, *args, **kwargs)
  return wrapper 
Example 26
Project: luci-py   Author: luci   File: rest_api.py    License: Apache License 2.0 6 votes vote down vote up
def forbid_api_on_replica(method):
  """Decorator for methods that are not allowed to be called on Replica.

  If such method is called on a service in Replica mode, it would return
  HTTP 405 "Method Not Allowed".
  """
  @functools.wraps(method)
  def wrapper(self, *args, **kwargs):
    assert isinstance(self, webapp2.RequestHandler)
    if model.is_replica():
      self.abort(
          405,
          json={
            'primary_url': model.get_replication_state().primary_url,
            'text': 'Use Primary service for API requests',
          },
          headers={
            'Content-Type': 'application/json; charset=utf-8',
          })
    return method(self, *args, **kwargs)
  return wrapper 
Example 27
Project: luci-py   Author: luci   File: rest_api_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_forbidden_on_replica(self):
    calls = []

    class Handler(webapp2.RequestHandler):
      @rest_api.forbid_api_on_replica
      def get(self):
        calls.append(1)

    mock_replication_state('http://locahost:1234')
    response = call_get(Handler, status=405)

    self.assertEqual(0, len(calls))
    expected = {
      'primary_url': 'http://locahost:1234',
      'text': 'Use Primary service for API requests',
    }
    self.assertEqual(expected, json.loads(response.body)) 
Example 28
Project: luci-py   Author: luci   File: rest_api_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_forbidden_on_replica(self):
    calls = []

    class Handler(webapp2.RequestHandler):
      @ui.forbid_ui_on_replica
      def get(self):
        calls.append(1)

    mock_replication_state('http://locahost:1234')
    response = call_get(Handler, status=405)

    self.assertEqual(0, len(calls))
    self.assertEqual(
        '405 Method Not Allowed\n\n'
        'The method GET is not allowed for this resource. \n\n '
        'Not allowed on a replica, see primary at http://locahost:1234',
        response.body) 
Example 29
Project: loaner   Author: google   File: frontend.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
    """Override RequestHandler init to track app readiness."""
    super(FrontendHandler, self).__init__(*args, **kwargs)
    self.bootstrap_started = bootstrap.is_bootstrap_started()
    self.bootstrap_completed = bootstrap.is_bootstrap_completed() 
Example 30
Project: locality-sensitive-hashing   Author: singhj   File: session.py    License: MIT License 5 votes vote down vote up
def dispatch(self):
        # Get a session store for this request.
        self.session_store = sessions.get_store(request=self.request)

        try:
            # Dispatch the request.
            webapp2.RequestHandler.dispatch(self)
        finally:
            # Save all sessions.
            self.session_store.save_sessions(self.response)