Python google.appengine.ext.webapp.WSGIApplication() Examples

The following are code examples for showing how to use google.appengine.ext.webapp.WSGIApplication(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: mimic   Author: googlearchive   File: control.py    Apache License 2.0 6 votes vote down vote up
def MakeControlApp(tree, namespace, create_channel_fn=channel.create_channel):
  """Create and return a WSGI application for controlling Mimic."""
  # standard handlers
  handlers = [
      ('/clear', _ClearHandler),
      ('/delete', _DeleteHandler),
      ('/dir', _DirHandler),
      ('/ziprepo', _ZipFromRepoHandler),
      ('/zip', _ZipHandler),
      ('/file', _FileHandler),
      ('/index', _IndexHandler),
      ('/log', _LogRequestHandler),
      ('/move', _MoveHandler),
      ('/version_id', _VersionIdHandler),
  ]
  # prepend CONTROL_PREFIX to all handler paths
  handlers = [(common.CONTROL_PREFIX + p, h) for (p, h) in handlers]
  config = {'tree': tree, 'namespace': namespace,
            'create_channel_fn': create_channel_fn}
  return webapp.WSGIApplication(handlers, debug=True, config=config) 
Example 2
Project: octopuscloud   Author: christianbaun   File: octopus.py    Apache License 2.0 6 votes vote down vote up
def main():
    application = webapp.WSGIApplication([('/', MainPage),
                                          ('/regionen', Regionen),
                                          ('/login', Login),
                                          ('/sprache', Sprache),
                                          ('/info', MainPage),
                                          ('/zugangeinrichten', ZugangEinrichten),
                                          ('/zugangentfernen', ZugangEntfernen),
                                          ('/regionwechseln', RegionWechseln),
                                          ('/persoenliche_datan_loeschen', PersoenlicheDatanLoeschen),
                                          ('/s3', S3),
                                          ('/bucketkeyentfernen', BucketKeyEntfernen),
                                          ('/acl_einsehen', ACL_einsehen),
                                          ('/acl_aendern', ACL_Aendern),
                                          ('/alle_keys_loeschen', AlleKeysLoeschenFrage),
                                          ('/alle_keys_loeschen_definitiv', AlleKeysLoeschenDefinitiv)],
                                          debug=True)
    wsgiref.handlers.CGIHandler().run(application) 
Example 3
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: bulkload_deprecated.py    Apache License 2.0 6 votes vote down vote up
def main(*loaders):
  """Starts bulk upload.

  Raises TypeError if not, at least one Loader instance is given.

  Args:
    loaders: One or more Loader instance.
  """
  if not loaders:
    raise TypeError('Expected at least one argument.')

  for loader in loaders:
    if not isinstance(loader, Loader):
      raise TypeError('Expected a Loader instance; received %r' % loader)

  application = webapp.WSGIApplication([('.*', BulkLoad)])
  wsgiref.handlers.CGIHandler().run(application) 
Example 4
Project: mimic   Author: googlearchive   File: shell.py    Apache License 2.0 5 votes vote down vote up
def MakeShellApp(tree, namespace):
  """Create and return a WSGI application for controlling Mimic."""
  # standard handlers
  handlers = [
      ('/python/file', FileHandler),
      ]
  # prepend CONTROL_PREFIX to all handler paths
  handlers = [(common.SHELL_PREFIX + p, h) for (p, h) in handlers]
  config = {'tree': tree, 'namespace': namespace}
  return webapp.WSGIApplication(handlers, debug=True, config=config) 
Example 5
Project: sndlatr   Author: Schibum   File: appengine.py    Apache License 2.0 5 votes vote down vote up
def callback_application(self):
    """WSGI application for handling the OAuth 2.0 redirect callback.

    If you need finer grained control use `callback_handler` which returns just
    the webapp.RequestHandler.

    Returns:
      A webapp.WSGIApplication that handles the redirect back from the
      server during the OAuth 2.0 dance.
    """
    return webapp.WSGIApplication([
        (self.callback_path, self.callback_handler())
        ]) 
Example 6
Project: experts-app-backend   Author: GoogleDeveloperExperts   File: appengine.py    Apache License 2.0 5 votes vote down vote up
def callback_application(self):
    """WSGI application for handling the OAuth 2.0 redirect callback.

    If you need finer grained control use `callback_handler` which returns just
    the webapp.RequestHandler.

    Returns:
      A webapp.WSGIApplication that handles the redirect back from the
      server during the OAuth 2.0 dance.
    """
    return webapp.WSGIApplication([
        (self.callback_path, self.callback_handler())
        ]) 
Example 7
Project: mlab-ns   Author: m-lab   File: main.py    Apache License 2.0 5 votes vote down vote up
def create_handlers_map():
  """Create new handlers map.

  Returns:
    list of (regexp, handler) pairs for WSGIApplication constructor.
  """
  pipeline_handlers_map = []

  if pipeline:
    pipeline_handlers_map = pipeline.create_handlers_map(prefix=".*/pipeline")

  return pipeline_handlers_map + [
      # Task queue handlers.
      (r".*/worker_callback", handlers.MapperWorkerCallbackHandler),
      (r".*/controller_callback", handlers.ControllerCallbackHandler),
      (r".*/kickoffjob_callback", handlers.KickOffJobHandler),
      (r".*/finalizejob_callback", handlers.FinalizeJobHandler),

      # RPC requests with JSON responses
      # All JSON handlers should have /command/ prefix.
      (r".*/command/start_job", handlers.StartJobHandler),
      (r".*/command/cleanup_job", handlers.CleanUpJobHandler),
      (r".*/command/abort_job", handlers.AbortJobHandler),
      (r".*/command/list_configs", status.ListConfigsHandler),
      (r".*/command/list_jobs", status.ListJobsHandler),
      (r".*/command/get_job_detail", status.GetJobDetailHandler),

      # UI static files
      (STATIC_RE, status.ResourceHandler),

      # Redirect non-file URLs that do not end in status/detail to status page.
      (r".*", RedirectHandler),
      ] 
Example 8
Project: mlab-ns   Author: m-lab   File: main.py    Apache License 2.0 5 votes vote down vote up
def create_application():
  """Create new WSGIApplication and register all handlers.

  Returns:
    an instance of webapp.WSGIApplication with all mapreduce handlers
    registered.
  """
  return webapp.WSGIApplication(create_handlers_map(),
                                debug=True) 
Example 9
Project: mekong-ssc-gae   Author: KMarkert   File: appengine.py    GNU General Public License v3.0 5 votes vote down vote up
def callback_application(self):
    """WSGI application for handling the OAuth 2.0 redirect callback.

    If you need finer grained control use `callback_handler` which returns just
    the webapp.RequestHandler.

    Returns:
      A webapp.WSGIApplication that handles the redirect back from the
      server during the OAuth 2.0 dance.
    """
    return webapp.WSGIApplication([
        (self.callback_path, self.callback_handler())
        ]) 
Example 10
Project: ecodash   Author: Servir-Mekong   File: appengine.py    GNU General Public License v3.0 5 votes vote down vote up
def callback_application(self):
    """WSGI application for handling the OAuth 2.0 redirect callback.

    If you need finer grained control use `callback_handler` which returns just
    the webapp.RequestHandler.

    Returns:
      A webapp.WSGIApplication that handles the redirect back from the
      server during the OAuth 2.0 dance.
    """
    return webapp.WSGIApplication([
        (self.callback_path, self.callback_handler())
        ]) 
Example 11
Project: chromabrush   Author: liuyanghejerry   File: server.py    Apache License 2.0 5 votes vote down vote up
def main():
    application = webapp.WSGIApplication([('/', MainHandler)], debug=False)
    util.run_wsgi_app(application) 
Example 12
Project: chromabrush   Author: liuyanghejerry   File: image.py    Apache License 2.0 5 votes vote down vote up
def main():
  application = webapp.WSGIApplication([
      ('/image/?(.*)', MainHandler)
  ], debug=True)
  util.run_wsgi_app(application) 
Example 13
Project: luci-py   Author: luci   File: main.py    Apache License 2.0 5 votes vote down vote up
def create_handlers_map():
  """Create new handlers map.

  Returns:
    list of (regexp, handler) pairs for WSGIApplication constructor.
  """
  pipeline_handlers_map = []

  if pipeline:
    pipeline_handlers_map = pipeline.create_handlers_map(prefix=".*/pipeline")

  return pipeline_handlers_map + [
      # Task queue handlers.
      # Always suffix by mapreduce_id or shard_id for log analysis purposes.
      # mapreduce_id or shard_id also presents in headers or payload.
      (r".*/worker_callback.*", handlers.MapperWorkerCallbackHandler),
      (r".*/controller_callback.*", handlers.ControllerCallbackHandler),
      (r".*/kickoffjob_callback.*", handlers.KickOffJobHandler),
      (r".*/finalizejob_callback.*", handlers.FinalizeJobHandler),

      # RPC requests with JSON responses
      # All JSON handlers should have /command/ prefix.
      (r".*/command/start_job", handlers.StartJobHandler),
      (r".*/command/cleanup_job", handlers.CleanUpJobHandler),
      (r".*/command/abort_job", handlers.AbortJobHandler),
      (r".*/command/list_configs", status.ListConfigsHandler),
      (r".*/command/list_jobs", status.ListJobsHandler),
      (r".*/command/get_job_detail", status.GetJobDetailHandler),

      # UI static files
      (STATIC_RE, status.ResourceHandler),

      # Redirect non-file URLs that do not end in status/detail to status page.
      (r".*", RedirectHandler),
      ] 
Example 14
Project: luci-py   Author: luci   File: main.py    Apache License 2.0 5 votes vote down vote up
def create_application():
  """Create new WSGIApplication and register all handlers.

  Returns:
    an instance of webapp.WSGIApplication with all mapreduce handlers
    registered.
  """
  return webapp.WSGIApplication(create_handlers_map(),
                                debug=True) 
Example 15
Project: luci-py   Author: luci   File: main.py    Apache License 2.0 5 votes vote down vote up
def create_handlers_map():
  """Create new handlers map.

  Returns:
    list of (regexp, handler) pairs for WSGIApplication constructor.
  """
  pipeline_handlers_map = []

  if pipeline:
    pipeline_handlers_map = pipeline.create_handlers_map(prefix=".*/pipeline")

  return pipeline_handlers_map + [
      # Task queue handlers.
      # Always suffix by mapreduce_id or shard_id for log analysis purposes.
      # mapreduce_id or shard_id also presents in headers or payload.
      (r".*/worker_callback.*", handlers.MapperWorkerCallbackHandler),
      (r".*/controller_callback.*", handlers.ControllerCallbackHandler),
      (r".*/kickoffjob_callback.*", handlers.KickOffJobHandler),
      (r".*/finalizejob_callback.*", handlers.FinalizeJobHandler),

      # RPC requests with JSON responses
      # All JSON handlers should have /command/ prefix.
      (r".*/command/start_job", handlers.StartJobHandler),
      (r".*/command/cleanup_job", handlers.CleanUpJobHandler),
      (r".*/command/abort_job", handlers.AbortJobHandler),
      (r".*/command/list_configs", status.ListConfigsHandler),
      (r".*/command/list_jobs", status.ListJobsHandler),
      (r".*/command/get_job_detail", status.GetJobDetailHandler),

      # UI static files
      (STATIC_RE, status.ResourceHandler),

      # Redirect non-file URLs that do not end in status/detail to status page.
      (r".*", RedirectHandler),
      ] 
Example 16
Project: luci-py   Author: luci   File: main.py    Apache License 2.0 5 votes vote down vote up
def create_application():
  """Create new WSGIApplication and register all handlers.

  Returns:
    an instance of webapp.WSGIApplication with all mapreduce handlers
    registered.
  """
  return webapp.WSGIApplication(create_handlers_map(),
                                debug=True) 
Example 17
Project: cocoslive   Author: ricardoquesada   File: zip_handler.py    GNU General Public License v3.0 5 votes vote down vote up
def main():
  """Sets up handlers for the zip files."""
  file_icons = zipserve.make_zip_handler('fileicons.zip')
  flag_icons = zipserve.make_zip_handler('flags.zip')
  fck_editor = zipserve.make_zip_handler('third_party/fckeditor.zip')
  
  application = webapp.WSGIApplication(
      [('/static/images/fileicons/(.*)', file_icons),
       ('/static/images/flags/(.*)', flag_icons),
       ('/fckeditor/(.*)', fck_editor),
      ],
      debug=True)
  util.run_wsgi_app(application) 
Example 18
Project: node-gn   Author: Shouqun   File: appengine.py    MIT License 5 votes vote down vote up
def callback_application(self):
    """WSGI application for handling the OAuth 2.0 redirect callback.

    If you need finer grained control use `callback_handler` which returns just
    the webapp.RequestHandler.

    Returns:
      A webapp.WSGIApplication that handles the redirect back from the
      server during the OAuth 2.0 dance.
    """
    return webapp.WSGIApplication([
        (self.callback_path, self.callback_handler())
        ]) 
Example 19
Project: SurfaceWaterTool   Author: Servir-Mekong   File: appengine.py    GNU General Public License v3.0 5 votes vote down vote up
def callback_application(self):
    """WSGI application for handling the OAuth 2.0 redirect callback.

    If you need finer grained control use `callback_handler` which returns just
    the webapp.RequestHandler.

    Returns:
      A webapp.WSGIApplication that handles the redirect back from the
      server during the OAuth 2.0 dance.
    """
    return webapp.WSGIApplication([
        (self.callback_path, self.callback_handler())
        ]) 
Example 20
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: ui.py    Apache License 2.0 5 votes vote down vote up
def main():
  """Main program. Run the auth checking middleware wrapped WSGIApplication."""
  util.run_bare_wsgi_app(app) 
Example 21
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: _webapp25.py    Apache License 2.0 5 votes vote down vote up
def new_factory(cls, *args, **kwargs):
    """Create new request handler factory.

    Use factory method to create reusable request handlers that just
    require a few configuration parameters to construct.  Also useful
    for injecting shared state between multiple request handler
    instances without relying on global variables.  For example, to
    create a set of post handlers that will do simple text transformations
    you can write:

      class ChangeTextHandler(webapp.RequestHandler):

        def __init__(self, transform):
          self.transform = transform

        def post(self):
          response_text = self.transform(
              self.request.request.body_file.getvalue())
          self.response.out.write(response_text)

      application = webapp.WSGIApplication(
          [('/to_lower', ChangeTextHandler.new_factory(str.lower)),
           ('/to_upper', ChangeTextHandler.new_factory(str.upper)),
          ],
          debug=True)

    Text POSTed to /to_lower will be lower cased.
    Text POSTed to /to_upper will be upper cased.
    """
    def new_instance():
      return cls(*args, **kwargs)
    new_instance.__name__ = cls.__name__ + 'Factory'
    return new_instance 
Example 22
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: _webapp25.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, url_mapping, debug=False):
    """Initializes this application with the given URL mapping.

    Args:
      url_mapping: list of (URI regular expression, RequestHandler) pairs
                   (e.g., [('/', ReqHan)])
      debug: if true, we send Python stack traces to the browser on errors
    """
    self._init_url_mappings(url_mapping)
    self.__debug = debug


    WSGIApplication.active_instance = self
    self.current_request_args = () 
