changeset 4144:0a62a439d81b

Trying to port some of RequestBase.__init__ to a WSGI app (very crude right now)
author Florian Krupicka <florian.krupicka@googlemail.com>
date Tue, 03 Jun 2008 11:56:29 +0200
parents 917970e17b73
children 5bd2da7053a3
files MoinMoin/session.py MoinMoin/web/contexts.py MoinMoin/web/utils.py MoinMoin/wsgiapp.py
diffstat 4 files changed, 177 insertions(+), 8 deletions(-) [+]
line wrap: on
line diff
--- a/MoinMoin/session.py	Tue Jun 03 11:54:35 2008 +0200
+++ b/MoinMoin/session.py	Tue Jun 03 11:56:29 2008 +0200
@@ -338,7 +338,9 @@
     def get(self, request):
         session_name = None
         if request.cookie and self.cookie_name in request.cookie:
-            session_name = request.cookie[self.cookie_name].value
+            session_name = request.cookie[self.cookie_name]
+            if hasattr(session_name, 'value'):
+                session_name = session_name.value
             session_name = ''.join([c for c in session_name
                                     if c in self._SESSION_NAME_CHARS])
             session_name = session_name[:self._SESSION_NAME_LEN]
--- a/MoinMoin/web/contexts.py	Tue Jun 03 11:54:35 2008 +0200
+++ b/MoinMoin/web/contexts.py	Tue Jun 03 11:56:29 2008 +0200
@@ -8,9 +8,9 @@
     @license: GNU GPL, see COPYING for details.
 """
 
-import re
+import re, time
 
-from werkzeug.utils import Headers
+from werkzeug.utils import Headers, http_date
 
 from MoinMoin.request import RequestBase
 from MoinMoin.web.request import Request
@@ -33,14 +33,20 @@
     """
     def __init__(self, environ):
         self._wsgirequest = Request(environ)
+        self.environ = environ
         self.__output = []
         self.headers = Headers()
 
         self.status = 200
-        self.failed = 0
 
-        self._setup_vars_from_std_env(environ)
-        RequestBase.__init__(self, {})
+        # compat properties (remove when not necessary anymore)
+        self._auth_redirected = False
+        self.forbidden = 0
+        self._cache_disabled = 0
+        self.page = None
+        self.user_headers = []
+        self.sent_headers = None
+        self.writestack = []
 
     # implementation of methods expected by RequestBase
     def read(self, n=None):
@@ -63,7 +69,6 @@
         return ''.join(self.__output)
 
     def _emit_http_headers(self, headers):
-        logging.info("_emit_http_headers called on HTTPContext")
         st_header, other_headers = headers[0], headers[1:]
         status = STATUS_CODE_RE.match(st_header)
         status = int(status.groups()[0])
@@ -78,6 +83,58 @@
     def setup_args(self):
         return self._wsgirequest.values.to_dict(flat=False)
 
+    def __getattr__(self, name):
+        logging.debug("Proxying to '%r' for attribute '%s'",
+                      self._wsgirequest, name)
+        return getattr(self._wsgirequest, name)
+
+    def __setattr__(self, name, value):
+        logging.debug("Setting attribute '%s' to value '%r'", name, value)
+        self.__dict__[name] = value
+    
+    # compatibility wrapping
+    cookie = Request.cookies
+    script_name = Request.script_root
+    request_method = Request.method
+    path_info = Request.path
+
+    def setHttpHeader(self, header):
+        header, value = header.split(':', 1)
+        self.headers.add(header, value)
+
+    def disableHttpCaching(self, level=1):
+        if level <= self._cache_disabled:
+            return
+        
+        if level == 1:
+            self.headers.add('Cache-Control', 'private, must-revalidate, mag-age=10')
+        elif level == 2:
+            self.headers.add('Cache-Control', 'no-cache')
+            self.headers.set('Pragma', 'no-cache')
+
+        if not self._cache_disabled:
+            when = time.time() - (3600 * 24 * 365)
+            self.headers.set('Expires', http_date(when))
+
+        self._cache_disabled = level
+
+    def _get_dicts(self):
+        if not hasattr(self, '_dicts'):
+            from MoinMoin import wikidicts
+            dicts = wikidicts.GroupDict(self)
+            dicts.load_dicts()
+            self._dicts = dicts
+        return self._dicts
+
+    def _del_dicts(self):
+        del self._dicts
+
+    dicts = property(_get_dicts, None, _del_dicts)
+    del _get_dicts, _del_dicts
+
+    def finish(self):
+        pass
+
 # mangle in logging of function calls
 import inspect
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MoinMoin/web/utils.py	Tue Jun 03 11:56:29 2008 +0200
@@ -0,0 +1,25 @@
+# -*- coding: iso-8859-1 -*-
+"""
+    MoinMoin - Utility functions for the web-layer
+
+    @copyright: 2003-2008 MoinMoin:ThomasWaldmann,
+                2008-2008 MoinMoin:FlorianKrupicka
+    @license: GNU GPL, see COPYING for details.
+"""
+from MoinMoin import log
+logging = log.getLogger(__name__)
+
+def check_spider(useragent, cfg):
+    """ Simple check if useragent is a spider bot
+    
+    @param useragent: werkzeug.useragents.UserAgent
+    @param cfg: wikiconfig instance
+    """
+    is_spider = False
+    if useragent and cfg.cache.ua_spiders:
+        is_spider = cfg.cache.ua_spiders.search(str(useragent)) is not None
+    return is_spider
+
+def handle_auth_form(user_obj):
+    logging.warning("handle_auth_form needs to be implemented yet.")
+    return user_obj
--- a/MoinMoin/wsgiapp.py	Tue Jun 03 11:54:35 2008 +0200
+++ b/MoinMoin/wsgiapp.py	Tue Jun 03 11:56:29 2008 +0200
@@ -2,18 +2,103 @@
 """
     MoinMoin - WSGI application
 
-
     @copyright: 2003-2008 MoinMoin:ThomasWaldmann,
                 2008-2008 MoinMoin:FlorianKrupicka
     @license: GNU GPL, see COPYING for details.
 """
 from werkzeug.utils import responder
 from werkzeug.wrappers import Response
