def webapp_add_wsgi_middleware(app):
    initialize_global_vars()
    from google.appengine.ext.appstats import recording
    app = recording.appstats_wsgi_middleware(app)
    cookie_key = "XjDzoCInuFhX1Jt3ZrSSNPQlu6rHLPJUe5DIeujJzZQwQRm7ZRPyOdQZoFzSi5y6CGOprcXgRCaXjDdHnl2RXOVak6fMyk6WJmJ8j9wayI8JoNznIGw7md9XurD7DheB"
    app = SessionMiddleware(app, cookie_key=cookie_key)
    return app
示例#2
0
def webapp_add_wsgi_middleware(app):
	# apply session middleware
	key = "'\\x15\\xbb\\x04]\\x87z\\x19\\xe5\\xb6(\\x19\\xc8c:I\\x83t\\xfbw\\ti\\x1c^`\\xa4\\x05\\x16\\x7f\\xce\\xff\\x98\\xac-vDj{x~\\xa9V\\x07\\x1e\\xebG\\x82\\xc4\\xef\\x0f\\xdd\\xc6\\xb0O!\\r\\xcf\\xd4\\xbb\\xb3^\\x16\\n\\x1a@'"
	app = SessionMiddleware(app, cookie_key=key, cookie_only_threshold=0)
	# apply appstats middleware
	app = recording.appstats_wsgi_middleware(app)
	return app
示例#3
0
def webapp_add_wsgi_middleware(app):
    from google.appengine.ext.appstats import recording
    app = recording.appstats_wsgi_middleware(app)

    app = BlockingMiddleware(app)

    return app
def webapp_add_wsgi_middleware(app):
	from google.appengine.ext.appstats import recording
	app = recording.appstats_wsgi_middleware(app)
    # To generate the cookie_key below, run the following:
    # ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits + "!@#$%^&*()-=+_[]}{;:'/.,<>?") for x in range(100))
	app = SessionMiddleware(app, cookie_key="!LHa-PU;Jtaitvd1#EXmKmDhP}Z43CXDNf3:qizp!O}Vzv['LU:P<f*UF]ro.wA10<qZ&1JIcW{Pgp&v{TPJ8eH.qI,0+P2?3=Tf")
	return app
def webapp_add_wsgi_middleware(app):
    """Enable AppStats if requested."""
    if gcb_appstats_enabled():
        logging.info('Enabling AppStats.')
        from google.appengine.ext.appstats import recording
        app = recording.appstats_wsgi_middleware(app)
    return app
示例#6
0
def webapp_add_wsgi_middleware(app):
    """
    Middleware for WSGI
    """
    from google.appengine.ext.appstats import recording
    app = recording.appstats_wsgi_middleware(app)
    return app
示例#7
0
文件: main.py 项目: AmirS2/tipfy
def enable_appstats(app):
    """Enables appstats middleware."""
    if debug:
        return

    from google.appengine.ext.appstats.recording import appstats_wsgi_middleware
    app.wsgi_app = appstats_wsgi_middleware(app.wsgi_app)
示例#8
0
    def __init__(self, app, setup_signals=False):
        self.settings_module = os.environ['DJANGO_SETTINGS_MODULE']

        from djangoappengine.boot import setup_env
        setup_env()

        from django.conf import settings

        if setup_signals:
            # Load all models.py to ensure signal handling installation or index
            # loading of some apps.
            for app_to_import in settings.INSTALLED_APPS:
                try:
                    import_module('%s.models' % app_to_import)
                except ImportError:
                    pass

        ## In vanilla Django, staticfiles overrides runserver to use StaticFilesHandler
        ## if necessary. As we can't do this in our runserver (because we handover to dev_appserver)
        ## this has to be done here
        if (not on_production_server and settings.DEBUG) and 'django.contrib.staticfiles' in settings.INSTALLED_APPS:
            from django.contrib.staticfiles.handlers import StaticFilesHandler
            app = StaticFilesHandler(app)

        if getattr(settings, 'ENABLE_APPSTATS', False):
            from google.appengine.ext.appstats.recording import \
                appstats_wsgi_middleware
            app = appstats_wsgi_middleware(app)

        self.wrapped_app = app
示例#9
0
def enable_appstats(app):

    """ Utility function that enables appstats middleware."""

    from google.appengine.ext.appstats.recording import appstats_wsgi_middleware
    app.app = appstats_wsgi_middleware(app.app)
    return app
示例#10
0
def webapp_add_wsgi_middleware(app):
    """Called with each WSGI handler initialisation """
    app = SessionMiddleware(app, cookie_key=COOKIE_KEY)
    # For profiling:
    from google.appengine.ext.appstats import recording

    app = recording.appstats_wsgi_middleware(app)
    return app