Example 23
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: _webapp25.py    Apache License 2.0 5 votes vote down vote up
def __call__(self, environ, start_response):
    """Called by WSGI when a request comes in."""
    request = self.REQUEST_CLASS(environ)
    response = self.RESPONSE_CLASS()


    WSGIApplication.active_instance = self


    handler = None
    groups = ()
    for regexp, handler_class in self._url_mapping:
      match = regexp.match(request.path)
      if match:
        try:
          handler = handler_class()



          handler.initialize(request, response)
        except Exception, e:
          if handler is None:
            handler = RequestHandler()
          handler.response = response
          handler.handle_exception(e, self.__debug)
          response.wsgi_write(start_response)
          return ['']
        groups = match.groups()
        break 
Example 24
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: main.py    Apache License 2.0 5 votes vote down vote up
def CreateApplication():
  """Create new WSGIApplication and register all handlers.

  Returns:
    an instance of webapp.WSGIApplication with all mapreduce handlers
    registered.
  """
  return webapp.WSGIApplication([(r'.*', RedirectToAdminConsole)],
                                debug=True) 
Example 25
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def get(self, prefix, name):
    """GET request handler.

    Typically the arguments are passed from the matching groups in the
    URL pattern passed to WSGIApplication().

    Args:
      prefix: The zipfilename without the .zip suffix.
      name: The name within the zipfile.
    """
    self.ServeFromZipFile(prefix + '.zip', name) 
