Example #1
0
    def testInitURLMapping(self):
        """Initializes the url/script map."""

        url_mapping = twistedae.initURLMapping(self.conf)
        for pattern, module, path in url_mapping:
            if pattern.match('/foo'):
                self.assertEqual(module, 'app')
Example #2
0
def serve(conf):
    """Implements the server loop.

    Args:
        conf: The application configuration.
    """

    # Inititalize URL mapping
    url_mapping = twistedae.initURLMapping(conf)

    module_cache = dict()

    while True:
        (inp, out, err, env) = fcgiapp.Accept()

        # Redirect standard input, output and error streams
        sys.stdin = inp
        sys.stdout = out
        sys.stderr = err

        # Initialize application environment
        os_env = dict(os.environ)
        os.environ.clear()
        os.environ.update(env)
        os.environ['APPLICATION_ID'] = conf.application
        os.environ['AUTH_DOMAIN'] = 'localhost'
        os.environ['SERVER_SOFTWARE'] = 'TwistedAE/0.1.0'
        os.environ['TZ'] = 'UTC'

        # Get user info and set the user environment variables
        email, admin, user_id = twistedae.handlers.login.getUserInfo(
            os.environ.get('HTTP_COOKIE', None))
        os.environ['USER_EMAIL'] = email
        if admin:
            os.environ['USER_IS_ADMIN'] = '1'
        os.environ['USER_ID'] = user_id

        # Compute script path and set PATH_TRANSLATED environment variable
        for pattern, name, script in url_mapping:
            if re.match(pattern, os.environ['PATH_INFO']) is not None:
                os.environ['PATH_TRANSLATED'] = script
                break

        try:
            # Lookup module in cache
            if name in module_cache:
                module_cache[name]['main']()
            else:
                # Load and run the application module
                mod = runpy.run_module(name, run_name='__main__')
                # Store module in the cache
                module_cache[name] = mod
        except:
            try:
                tb = get_traceback()
                logging.error(tb)
                print 'Content-Type: text/plain\n'
                print tb
            except IOError:
                # TODO: Check whether it occurs due to a broken FastCGI
                # pipe or if we have some kind of leak
                pass
        finally:
            # Re-redirect standard input, output and error streams
            sys.stdin = sys.__stdin__
            sys.stdout = sys.__stdout__
            sys.stderr = sys.__stderr__

            # Restore original environment
            os.environ.clear()
            os.environ.update(os_env)

            # Finish request
            fcgiapp.Finish()