示例#11
0
def main():
    app = webapp.WSGIApplication([
        ('/tag/(.+)', TagHandler),
        ],
        debug=False)
    app = SessionMiddleware(app, cookie_key='-\x9e}f\xd0h\x8fn\x83\x9a\xef\xf2\x13c\x15\x9cZk\x1f\x1d.Z\x02\xec\x8d)\xb9\r,\xb3\x90mG\x1a\xe2z\x9d\xb8\xd8d\xb6\x1a\xce\x81\x12\x89\xbdT\xf0c\x0e\x13N\xff\xfd\x9d\xc5\x87\xcd\xa3\xb6Y\xd6\x8f')
    app = recording.appstats_wsgi_middleware(app)
    run_wsgi_app(app)
def enable_appstats(app):
  '''Utility function that enables appstats middleware.'''
  try:
    from google.appengine.ext.appstats.recording import appstats_wsgi_middleware
    app.app = appstats_wsgi_middleware(app.app)
  except Exception, e:
    logging.error(
      'Failed to initialize AppStats. Exception encountered: "' + str(e) + '".')
示例#13
0
def main():
	# create app
	app = webapp.WSGIApplication([('/tasks/ping/(.*)', PingWorker),
								('/tasks/twit/(.*)', TwitterWorker)])
	# instrument app for appstats
	app = recording.appstats_wsgi_middleware(app)
	# run the app
	run_wsgi_app(app)
示例#14
0
def webapp_add_wsgi_middleware(app):

    ''' Add appstats profiling middleware. '''

    if config.get('apptools.system', {}).get('hooks', {}).get('appstats', {}).get('enabled', False) == True:
        from google.appengine.ext.appstats import recording
        app = recording.appstats_wsgi_middleware(app)
    return app
示例#15
0
def webapp_add_wsgi_middleware(app):
    app = SessionMiddleware(app, cookie_key=settings.COOKIE_KEY)
    
    if settings.DEBUG:
      # load profiling tool
      from google.appengine.ext.appstats import recording
      app = recording.appstats_wsgi_middleware(app)
    
    return app
示例#16
0
    def pre_run_app(self, app):
        """Wraps the application by by AppEngine's appstats

        :param app:
            The ``WSGIApplication`` instance.
        :return:
            The application, wrapped or not.
        """
        return appstats_wsgi_middleware(app)
示例#17
0
def webapp_add_wsgi_middleware(app):
    """
    Records statistics about each web request.

    @see: https://developers.google.com/appengine/docs/python/tools/appstats
    """
    from google.appengine.ext.appstats import recording
    app = recording.appstats_wsgi_middleware(app)
    return app
示例#18
0
def webapp_add_wsgi_middleware(app):
    from google.appengine.ext.appstats import recording
    app = recording.appstats_wsgi_middleware(app)

    # cookie key was generated using os.random(64)
    # as per documentation recommendation
    app = SessionMiddleware(app, 
                            cookie_key="\xef\xcd\xa50\xee3\x06_\x8e\xaa\xa2\xd5G\x98\xa9\x89\xf1\xe5\x18\x8fJ\xa1-\x939\xb2\x1b\x7fe\xf5\xc0\xfc`C\xd2\xc0\xe0vN\x03\x83\xfe`\xa5\x94\xfe\xf0P\xf1p,\xdcc\xael\xf9\xb2V\x83-\xb3\xb0\x16\xc1")
    return app
def webapp_add_wsgi_middleware(app):
    from google.appengine.ext.appstats import recording
    app = recording.appstats_wsgi_middleware(app)

    from lib.secret_keys import SESSION_KEY
    from lib.gaesessions import SessionMiddleware
    app = SessionMiddleware(app, cookie_key=SESSION_KEY)

    return app
示例#20
0
def webapp_add_wsgi_middleware(app):
    """Enable AppStats if requested."""
    if gcb_appstats_enabled():
        logging.info('Enabling AppStats.')
        # pylint: disable-msg=g-import-not-at-top
        from google.appengine.ext.appstats import recording
        # pylint: enable-msg=g-import-not-at-top
        app = recording.appstats_wsgi_middleware(app)
    return app
示例#21
0
def webapp_add_wsgi_middleware(app):

  #Does this get called too often?
  #while delete_expired_sessions() is False:
    #pass

  from google.appengine.ext.appstats import recording
  app = SessionMiddleware(app, cookie_key=SESSION_COOKIE_KEY)
  app = recording.appstats_wsgi_middleware(app)
  return app