Example 26
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def main():
  """Main program.

  This is invoked when this package is referenced from app.yaml.
  """
  application = webapp.WSGIApplication([('/([^/]+)/(.*)', ZipHandler)])
  util.run_wsgi_app(application) 
Example 27
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: main.py    Apache License 2.0 5 votes vote down vote up
def create_handlers_map():
  """Create new handlers map.

  Returns:
    list of (regexp, handler) pairs for WSGIApplication constructor.
  """
  pipeline_handlers_map = []

  if pipeline:
    pipeline_handlers_map = pipeline.create_handlers_map(prefix=".*/pipeline")

  return pipeline_handlers_map + [



      (r".*/worker_callback.*", handlers.MapperWorkerCallbackHandler),
      (r".*/controller_callback.*", handlers.ControllerCallbackHandler),
      (r".*/kickoffjob_callback.*", handlers.KickOffJobHandler),
      (r".*/finalizejob_callback.*", handlers.FinalizeJobHandler),



      (r".*/command/start_job", handlers.StartJobHandler),
      (r".*/command/cleanup_job", handlers.CleanUpJobHandler),
      (r".*/command/abort_job", handlers.AbortJobHandler),
      (r".*/command/list_configs", status.ListConfigsHandler),
      (r".*/command/list_jobs", status.ListJobsHandler),
      (r".*/command/get_job_detail", status.GetJobDetailHandler),


      (STATIC_RE, status.ResourceHandler),


      (r".*", RedirectHandler),
      ] 
