Ejemplo n.º 1
0
  def handle_interactive_request(self, environ):
    code = environ['wsgi.input'].read().replace('\r\n', '\n')

    user_environ = self.get_user_environ(environ)
    if 'HTTP_CONTENT_LENGTH' in user_environ:
      del user_environ['HTTP_CONTENT_LENGTH']
    user_environ['REQUEST_METHOD'] = 'GET'
    url = 'http://%s:%s%s?%s' % (user_environ['SERVER_NAME'],
                                 user_environ['SERVER_PORT'],
                                 urllib.quote(environ['PATH_INFO']),
                                 environ['QUERY_STRING'])

    results_io = cStringIO.StringIO()
    old_sys_stdout = sys.stdout

    try:
      error = logservice.LogsBuffer()
      request_environment.current_request.Init(error, user_environ)
      url = urlparse.urlsplit(url)
      environ.update(runtime.CgiDictFromParsedUrl(url))
      sys.stdout = results_io
      try:
        compiled_code = compile(code, '<string>', 'exec')
        exec(compiled_code, self._command_globals)
      except:
        traceback.print_exc(file=results_io)

      return {'error': 0,
              'response_code': 200,
              'headers': [('Content-Type', 'text/plain')],
              'body': results_io.getvalue(),
              'logs': error.parse_logs()}
    finally:
      request_environment.current_request.Clear()
      sys.stdout = old_sys_stdout
def _bootstrap(target, args, kwargs=None):
    """Helper to start a thread."""
    if kwargs is None:
        kwargs = {}
    errors = logservice.LogsBuffer()
    environ = dict(_original_environ)
    if _filtered_environ:
        environ.update(_filtered_environ)
    try:
        request_environment.current_request.Init(errors, environ)
        target(*args, **kwargs)
    finally:
        request_environment.current_request.Reset()
Ejemplo n.º 3
0
def Handle(environ):
  """Handles a background request.

  This function is called by the runtime in response to an /_ah/background
  request.

  Args:
    environ: A dict containing the environ for this request (i.e. for
        os.environ).

  Returns:
    A dict containing:
      error: App Engine error code. 0 if completed successfully, 1 otherwise.
      response_code: The HTTP response code. 200 if completed successfully, 500
          otherwise.
      logs: A list of tuples (timestamp_usec, severity, message) of log
          entries.  timestamp_usec is a long, severity is int and message is
          str.  Severity levels are 0..4 for Debug, Info, Warning, Error,
          Critical.
  """
  error = logservice.LogsBuffer()
  request_environment.current_request.Init(error, environ)
  response = {'error': 0, 'response_code': 200}
  try:
    request_id = environ[BACKGROUND_REQUEST_ID]
    _pending_background_threads.RunBackgroundThread(request_id)
    return response

  except:
    exception = sys.exc_info()


    tb = exception[2].tb_next
    if tb:
      tb = tb.tb_next
    message = ''.join(traceback.format_exception(exception[0], exception[1],
                                                 tb))
    logging.error(message)
    response['response_code'] = 500
    response['error'] = 1
    return response
  finally:
    request_environment.current_request.Clear()
    response['logs'] = error.parse_logs()
Ejemplo n.º 4
0
def Handle(environ):
    """Handles a shutdown request.

  Args:
    environ: A dict containing the environ for this request (i.e. for
        os.environ).

  Returns:
    A tuple with:
      A dict containing:
        error: App Engine error code. Always 0 for OK.
        response_code: The HTTP response code. Always 200.
        logs: A list of tuples (timestamp_usec, severity, message) of log
            entries.  timestamp_usec is a long, severity is int and message is
            str.  Severity levels are 0..4 for Debug, Info, Warning, Error,
            Critical.
      A tuple containing the result of sys.exc_info() if an exception occured,
      or None.
  """
    response = {}
    response['error'] = 0
    response['response_code'] = 200
    exc = None
    try:
        error = logservice.LogsBuffer()
        request_environment.current_request.Init(error, environ)
        getattr(runtime_api, '__BeginShutdown')()
    except:
        exc = sys.exc_info()
        message = ''.join(
            traceback.format_exception(exc[0], exc[1], exc[2].tb_next))
        logging.info('Raised exception in shutdown handler:\n' + message)
    finally:
        request_environment.current_request.Clear()
        response['logs'] = error.parse_logs()
        return (response, exc)
Ejemplo n.º 5
0
def HandleRequest(environ,
                  handler_name,
                  url,
                  post_data,
                  application_root,
                  python_lib,
                  import_hook=None):
    """Handles a single request.

  Handles a single request for handler_name by dispatching to the appropriate
  server interface implementation (CGI or WSGI) depending on the form of
  handler_name. The arguments are processed to fill url and post-data related
  environ members.

  Args:
    environ: A dict containing the environ for this request (i.e. for
        os.environ).
    handler_name: A str containing the user-specified handler to use for this
        request, i.e. the script parameter for a handler in app.yaml; e.g.
        'package.module.application' for a WSGI handler or 'path/to/handler.py'
        for a CGI handler.
    url: The requested url.
    post_data: The post data for this request.
    application_root: A str containing the root path of the application.
    python_lib: A str containing the root the Python App Engine library.
    import_hook: Optional import hook (PEP 302 style loader).

  Returns:
    A dict containing:
      error: App Engine error code. 0 for OK, 1 for error.
      response_code: The HTTP response code.
      headers: A list of str tuples (key, value) of HTTP headers.
      body: A str of the body of the response
      logs: A list of tuples (timestamp_usec, severity, message) of log entries.
          timestamp_usec is a long, severity is int and message is str. Severity
          levels are 0..4 for Debug, Info, Warning, Error, Critical.
      stats: A list of strings, for internal stats collection.
  """
    try:
        error = logservice.LogsBuffer()
        runtime_stats = {
            'ssl_cert_verify_result': {},
        }
        request_environment.current_request.Init(error, environ, runtime_stats)
        url = urlparse.urlsplit(url)
        environ.update(CgiDictFromParsedUrl(url))
        if post_data:

            environ['CONTENT_LENGTH'] = str(len(post_data))
            if 'HTTP_CONTENT_TYPE' in environ:
                environ['CONTENT_TYPE'] = environ['HTTP_CONTENT_TYPE']
            else:
                environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
        post_data = cStringIO.StringIO(post_data)

        if '/' in handler_name or handler_name.endswith('.py'):
            response = cgi.HandleRequest(environ, handler_name, url, post_data,
                                         error, application_root, python_lib,
                                         import_hook)
        else:
            response = wsgi.HandleRequest(environ, handler_name, url,
                                          post_data, error)
        response['logs'] = error.parse_logs()
        response['runtime_stats'] = (
            request_environment.current_request.runtime_stats)
        return response
    finally:
        request_environment.current_request.Clear()