def webapp_add_wsgi_middleware(wsgi_app):
  from google.appengine.ext.appstats import recording
  wsgi_app = recording.appstats_wsgi_middleware(wsgi_app)
  try:
    import datastore_stats
    wsgi_app = datastore_stats.datastore_stats_wsgi_middleware(wsgi_app)
  except:
    logging.exception('No DS Stats module')
    pass
  return wsgi_app
示例#23
0
def add_wsgi_middleware(app):
    """
    Enables appstats

    :param app: application object
    :return: returns the application object
    """

    from google.appengine.ext.appstats import recording
    app.wsgi_app = recording.appstats_wsgi_middleware(app.wsgi_app)
    return app
示例#24
0
def webapp_add_wsgi_middleware(app):
    # Monkey patch that disables AppStats logging
    from google.appengine.ext.appstats import recording
    def save(self):
        try:        
            self._save()      
        except Exception:
            pass
    recording.Recorder.save = save
    app = recording.appstats_wsgi_middleware(app)
    return app
def webapp_add_wsgi_middleware(app):
    import settings
    from google.appengine.ext.appstats import recording
    from gaesessions import SessionMiddleware

    app = SessionMiddleware(app,
         cookie_key=settings.SESSION_COOKIE_KEY,
         cookie_only_threshold=0, #we cannot use cookies as session is used by ios apps as well
         lifetime=settings.SESSION_LIFETIME)
    if settings.APPSTATS_ENABLED:
        app = recording.appstats_wsgi_middleware(app)
    return app
示例#26
0
def webapp_add_wsgi_middleware(app):
    from google.appengine.ext.appstats import recording
    app = SessionMiddleware(app, cookie_key=";lkjascvpoiuzxclvkjswd:LKJHLKJHPoiu;lkj32453456lkjhkjwdhfgsdfggfdse",lifetime=datetime.timedelta(365))

    from google.appengine.ext.appstats import recording
    app = recording.appstats_wsgi_middleware(app)

    # Add the following
    from gae_bingo.middleware import GAEBingoWSGIMiddleware
    app = GAEBingoWSGIMiddleware(app)

    return app
示例#27
0
文件: appstats.py 项目: ac001/x-hands
    def post_make_app(self, app):
        """Wraps the application by by AppEngine's appstats

        :param app:
            The ``WSGIApplication`` instance.
        :return:
            The application, wrapped or not.
        """
        # Wrap the callable, so we keep a reference to the app...
        app.wsgi_app = appstats_wsgi_middleware(app.wsgi_app)
        # ...and return the original app.
        return app
示例#28
0
def run(project_dir, appstats=True, debug=None):
    # auto detect environment (development or production)
    if debug is None:
        debug = development_env()
    COOKIE_KEY = 'my_private_key_used_for_this_application_%s' % get_application_id()
    if development_env(): # always reload configuration
        app = WSGIApplication(project_dir, debug)
    else:
        app = WSGIApplication.active_instance or WSGIApplication(project_dir, debug)
    app = SessionMiddleware(app, cookie_key=COOKIE_KEY, cookie_only_threshold=0)
    if appstats:
        app = recording.appstats_wsgi_middleware(app)
    run_wsgi_app(app)
def _add_appengine_stats(wsgi_app):
  """Adds middleware to capture stats via AppStats.

  You should enable AppStats by setting "appstats: on" under builtins in
  app.yaml.
  """
  try:
    from google.appengine.ext.appstats import recording
  except ImportError:
    pass
  else:
    wsgi_app = recording.appstats_wsgi_middleware(wsgi_app)
  return wsgi_app
示例#30
0
def webapp_add_wsgi_middleware(app):
  """Configure additional middlewares for webapp.

  This function is called automatically by webapp.util.run_wsgi_app
  to give the opportunity for an application to register additional
  wsgi middleware components.

  See http://http://code.google.com/appengine/docs/python/tools/appstats.html
  for more information about configuring and running appstats.
  """
  from google.appengine.ext.appstats import recording
  app = recording.appstats_wsgi_middleware(app)
  return app
示例#31
0
    def wrap(self, app):
        """Wrap and return a WSGI application with appstats recording enabled.

        Args:
            app: existing WSGI application to be wrapped
        Returns:
            new WSGI application that will run the original app with appstats
                enabled.
        """
        def wrapped_appstats_app(environ, start_response):
            # Use this wrapper to grab the app stats recorder for RequestStats.save()
            if recording.recorder_proxy.has_recorder_for_current_request():
                self.recorder = recording.recorder_proxy.get_for_current_request(
                )
            return app(environ, start_response)

        return recording.appstats_wsgi_middleware(wrapped_appstats_app)