Example 28
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: main.py    Apache License 2.0 5 votes vote down vote up
def create_application():
  """Create new WSGIApplication and register all handlers.

  Returns:
    an instance of webapp.WSGIApplication with all mapreduce handlers
    registered.
  """
  return webapp.WSGIApplication(create_handlers_map(),
                                debug=True) 
Example 29
Project: python-for-android   Author: kuri65536   File: blogapp.py    Apache License 2.0 5 votes vote down vote up
def main():
  application = webapp.WSGIApplication([('/blogs', ListBlogs), 
                                        ('/write_post', WritePost)],
      debug=True)
  wsgiref.handlers.CGIHandler().run(application) 
Example 30
Project: python-for-android   Author: kuri65536   File: main_rsa.py    Apache License 2.0 5 votes vote down vote up
def main():
  application = webapp.WSGIApplication([('/', MainPage),
                                        ('/get_oauth_token', OAuthDance),
                                        ('/fetch_data', FetchData),
                                        ('/revoke_token', RevokeToken)],
                                        debug=True)
  run_wsgi_app(application) 
Example 31
Project: python-for-android   Author: kuri65536   File: main_hmac.py    Apache License 2.0 5 votes vote down vote up
def main():
  application = webapp.WSGIApplication([('/', MainPage),
                                        ('/get_oauth_token', OAuthDance),
                                        ('/fetch_data', FetchData),
                                        ('/revoke_token', RevokeToken)],
                                        debug=True)
  run_wsgi_app(application) 
