# HG changeset patch
# Parent 6663d4056caf4d5a1e79323adf12bc5e93ff735d
# User cboos
fcgi: make it possible to use the installed version of flup instead of builtin version.

The environment varialbe TRAC_USE_FLUP needs to be set to `1` in order to force the use of flup.
If `flup` is used, we need to insert some WSGI middleware in order to deal with URL encoding.

diff -r 6663d4056caf trac/web/fcgi_frontend.py
--- a/trac/web/fcgi_frontend.py	Sat Jul 03 19:43:09 2010 +0200
+++ b/trac/web/fcgi_frontend.py	Thu Jul 15 11:08:41 2010 +0200
@@ -15,15 +15,42 @@
 #
 # Author: Matthew Good <trac@matt-good.net>
 
+import os
 import pkg_resources
+import urllib
 
 from trac import __version__ as VERSION
 from trac.web.main import dispatch_request
 
-import _fcgi
+use_flup = os.environ.get('TRAC_USE_FLUP', False)
+if use_flup in ('0', 'no', 'off'):
+    use_flup = False
+
+
+class FlupMiddleware(object):
+    """Flup doesn't URL unquote the PATH_INFO, so we need to do it."""
+    def __init__(self, application):
+        self.application = application
+
+    def __call__(self, environ, start_response):
+        environ['PATH_INFO'] = urllib.unquote(environ.get('PATH_INFO', ''))
+        return self.application(environ, start_response)
+
+params = {}
+
+if use_flup:
+    try:
+        from flup.server.fcgi import WSGIServer
+        params['maxThreads'] = 15
+        dispatch_request = FlupMiddleware(dispatch_request)
+    except ImportError:
+        use_flup = False
+
+if not use_flup:
+    from _fcgi import WSGIServer
 
 def run():
-    _fcgi.WSGIServer(dispatch_request).run()
+    WSGIServer(dispatch_request, **params).run()
 
 if __name__ == '__main__':
     pkg_resources.require('Trac==%s' % VERSION)
diff -r 6663d4056caf trac/web/standalone.py
--- a/trac/web/standalone.py	Sat Jul 03 19:43:09 2010 +0200
+++ b/trac/web/standalone.py	Thu Jul 15 11:08:41 2010 +0200
@@ -23,7 +23,6 @@
 import os
 import sys
 from SocketServer import ThreadingMixIn
-import urllib
 
 from trac import __version__ as VERSION
 from trac.util import autoreload, daemon
@@ -71,16 +70,6 @@
         return self.application(environ, start_response)
 
 
-class FlupMiddleware(object):
-
-    def __init__(self, application):
-        self.application = application
-
-    def __call__(self, environ, start_response):
-        environ['PATH_INFO'] = urllib.unquote(environ.get('PATH_INFO', ''))
-        return self.application(environ, start_response)
-
-
 class TracEnvironMiddleware(object):
 
     def __init__(self, application, env_parent_dir, env_paths, single_env):
@@ -272,6 +261,7 @@
                                     None, None, ['']).WSGIServer
             flup_app = wsgi_app
             if options.unquote:
+                from trac.web.fcgi_frontend import FlupMiddleware
                 flup_app = FlupMiddleware(flup_app)
             ret = server_cls(flup_app, bindAddress=server_address).run()
             sys.exit(ret and 42 or 0) # if SIGHUP exit with status 42