示例#32
0
def webapp_add_wsgi_middleware(app):  # pragma: no cover
    """Add AppStats recording.

    This also sets the level of appstats log messages to 'debug' by
    monkey-patching. For details, see:

        https://stackoverflow.com/questions/4305243/disable-appstats-logging
    """

    from google.appengine.ext.appstats import recording

    def save(self):
        t0 = time.time()
        with self._lock:
            num_pending = len(self.pending)
        if num_pending:
            logging.warn(
                'Found %d RPC request(s) without matching response '
                '(presumably due to timeouts or other errors)', num_pending)
        self.dump()
        try:
            key, len_part, len_full = self._save()
        except Exception:
            logging.exception('Recorder.save() failed')
            return
        t1 = time.time()
        link = 'http://%s%s/details?time=%s' % (self.env.get(
            'HTTP_HOST',
            ''), recording.config.stats_url, int(self.start_timestamp * 1000))
        logging.debug(
            'Saved; key: %s, part: %s bytes, full: %s bytes, '
            'overhead: %.3f + %.3f; link: %s', key, len_part, len_full,
            self.overhead, t1 - t0, link)

    recording.Recorder.save = save

    app = recording.appstats_wsgi_middleware(app)
    return app
示例#33
0
    def __call__(self, environ, start_response):
        path_info = environ.get("PATH_INFO", "")
        # Never profile calls to the profiler itself to avoid endless recursion.
        should_not_profile = (not config.should_profile(environ)
                              or path_info.startswith("/gae_mini_profiler/")
                              or path_info.startswith('/_ah/stats'))
        if should_not_profile:
            result = self.app(environ, start_response)
            for value in result:
                yield value
            return

        try:
            self._lock.acquire()

            # Start w/ a non-profiled app at the beginning of each request
            self.app = self.app_clean
            self.prof = None
            self.recorder = None
            self.temporary_redirect = False
            self.simple_timing = cookies.get_cookie_value(
                "g-m-p-disabled") == "1"
            requeststore.clear_id()

            # Set a random ID for this request so we can look up stats later
            request_id = requeststore.generate_id()

            # Send request id in headers so jQuery ajax calls can pick
            # up profiles.
            def profiled_start_response(status, headers, exc_info=None):

                if status.startswith("302 "):
                    # Temporary redirect. Add request identifier to redirect location
                    # so next rendered page can show this request's profile.
                    headers = ProfilerWSGIMiddleware.headers_with_modified_redirect(
                        environ, headers)
                    self.temporary_redirect = True

                # Append headers used when displaying profiler results from ajax requests
                headers.append(("X-MiniProfiler-Id", request_id))
                headers.append(
                    ("X-MiniProfiler-QS", environ.get("QUERY_STRING")))

                return start_response(status, headers, exc_info)

            if self.simple_timing:

                # Detailed recording is disabled. Just track simple start/stop time.
                self.start = time.clock()

                result = self.app(environ, profiled_start_response)
                for value in result:
                    yield value

                self.end = time.clock()

            else:

                # Add logging handler
                self.add_handler()

                # Configure AppStats output, keeping a high level of request
                # content so we can detect dupe RPCs more accurately
                from google.appengine.ext.appstats import recording
                recording.config.MAX_REPR = 750

                # Turn on AppStats monitoring for this request
                old_app = self.app

                def wrapped_appstats_app(environ, start_response):
                    # Use this wrapper to grab the app stats recorder for RequestStats.save()

                    if recording.recorder_proxy.has_recorder_for_current_request(
                    ):
                        self.recorder = recording.recorder_proxy.get_for_current_request(
                        )

                    return old_app(environ, start_response)

                self.app = recording.appstats_wsgi_middleware(
                    wrapped_appstats_app)

                # Turn on cProfile profiling for this request
                import cProfile
                self.prof = cProfile.Profile()

                # Get profiled wsgi result
                result = self.prof.runcall(
                    lambda *args, **kwargs: self.app(
                        environ, profiled_start_response), None, None)

                # If we're dealing w/ a generator, profile all of the .next calls as well
                if type(result) == GeneratorType:

                    while True:
                        try:
                            yield self.prof.runcall(result.next)
                        except StopIteration:
                            break

                else:
                    for value in result:
                        yield value

                self.logs = self.get_logs(self.handler)
                logging.getLogger().removeHandler(self.handler)
                self.handler.stream.close()
                self.handler = None

            # Store stats for later access
            RequestStats(request_id, environ, self).store()
            admins = config.email_profile_results_to(environ)
            if admins:
                version = environ.get("CURRENT_VERSION_ID").split('.')[0]
                app_id = app_identity.get_application_id()
                path_info = environ.get("PATH_INFO", "")
                mail.send_mail(
                    'profiles@%s.appspotmail.com' % app_id, admins,
                    'Profile for %s' % path_info,
                    'Go to https://%s-dot-%s.appspot.com/gae_mini_profiler/shared?request_id=%s'
                    % (version, app_id, request_id))

            # Just in case we're using up memory in the recorder and profiler
            self.recorder = None
            self.prof = None
            requeststore.clear_id()

        finally:
            self._lock.release()