Example 32
Project: yumstat   Author: RKD314   File: appengine.py    MIT License 5 votes vote down vote up
def callback_application(self):
    """WSGI application for handling the OAuth 2.0 redirect callback.

    If you need finer grained control use `callback_handler` which returns just
    the webapp.RequestHandler.

    Returns:
      A webapp.WSGIApplication that handles the redirect back from the
      server during the OAuth 2.0 dance.
    """
    return webapp.WSGIApplication([
        (self.callback_path, self.callback_handler())
        ]) 
Example 33
Project: yumstat   Author: RKD314   File: appengine.py    MIT License 5 votes vote down vote up
def callback_application(self):
    """WSGI application for handling the OAuth 2.0 redirect callback.

    If you need finer grained control use `callback_handler` which returns just
    the webapp.RequestHandler.

    Returns:
      A webapp.WSGIApplication that handles the redirect back from the
      server during the OAuth 2.0 dance.
    """
    return webapp.WSGIApplication([
        (self.callback_path, self.callback_handler())
        ]) 
Example 34
Project: sndlatr   Author: Schibum   File: appengine.py    Apache License 2.0 4 votes vote down vote up
def callback_handler(self):
    """RequestHandler for the OAuth 2.0 redirect callback.

    Usage:
       app = webapp.WSGIApplication([
         ('/index', MyIndexHandler),
         ...,
         (decorator.callback_path, decorator.callback_handler())
       ])

    Returns:
      A webapp.RequestHandler that handles the redirect back from the
      server during the OAuth 2.0 dance.
    """
    decorator = self

    class OAuth2Handler(webapp.RequestHandler):
      """Handler for the redirect_uri of the OAuth 2.0 dance."""

      @login_required
      def get(self):
        error = self.request.get('error')
        if error:
          errormsg = self.request.get('error_description', error)
          self.response.out.write(
              'The authorization request failed: %s' % _safe_html(errormsg))
        else:
          user = users.get_current_user()
          decorator._create_flow(self)
          credentials = decorator.flow.step2_exchange(self.request.params)
          decorator._storage_class(
              decorator._credentials_class, None,
              decorator._credentials_property_name, user=user).put(credentials)
          redirect_uri = _parse_state_value(str(self.request.get('state')),
                                            user)

          if decorator._token_response_param and credentials.token_response:
            resp_json = simplejson.dumps(credentials.token_response)
            redirect_uri = util._add_query_parameter(
                redirect_uri, decorator._token_response_param, resp_json)

          self.redirect(redirect_uri)

    return OAuth2Handler 
