source: indico/indico/web/wsgi/indico_wsgi_url_parser.py @ a691b3

burotelhello-world-walkthroughipv6v0.98-seriesv0.98.2v0.98.3v0.98b1v0.98b2v0.99v1.0v1.1
Last change on this file since a691b3 was a691b3, checked in by Pedro Ferreira <jose.pedro.ferreira@…>, 3 years ago

[FIX] Several fixes

  • Exception throwing and wording;
  • Added actual config option for UseXSendFile;
  • Real logging instead of prints;
  • Some line breaks added;
  • Property mode set to 100644
File size: 5.5 KB
Line 
1# -*- coding: utf-8 -*-
2##
3##
4## This file is part of CDS Indico.
5## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 CERN.
6##
7## CDS Indico is free software; you can redistribute it and/or
8## modify it under the terms of the GNU General Public License as
9## published by the Free Software Foundation; either version 2 of the
10## License, or (at your option) any later version.
11##
12## CDS Indico is distributed in the hope that it will be useful, but
13## WITHOUT ANY WARRANTY; without even the implied warranty of
14## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15## General Public License for more details.
16##
17## You should have received a copy of the GNU General Public License
18## along with CDS Indico; if not, write to the Free Software Foundation, Inc.,
19## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20"""
21Some apache rewrites managed with mod_wsgi.
22"""
23
24import os
25from MaKaC.common import Config
26from MaKaC.services import handler
27
28DIR_HTDOCS = Config.getInstance().getHtdocsDir()
29DIR_SERVICES = os.path.dirname(handler.__file__)
30
31"""
32urlMapping stores the modules and handlers for every page we want,
33in the form (hash, tuple)
34@hash: matching directory
35@tuple[0]: module, a pair in the form "(containingDir, file)"
36@tuple[1]: handler
37@tuple[2]: preprocessing function (if there's no function, '')
38@tuple[3]: parameters for the preprocessing function (dictionary)
39
40Add pages that need url parsing here.
41"""
42urlMapping = {'':   ((DIR_HTDOCS, 'index.py'), 'index', '', None), \
43    'services':     ((DIR_SERVICES, 'handler.py'), 'handler', '', None), \
44    'event':        ((DIR_HTDOCS, 'events.py'), 'index', 'genericRewrite', \
45                        {'queryReplacement': 'tag'}), \
46    'categ':        ((DIR_HTDOCS, 'categoryDisplay.py'), 'index', 'genericRewrite', \
47                        {'queryReplacement': 'categId'})
48}
49
50def is_static_path(path):
51    """
52    Returns True if path corresponds to an existing file under DIR_HTDOCS.
53    @param path: the path.
54    @type path: string
55    @return: True if path corresponds to an existing file under DIR_HTDOCS.
56    @rtype: bool
57    """
58    path = os.path.abspath(DIR_HTDOCS + path)
59    if path.startswith(DIR_HTDOCS) and os.path.isfile(path):
60        return path
61    return None
62
63def is_mp_legacy_publisher_path(req):
64    """
65    Finds the corresponding module and handler for the path given.
66    Checks path corresponds to an existing Python file under DIR_HTDOCS.
67    @param path: the path.
68    @type path: string
69    @return: the path of the module to load and the function to call there.
70    @rtype: tuple
71    """
72    path = req.URLFields['PATH_INFO'].split('/')
73    startingDir = ''
74    if len(path) > 1:
75        startingDir = path[1]
76
77    # First, we try to assign an existing redirection
78    if urlMapping.has_key(startingDir):
79        module, handler, function, params = urlMapping[startingDir]
80        if callable(getattr(WSGIRedirection, function, None)):
81            rwPage = WSGIRedirection(req, module, handler, startingDir)
82            getattr(rwPage, function)(params)
83        return (os.path.join(module[0], module[1]), handler)
84
85    # Else, we try to find the called module
86    for index, component in enumerate(path):
87        if component.endswith('.py'):
88            possible_module = os.path.abspath(DIR_HTDOCS + os.path.sep + \
89                                              os.path.sep.join(path[:index + 1]))
90            possible_handler = '/'.join(path[index + 1:]).strip()
91            if not possible_handler:
92                possible_handler = 'index'
93            if os.path.exists(possible_module):
94                return (possible_module, possible_handler)
95
96    # If all fails, then we will load a static resource
97    else:
98        return None, None
99
100class WSGIRedirection(object):
101    """
102    Redirections that need a especial treatment are handled through this class.
103    """
104    def __init__(self, req, module, handler, dir):
105        self._dir = dir
106        self._module = module
107        self._handler = handler
108        self._req = req
109        # These two lines locate DIR in the PATH_INFO
110        self._path = self._req.URLFields['PATH_INFO'].split('/')
111        self._index = self._path.index(self._dir)
112
113    def _pathRewrite(self, fileName):
114        """
115        Obtain the web base directory from the PATH_INFO,
116        and then add the module to the path:
117        '/indico/DIR/...' => '/indico' => '/indico/fileName'
118        """
119        newPathInfo = os.path.sep.join(self._path[:self._index]) + fileName
120        self._req.URLFields['PATH_INFO'] = newPathInfo
121
122    def _queryRewrite(self, query):
123        """
124        Rewrites the QUERY_STRING, putting everything after DIR in it
125        Example of URL:
126        http://indico.cern.ch/DIR/index.py?my=messy/short.py?tag=true
127         =>
128        http://indico.cern.ch/fileName?query=index.py?my=messy/short.py?tag=true
129        """
130        newQueryString = query + '='
131        newQueryString += '/'.join(self._path[self._index+1:])
132        if self._req.URLFields['QUERY_STRING']:
133            newQueryString += '?' + self._req.URLFields['QUERY_STRING']
134        self._req.URLFields['QUERY_STRING'] = newQueryString
135
136    # Add the preprocessing functions for rewriting here.
137    def genericRewrite(self, params):
138        """
139        Rewrites a /DIR/ directory tag with queryReplacement
140        Example:
141        http://indico.cern.ch/DIR/108?my=messy/short.py?tag=true
142         =>
143        http://indico.cern.ch/MODULE[1]?queryReplacement=108?my=messy/short.py?tag=true
144        """
145        self._pathRewrite(self._module[1])
146        self._queryRewrite(params['queryReplacement'])
147
Note: See TracBrowser for help on using the repository browser.