示例#34
0
if 'SERVER_SOFTWARE' in os.environ and os.environ[
        'SERVER_SOFTWARE'].startswith('Dev'):
    # use our debug.utils with Jinja2 templates
    import debug.utils
    sys.modules['werkzeug.debug.utils'] = debug.utils

    # don't use inspect.getsourcefile because the imp module is empty
    import inspect
    inspect.getsourcefile = inspect.getfile

    # wrap the application
    from werkzeug import DebuggedApplication
    app = DebuggedApplication(app, evalex=True)

CGIHandler().run(recording.appstats_wsgi_middleware(app))

########NEW FILE########
__FILENAME__ = decorators
# coding: UTF-8

from flask import g
from flask import redirect
from flask import url_for

from functools import wraps

from werkzeug.contrib.cache import GAEMemcachedCache
cache = GAEMemcachedCache()

示例#35
0
def webapp_add_wsgi_middleware(app):
    from google.appengine.ext.appstats import recording
    app = SessionMiddleware(app, cookie_key=COOKIE_KEY)
    app = recording.appstats_wsgi_middleware(app)
    return app
def webapp_add_wsgi_middleware(app):
    if settings.RUN_APP_STATS:
        from google.appengine.ext.appstats import recording
        app = recording.appstats_wsgi_middleware(app)
    return app
示例#37
0
def webapp_add_wsgi_middleware(app):
    app = recording.appstats_wsgi_middleware(app)
    return app
示例#38
0
def webapp_add_wsgi_middleware(app):
    """Enable AppStats if requested."""
    if gcb_appstats_enabled():
        from google.appengine.ext.appstats import recording
        app = recording.appstats_wsgi_middleware(app)
    return app
示例#39
0
def webapp_add_wsgi_middleware(app):
  """WSGI middleware configuration."""
  from google.appengine.ext.appstats import recording
  return recording.appstats_wsgi_middleware(app)
示例#40
0
    if num_errors:
        s.seek(0)
        error_text = s.read()
        logging.critical("One or more models did not validate:\n%s" %
                         error_text)
    else:
        logging.info("All models validated.")

if not on_production_server:
    validate_models()

def log_traceback(*args, **kwargs):
    import logging
    logging.exception("Exception in request:")

signals.got_request_exception.connect(log_traceback)

# Create a Django application for WSGI.
application = WSGIHandler()

# Add the staticfiles handler if necessary.
if settings.DEBUG and 'django.contrib.staticfiles' in settings.INSTALLED_APPS:
    from django.contrib.staticfiles.handlers import StaticFilesHandler
    application = StaticFilesHandler(application)

if getattr(settings, 'ENABLE_APPSTATS', False):
    from google.appengine.ext.appstats.recording import \
        appstats_wsgi_middleware
    application = appstats_wsgi_middleware(application)
示例#41
0
def webapp_add_wsgi_middleware(app):
    """Adds support for Appstats, the appengine RPC instrumentation service."""
    app = recording.appstats_wsgi_middleware(app)
    return app