Example 35
Project: experts-app-backend   Author: GoogleDeveloperExperts   File: appengine.py    Apache License 2.0 4 votes vote down vote up
def callback_handler(self):
    """RequestHandler for the OAuth 2.0 redirect callback.

    Usage:
       app = webapp.WSGIApplication([
         ('/index', MyIndexHandler),
         ...,
         (decorator.callback_path, decorator.callback_handler())
       ])

    Returns:
      A webapp.RequestHandler that handles the redirect back from the
      server during the OAuth 2.0 dance.
    """
    decorator = self

    class OAuth2Handler(webapp.RequestHandler):
      """Handler for the redirect_uri of the OAuth 2.0 dance."""

      @login_required
      def get(self):
        error = self.request.get('error')
        if error:
          errormsg = self.request.get('error_description', error)
          self.response.out.write(
              'The authorization request failed: %s' % _safe_html(errormsg))
        else:
          user = users.get_current_user()
          decorator._create_flow(self)
          credentials = decorator.flow.step2_exchange(self.request.params)
          decorator._storage_class(
              decorator._credentials_class, None,
              decorator._credentials_property_name, user=user).put(credentials)
          redirect_uri = _parse_state_value(str(self.request.get('state')),
                                            user)

          if decorator._token_response_param and credentials.token_response:
            resp_json = simplejson.dumps(credentials.token_response)
            redirect_uri = util._add_query_parameter(
                redirect_uri, decorator._token_response_param, resp_json)

          self.redirect(redirect_uri)

    return OAuth2Handler 
Example 36
Project: mekong-ssc-gae   Author: KMarkert   File: appengine.py    GNU General Public License v3.0 4 votes vote down vote up
def callback_handler(self):
    """RequestHandler for the OAuth 2.0 redirect callback.

    Usage:
       app = webapp.WSGIApplication([
         ('/index', MyIndexHandler),
         ...,
         (decorator.callback_path, decorator.callback_handler())
       ])

    Returns:
      A webapp.RequestHandler that handles the redirect back from the
      server during the OAuth 2.0 dance.
    """
    decorator = self

    class OAuth2Handler(webapp.RequestHandler):
      """Handler for the redirect_uri of the OAuth 2.0 dance."""

      @login_required
      def get(self):
        error = self.request.get('error')
        if error:
          errormsg = self.request.get('error_description', error)
          self.response.out.write(
              'The authorization request failed: %s' % _safe_html(errormsg))
        else:
          user = users.get_current_user()
          decorator._create_flow(self)
          credentials = decorator.flow.step2_exchange(self.request.params)
          decorator._storage_class(
              decorator._credentials_class, None,
              decorator._credentials_property_name, user=user).put(credentials)
          redirect_uri = _parse_state_value(str(self.request.get('state')),
                                            user)

          if decorator._token_response_param and credentials.token_response:
            resp_json = json.dumps(credentials.token_response)
            redirect_uri = util._add_query_parameter(
                redirect_uri, decorator._token_response_param, resp_json)

          self.redirect(redirect_uri)

    return OAuth2Handler 
Example 37
Project: ecodash   Author: Servir-Mekong   File: appengine.py    GNU General Public License v3.0 4 votes vote down vote up
def callback_handler(self):
    """RequestHandler for the OAuth 2.0 redirect callback.

    Usage:
       app = webapp.WSGIApplication([
         ('/index', MyIndexHandler),
         ...,
         (decorator.callback_path, decorator.callback_handler())
       ])

    Returns:
      A webapp.RequestHandler that handles the redirect back from the
      server during the OAuth 2.0 dance.
    """
    decorator = self

    class OAuth2Handler(webapp.RequestHandler):
      """Handler for the redirect_uri of the OAuth 2.0 dance."""

      @login_required
      def get(self):
        error = self.request.get('error')
        if error:
          errormsg = self.request.get('error_description', error)
          self.response.out.write(
              'The authorization request failed: %s' % _safe_html(errormsg))
        else:
          user = users.get_current_user()
          decorator._create_flow(self)
          credentials = decorator.flow.step2_exchange(self.request.params)
          decorator._storage_class(
              decorator._credentials_class, None,
              decorator._credentials_property_name, user=user).put(credentials)
          redirect_uri = _parse_state_value(str(self.request.get('state')),
                                            user)

          if decorator._token_response_param and credentials.token_response:
            resp_json = json.dumps(credentials.token_response)
            redirect_uri = util._add_query_parameter(
                redirect_uri, decorator._token_response_param, resp_json)

          self.redirect(redirect_uri)

    return OAuth2Handler 