+from werkzeug.exceptions import NotFound
 
 from MoinMoin.web.contexts import HTTPContext
+from MoinMoin.web.utils import check_spider, handle_auth_form
+
+from MoinMoin.Page import Page
+from MoinMoin import config, wikiutil, user, caching, error
+from MoinMoin.action import get_names, get_available_actions
+from MoinMoin.config import multiconfig
+from MoinMoin.support.python_compatibility import set
+from MoinMoin.util import IsWin9x
+from MoinMoin.util.clock import Clock
+from MoinMoin import auth
+
+def _request_init(request):
+    request.clock = Clock()
+    request.clock.start('total')
+    request.clock.start('base__init__')
+
+    try:
+        request.clock.start('load_multi_cfg')
+        request.cfg = multiconfig.getConfig(request.url)
+        request.clock.stop('load_multi_cfg')
+    except error.NoConfigMatchedError:
+        raise NotFound('<p>No wiki configuration matching the URL found!</p>')
+    
+    request.isSpiderAgent = check_spider(request.user_agent, request.cfg)
+    
+    request.action = request.form.get('action', 'show')
+    
+    try:
+        request.rev = int(request.form['rev'])
+    except:
+        request.rev = None
+
+    from MoinMoin.Page import RootPage
+    request.rootpage = RootPage(request)
+
+    from MoinMoin.logfile import editlog
+    request.editlog = editlog.EditLog(request)
+
+    from MoinMoin import i18n
+    request.i18n = i18n
+    i18n.i18n_init(request)
+
+    lang = i18n.requestLanguage(request, try_user=False)
+    request.getText = lambda text, i18n=i18n, request=request, lang=lang, **kw: i18n.getText(text, request, lang, **kw)
+    
+    user_obj = request.cfg.session_handler.start(request, request.cfg.session_id_handler)
+    
+    request.user = None
+    request.user = handle_auth_form(user_obj)
+
+    request.cfg.session_handler.after_auth(request, request.cfg.session_id_handler, request.user)
+
+    if not request.user:
+        request.user = user.User(request, auth_method='request:invalid')
+
+    if 'setuid' in request.session and request.user.isSuperUser():
+        request._setuid_real_user = request.user
+        uid = request.session['setuid']
+        request.user = user.User(request, uid, auth_method='setuid')
+        request.user.valid = True
+
+    if request.action != 'xmlrpc':
+        if not request.forbidden and request.isForbidden():
+            raise Forbidden()
+        if not request.forbidden and request.surge_protect():
+            raise SurgeProtection(retry_after=request.cfg.surge_lockout_time)
+
+    request.pragma = {}
+    request.mode_getpagelinks = 0 # is > 0 as long as we are in a getPageLinks call
+    request.parsePageLinks_running = {} # avoid infinite recursion by remembering what we are already running
+
+    request.lang = i18n.requestLanguage(request)
+            # Language for content. Page content should use the wiki default lang,
+            # but generated content like search results should use the user language.
+    request.content_lang = request.cfg.language_default
+    request.getText = lambda text, i18n=request.i18n, request=request, lang=request.lang, **kv: i18n.getText(text, request, lang, **kv)
+
+    request.reset()
+
+    from MoinMoin.formatter.text_html import Formatter
+    request.html_formatter = Formatter(request)
+    request.formatter = request.html_formatter
+
+    request.clock.stop('base__init__')    
 
 def application(environ, start_response):
     request = HTTPContext(environ)
+    _request_init(request)
     request.run()
 
     response = Response(status=request.status,