示例#42
0
    def __call__(self, environ, start_response):

        global request_id
        request_id = None

        # Start w/ a non-profiled app at the beginning of each request
        self.app = self.app_clean
        self.prof = None
        self.recorder = None
        self.temporary_redirect = False

        if config.should_profile(environ):

            # Set a random ID for this request so we can look up stats later
            import base64
            import os
            request_id = base64.urlsafe_b64encode(os.urandom(5))

            self.add_handler()

            # Send request id in headers so jQuery ajax calls can pick
            # up profiles.
            def profiled_start_response(status, headers, exc_info=None):

                if status.startswith("302 "):
                    # Temporary redirect. Add request identifier to redirect location
                    # so next rendered page can show this request's profile.
                    headers = ProfilerWSGIMiddleware.headers_with_modified_redirect(
                        environ, headers)
                    self.temporary_redirect = True

                # Append headers used when displaying profiler results from ajax requests
                headers.append(("X-MiniProfiler-Id", request_id))
                headers.append(
                    ("X-MiniProfiler-QS", environ.get("QUERY_STRING")))

                return start_response(status, headers, exc_info)

            # Configure AppStats output, keeping a high level of request
            # content so we can detect dupe RPCs more accurately

            # monkey patch appstats.formatting to fix string quoting bug
            # see http://code.google.com/p/googleappengine/issues/detail?id=5976
            import unformatter.formatting
            import google.appengine.ext.appstats.formatting
            google.appengine.ext.appstats.formatting._format_value = unformatter.formatting._format_value

            from google.appengine.ext.appstats import recording
            recording.config.MAX_REPR = 750

            # Turn on AppStats monitoring for this request
            old_app = self.app

            def wrapped_appstats_app(environ, start_response):
                # Use this wrapper to grab the app stats recorder for RequestStats.save()

                if hasattr(recording.recorder, "get_for_current_request"):
                    self.recorder = recording.recorder.get_for_current_request(
                    )
                else:
                    self.recorder = recording.recorder

                return old_app(environ, start_response)

            self.app = recording.appstats_wsgi_middleware(wrapped_appstats_app)

            # Turn on cProfile profiling for this request
            import cProfile
            self.prof = cProfile.Profile()

            # Get profiled wsgi result
            result = self.prof.runcall(
                lambda *args, **kwargs: self.app(
                    environ, profiled_start_response), None, None)

            self.recorder = recording.recorder

            # If we're dealing w/ a generator, profile all of the .next calls as well
            if type(result) == GeneratorType:

                while True:
                    try:
                        yield self.prof.runcall(result.next)
                    except StopIteration:
                        break

            else:
                for value in result:
                    yield value

            self.logs = self.get_logs(self.handler)
            logging.getLogger().removeHandler(self.handler)
            self.handler.stream.close()
            self.handler = None

            # Store stats for later access
            RequestStats(request_id, environ, self).store()

            # Just in case we're using up memory in the recorder and profiler
            self.recorder = None
            self.prof = None
            request_id = None

        else:
            result = self.app(environ, start_response)
            for value in result:
                yield value
示例#43
0
    def profile_start_response(self, app, environ, start_response):
        """Collect and store statistics for a single request.

        Use this method from middleware in place of the standard
        request-serving pattern. Do:

           profiler = RequestProfiler(...)
           return profiler(app, environ, start_response)

        Instead of:

           return app(environ, start_response)

        Depending on the mode, this method gathers timing information
        and an execution profile and stores them in the datastore for
        later access.
        """

        # Always track simple start/stop time.
        self.start = time.time()

        if self.mode == Mode.SIMPLE:

            # Detailed recording is disabled.
            result = app(environ, start_response)
            for value in result:
                yield value

        else:

            # Add logging handler
            self.add_handler()

            # Monkey patch appstats.formatting to fix string quoting bug
            # See http://code.google.com/p/googleappengine/issues/detail?id=5976
            # TODO(chris): remove. This bug is marked as fixed.
            import unformatter.formatting
            import google.appengine.ext.appstats.formatting
            google.appengine.ext.appstats.formatting._format_value = unformatter.formatting._format_value

            # Configure AppStats output, keeping a high level of request
            # content so we can detect dupe RPCs more accurately
            from google.appengine.ext.appstats import recording
            recording.config.MAX_REPR = 750

            if self.mode != Mode.CPU_ONLY:

                # Turn on AppStats monitoring for this request
                old_app = app
                def wrapped_appstats_app(environ, start_response):
                    # Use this wrapper to grab the app stats recorder for RequestStats.save()

                    if recording.recorder_proxy.has_recorder_for_current_request():
                        self.recorder = recording.recorder_proxy.get_for_current_request()

                    return old_app(environ, start_response)
                app = recording.appstats_wsgi_middleware(wrapped_appstats_app)

            # By default, we create a placeholder wrapper function that
            # simply calls whatever function it is passed as its first
            # argument. This is a placeholder that mimics the signature
            # expected by self.prof.runcall's function wrapper (see below).
            result_fxn_wrapper = lambda fxn, *args: fxn()

            if self.mode != Mode.RPC_ONLY:
                # Turn on cProfile profiling for this request
                import cProfile
                self.prof = cProfile.Profile()

                # Get profiled wsgi results by executing them via
                # prof.runcall.
                result_fxn_wrapper = self.prof.runcall

            # Get wsgi result
            result = result_fxn_wrapper(lambda *args, **kwargs: app(environ, start_response), None, None)

            # If we're dealing w/ a generator, profile all of the .next calls as well
            if type(result) == GeneratorType:

                while True:
                    try:
                        yield result_fxn_wrapper(result.next)
                    except StopIteration:
                        break

            else:
                for value in result:
                    yield value

            self.logs = self.get_logs(self.handler)
            logging.getLogger().removeHandler(self.handler)
            self.handler.stream.close()
            self.handler = None

        self.end = time.time()

        # Store stats for later access
        RequestStats(self.request_id, environ, self).store()