Example 38
Project: server   Author: viur-framework   File: __init__.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def setup( modules, render=None, default="html" ):
	"""
		Define whats going to be served by this instance.

		:param config: Usually the module provided as *modules* directory within the application.
		:type config: module | object
		:param renders: Usually the module *server.renders*, or a dictionary renderName => renderClass.
		:type renders: module | dict
		:param default: Name of the renderer, which will form the root of the application.\
		This will be the renderer, which wont get a prefix, usually html. \
		(=> /user instead of /html/user)
		:type default: str
	"""
	import skeletons	# This import is not used here but _must_ remain to ensure that the
						# application's data models are explicitly imported at some place!

	from server.bones import bone

	if not render:
		import server.render
		render = server.render
	conf["viur.mainApp"] = buildApp( modules, render, default )
	renderPrefix = [ "/%s" % x for x in dir( render ) if (not x.startswith("_") and x!=default) ]+[""]
	conf["viur.wsgiApp"] = webapp.WSGIApplication( [(r'/(.*)', BrowseHandler)] )
	# Ensure that our Content Security Policy Header Cache gets build
	from server import securityheaders
	securityheaders._rebuildCspHeaderCache()
	bone.setSystemInitialized()
	# Assert that all security releated headers are in a sane state
	if conf["viur.security.contentSecurityPolicy"] and conf["viur.security.contentSecurityPolicy"]["_headerCache"]:
		for k, v in conf["viur.security.contentSecurityPolicy"]["_headerCache"].items():
			assert k.startswith(
				"Content-Security-Policy"), "Got unexpected header in conf['viur.security.contentSecurityPolicy']['_headerCache']"
	if conf["viur.security.strictTransportSecurity"]:
		assert conf["viur.security.strictTransportSecurity"].startswith(
			"max-age"), "Got unexpected header in conf['viur.security.strictTransportSecurity']"
	if conf["viur.security.publicKeyPins"]:
		assert conf["viur.security.publicKeyPins"].startswith(
			"pin-"), "Got unexpected header in conf['viur.security.publicKeyPins']"
	assert conf["viur.security.xPermittedCrossDomainPolicies"] in [None, "none", "master-only", "by-content-type", "all"], \
		"conf[\"viur.security.xPermittedCrossDomainPolicies\"] must be one of [None, \"none\", \"master-only\", \"by-content-type\", \"all\"]"
	if conf["viur.security.xFrameOptions"] is not None and isinstance(conf["viur.security.xFrameOptions"], tuple):
		mode, uri = conf["viur.security.xFrameOptions"]
		assert mode in ["deny", "sameorigin", "allow-from"]
		if mode == "allow-from":
			assert uri is not None and (
			uri.lower().startswith("https://") or uri.lower().startswith("http://"))
	runStartupTasks() #Add a deferred call to run all queued startup tasks
	return( conf["viur.wsgiApp"] ) 
Example 39
Project: node-gn   Author: Shouqun   File: appengine.py    MIT License 4 votes vote down vote up
def callback_handler(self):
    """RequestHandler for the OAuth 2.0 redirect callback.

    Usage:
       app = webapp.WSGIApplication([
         ('/index', MyIndexHandler),
         ...,
         (decorator.callback_path, decorator.callback_handler())
       ])

    Returns:
      A webapp.RequestHandler that handles the redirect back from the
      server during the OAuth 2.0 dance.
    """
    decorator = self

    class OAuth2Handler(webapp.RequestHandler):
      """Handler for the redirect_uri of the OAuth 2.0 dance."""

      @login_required
      def get(self):
        error = self.request.get('error')
        if error:
          errormsg = self.request.get('error_description', error)
          self.response.out.write(
              'The authorization request failed: %s' % _safe_html(errormsg))
        else:
          user = users.get_current_user()
          decorator._create_flow(self)
          credentials = decorator.flow.step2_exchange(self.request.params)
          decorator._storage_class(
              decorator._credentials_class, None,
              decorator._credentials_property_name, user=user).put(credentials)
          redirect_uri = _parse_state_value(str(self.request.get('state')),
                                            user)

          if decorator._token_response_param and credentials.token_response:
            resp_json = simplejson.dumps(credentials.token_response)
            redirect_uri = util._add_query_parameter(
                redirect_uri, decorator._token_response_param, resp_json)

          self.redirect(redirect_uri)

    return OAuth2Handler 