import webapp2
from google.appengine.ext.appstats import recording
from Controllers import Home1

app = recording.appstats_wsgi_middleware(
    webapp2.WSGIApplication([("/", Home1), ("/home", Home1)], debug=True))
示例#45
0
def webapp_add_wsgi_middleware(app):  # pylint: disable-msg=C6409
    from google.appengine.ext.appstats import recording
    return recording.appstats_wsgi_middleware(app)
示例#46
0
def enable_appstats(app):
    """Enables appstats middleware."""
    from google.appengine.ext.appstats.recording import \
        appstats_wsgi_middleware
    app.dispatch = appstats_wsgi_middleware(app.dispatch)
def webapp_add_wsgi_middleware(app):
    from google.appengine.ext.appstats import recording
    app = recording.appstats_wsgi_middleware(app)
    appstats_CALC_RPC_COSTS = True
    return app
示例#48
0
        # Password is not set, or is empty
        #   So we skip authentication
        return True
    secret_key = memcache.get('secret_key')
    if not secret_key:
        secret_key = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(10))
        memcache.add('secret_key', secret_key)
    if request.form.get('password') == PASSWORD:
        session['secret_key'] = secret_key
    if session.get('secret_key') == secret_key:
        return True
    return False


app = Flask(__name__)
app.wsgi_app = recording.appstats_wsgi_middleware(app.wsgi_app)
app.config.from_object(Config)


@app.route('/', methods=['GET', 'POST'])
def home():
    return redirect(url_for("index", path=""))


@app.route('/bucket/', methods=['GET', 'POST'])
def catch_urls():
    """
    Alias for the index function at the root,
    Flask won't let us catch the root dir with the <path> variable
    """
    return index("")
def webapp_add_wsgi_middleware(app):
    from google.appengine.ext.appstats import recording
    app = recording.appstats_wsgi_middleware(app)
    return app
示例#50
0
    def __call__(self, environ, start_response):

        CurrentRequestId.set(None)

        # Never profile calls to the profiler itself to avoid endless recursion.
        if (not config.should_profile() or environ.get(
                "PATH_INFO", "").startswith("/gae_mini_profiler/")):
            app = self.app
            if self.keep_appstats:
                app = recording.appstats_wsgi_middleware(app)
            result = app(environ, start_response)
            for value in result:
                yield value
        else:
            # Set a random ID for this request so we can look up stats later
            import base64
            CurrentRequestId.set(base64.urlsafe_b64encode(os.urandom(5)))
            profile_mode = config.get_mode(environ, cookies)

            # Send request id in headers so jQuery ajax calls can pick
            # up profiles.
            def profiled_start_response(status, headers, exc_info=None):

                if status.startswith("302 "):
                    # Temporary redirect. Add request identifier to redirect location
                    # so next rendered page can show this request's profile.
                    headers = ProfilerWSGIMiddleware.headers_with_modified_redirect(
                        environ, headers)
                    # Access the profiler in closure scope
                    profiler.temporary_redirect = True

                # Append headers used when displaying profiler results from ajax requests
                headers.append(("X-MiniProfiler-Id", CurrentRequestId.get()))
                headers.append(
                    ("X-MiniProfiler-QS", str(environ.get("QUERY_STRING"))))
                headers.append(("Set-Cookie",
                                cookies.set_cookie_value("g-m-p-mode",
                                                         profile_mode,
                                                         path="/")))

                return start_response(status, headers, exc_info)

            # As a simple form of rate-limiting, appstats protects all
            # its work with a memcache lock to ensure that only one
            # appstats request ever runs at a time, across all
            # appengine instances.  (GvR confirmed this is the purpose
            # of the lock).  So our attempt to profile will fail if
            # appstats is running on another instance.  Boo-urns!  We
            # just turn off the lock-checking for us, which means we
            # don't rate-limit quite as much with the mini-profiler as
            # we would do without.
            old_memcache_add = memcache.add
            old_memcache_delete = memcache.delete
            memcache.add = (lambda key, *args, **kwargs:
                            (True if key == recording.lock_key() else
                             old_memcache_add(key, *args, **kwargs)))
            memcache.delete = (lambda key, *args, **kwargs:
                               (True if key == recording.lock_key() else
                                old_memcache_delete(key, *args, **kwargs)))

            try:
                profiler = RequestProfiler(CurrentRequestId.get(),
                                           profile_mode)
                result = profiler.profile_start_response(
                    self.app, environ, profiled_start_response)
                for value in result:
                    yield value
            finally:
                CurrentRequestId.set(None)
                memcache.add = old_memcache_add
                memcache.delete = old_memcache_delete
示例#51
0
def webapp_add_wsgi_middleware(app):
    """Enables appstats middleware."""
    from google.appengine.ext.appstats import recording
    return recording.appstats_wsgi_middleware(app)
示例#52
0
def webapp_add_wsgi_middleware(app):
    """WSGI middleware declaration."""
    from google.appengine.ext.appstats import recording
    app = GaeSessionMiddleware(app, cookie_key=COOKIE_KEY)
    app = recording.appstats_wsgi_middleware(app)
    return app
示例#53
0
def enable_appstats(app):
    """ Utility function that enables appstats middleware."""

    from google.appengine.ext.appstats import recording
    app = recording.appstats_wsgi_middleware(app)
    return app
示例#54
0
def add_appstats(app):
    return recording.appstats_wsgi_middleware(app)
示例#55
0
from ferris import fix_imports
(fix_imports)

# Import the application

import ferris
import ferris.app
import ferris.deferred_app
import ferris.routes
import app.routes
import app.listeners
from ferris.core import settings
(app)

main_app = ferris.app.app  # Main application
deferred_app = ferris.deferred_app.app  # Deferred application

settings.load_settings()
appstats_settings = settings.get('appstats', {})

if (appstats_settings.get('enabled', False)
        and ferris.app.debug) or appstats_settings.get('enabled_live', True):
    from google.appengine.ext.appstats import recording
    main_app = recording.appstats_wsgi_middleware(main_app)
示例#56
0
def webapp_add_wsgi_middleware(app):
    app = SessionMiddleware(app, cookie_key=keys.cookie_key)
    app = recording.appstats_wsgi_middleware(app)
    return app
示例#57
0
def webapp_add_wsgi_middleware(app):
  from google.appengine.ext.appstats import recording
  if ENABLE_PROFILING:
    return recording.appstats_wsgi_middleware(app)
  return app
示例#58
0
def webapp_add_wsgi_middleware(app):
    from google.appengine.ext.appstats import recording
    import gae_mini_profiler.profiler
    app = gae_mini_profiler.profiler.ProfilerWSGIMiddleware(app)
    app = recording.appstats_wsgi_middleware(app)
    return app
示例#59
0
    def __call__(self, environ, start_response):

        global request_id
        request_id = None

        # Start w/ a non-profiled app at the beginning of each request
        self.app = self.app_clean
        self.prof = None
        self.recorder = None

        if config.should_profile(environ):

            # Set a random ID for this request so we can look up stats later
            import base64
            import os
            request_id = base64.urlsafe_b64encode(os.urandom(15))

            # Send request id in headers so jQuery ajax calls can pick
            # up profiles.
            def profiled_start_response(status, headers, exc_info = None):
                headers.append(("X-MiniProfiler-Id", request_id))
                return start_response(status, headers, exc_info)

            # Configure AppStats output, keeping a high level of request
            # content so we can detect dupe RPCs more accurately
            from google.appengine.ext.appstats import recording
            recording.config.MAX_REPR = 750

            # Turn on AppStats monitoring for this request
            old_app = self.app
            def wrapped_appstats_app(environ, start_response):
                # Use this wrapper to grab the app stats recorder for RequestStats.save()
                self.recorder = recording.recorder
                return old_app(environ, start_response)
            self.app = recording.appstats_wsgi_middleware(wrapped_appstats_app)

            # Turn on cProfile profiling for this request
            import cProfile
            self.prof = cProfile.Profile()

            # Get profiled wsgi result
            result = self.prof.runcall(lambda *args, **kwargs: self.app(environ, profiled_start_response), None, None)

            self.recorder = recording.recorder

            # If we're dealing w/ a generator, profile all of the .next calls as well
            if type(result) == GeneratorType:

                while True:
                    try:
                        yield self.prof.runcall(result.next)
                    except StopIteration:
                        break

            else:
                for value in result:
                    yield value

            # Store stats for later access
            RequestStats(request_id, environ, self).store()

            # Just in case we're using up memory in the recorder and profiler
            self.recorder = None
            self.prof = None
            request_id = None

        else:
            result = self.app(environ, start_response)
            for value in result:
                yield value