Example 40
Project: SurfaceWaterTool   Author: Servir-Mekong   File: appengine.py    GNU General Public License v3.0 4 votes vote down vote up
def callback_handler(self):
    """RequestHandler for the OAuth 2.0 redirect callback.

    Usage:
       app = webapp.WSGIApplication([
         ('/index', MyIndexHandler),
         ...,
         (decorator.callback_path, decorator.callback_handler())
       ])

    Returns:
      A webapp.RequestHandler that handles the redirect back from the
      server during the OAuth 2.0 dance.
    """
    decorator = self

    class OAuth2Handler(webapp.RequestHandler):
      """Handler for the redirect_uri of the OAuth 2.0 dance."""

      @login_required
      def get(self):
        error = self.request.get('error')
        if error:
          errormsg = self.request.get('error_description', error)
          self.response.out.write(
              'The authorization request failed: %s' % _safe_html(errormsg))
        else:
          user = users.get_current_user()
          decorator._create_flow(self)
          credentials = decorator.flow.step2_exchange(self.request.params)
          decorator._storage_class(
              decorator._credentials_class, None,
              decorator._credentials_property_name, user=user).put(credentials)
          redirect_uri = _parse_state_value(str(self.request.get('state')),
                                            user)

          if decorator._token_response_param and credentials.token_response:
            resp_json = json.dumps(credentials.token_response)
            redirect_uri = util._add_query_parameter(
                redirect_uri, decorator._token_response_param, resp_json)

          self.redirect(redirect_uri)

    return OAuth2Handler 
Example 41
Project: yumstat   Author: RKD314   File: appengine.py    MIT License 4 votes vote down vote up
def callback_handler(self):
    """RequestHandler for the OAuth 2.0 redirect callback.

    Usage:
       app = webapp.WSGIApplication([
         ('/index', MyIndexHandler),
         ...,
         (decorator.callback_path, decorator.callback_handler())
       ])

    Returns:
      A webapp.RequestHandler that handles the redirect back from the
      server during the OAuth 2.0 dance.
    """
    decorator = self

    class OAuth2Handler(webapp.RequestHandler):
      """Handler for the redirect_uri of the OAuth 2.0 dance."""

      @login_required
      def get(self):
        error = self.request.get('error')
        if error:
          errormsg = self.request.get('error_description', error)
          self.response.out.write(
              'The authorization request failed: %s' % _safe_html(errormsg))
        else:
          user = users.get_current_user()
          decorator._create_flow(self)
          credentials = decorator.flow.step2_exchange(self.request.params)
          decorator._storage_class(
              decorator._credentials_class, None,
              decorator._credentials_property_name, user=user).put(credentials)
          redirect_uri = _parse_state_value(str(self.request.get('state')),
                                            user)

          if decorator._token_response_param and credentials.token_response:
            resp_json = simplejson.dumps(credentials.token_response)
            redirect_uri = util._add_query_parameter(
                redirect_uri, decorator._token_response_param, resp_json)

          self.redirect(redirect_uri)

    return OAuth2Handler 
Example 42
Project: yumstat   Author: RKD314   File: appengine.py    MIT License 4 votes vote down vote up
def callback_handler(self):
    """RequestHandler for the OAuth 2.0 redirect callback.

    Usage:
       app = webapp.WSGIApplication([
         ('/index', MyIndexHandler),
         ...,
         (decorator.callback_path, decorator.callback_handler())
       ])

    Returns:
      A webapp.RequestHandler that handles the redirect back from the
      server during the OAuth 2.0 dance.
    """
    decorator = self

    class OAuth2Handler(webapp.RequestHandler):
      """Handler for the redirect_uri of the OAuth 2.0 dance."""

      @login_required
      def get(self):
        error = self.request.get('error')
        if error:
          errormsg = self.request.get('error_description', error)
          self.response.out.write(
              'The authorization request failed: %s' % _safe_html(errormsg))
        else:
          user = users.get_current_user()
          decorator._create_flow(self)
          credentials = decorator.flow.step2_exchange(self.request.params)
          decorator._storage_class(
              decorator._credentials_class, None,
              decorator._credentials_property_name, user=user).put(credentials)
          redirect_uri = _parse_state_value(str(self.request.get('state')),
                                            user)

          if decorator._token_response_param and credentials.token_response:
            resp_json = simplejson.dumps(credentials.token_response)
            redirect_uri = util._add_query_parameter(
                redirect_uri, decorator._token_response_param, resp_json)

          self.redirect(redirect_uri)

    return OAuth2Handler