1 # -*- coding: utf-8 -*-
7 import werkzeug.routing
10 from openerp.addons.base import ir
11 from openerp.addons.base.ir import ir_qweb
12 from openerp.addons.website.models.website import slug
13 from openerp.http import request
14 from openerp.osv import orm
16 logger = logging.getLogger(__name__)
18 class RequestUID(object):
19 def __init__(self, **kw):
20 self.__dict__.update(kw)
22 class ir_http(orm.AbstractModel):
27 def _get_converters(self):
29 super(ir_http, self)._get_converters(),
35 first_pass = not hasattr(request, 'website')
36 request.website = None
39 func, arguments = self._find_handler()
40 request.website_enabled = func.routing.get('website', False)
41 except werkzeug.exceptions.NotFound:
42 # either we have a language prefixed route, either a real 404
43 # in all cases, website processes them
44 request.website_enabled = True
46 if request.website_enabled:
48 self._authenticate(func.routing['auth'])
50 self._auth_method_public()
51 request.website = request.registry['website'].get_current_website(request.cr, request.uid, context=request.context)
53 request.lang = request.website.default_lang_code
54 request.context['lang'] = request.lang
55 request.website.preprocess_request(request)
57 path = request.httprequest.path.split('/')
58 langs = [lg[0] for lg in request.website.get_languages()]
60 request.lang = request.context['lang'] = path.pop(1)
61 path = '/'.join(path) or '/'
62 return self.reroute(path)
63 return self._handle_exception(code=404)
64 return super(ir_http, self)._dispatch()
66 def reroute(self, path):
67 if not hasattr(request, 'rerouting'):
68 request.rerouting = []
69 if path in request.rerouting:
70 raise Exception("Rerouting loop is forbidden")
71 request.rerouting.append(path)
72 if len(request.rerouting) > self.rerouting_limit:
73 raise Exception("Rerouting limit exceeded")
74 request.httprequest.environ['PATH_INFO'] = path
75 # void werkzeug cached_property. TODO: find a proper way to do this
76 for key in ('path', 'full_path', 'url', 'base_url'):
77 request.httprequest.__dict__.pop(key, None)
79 return self._dispatch()
81 def _postprocess_args(self, arguments):
82 url = request.httprequest.url
83 for arg in arguments.itervalues():
84 if isinstance(arg, orm.browse_record) and isinstance(arg._uid, RequestUID):
85 placeholder = arg._uid
86 arg._uid = request.uid
89 if str(arg.id) != placeholder.value and placeholder.value != good_slug:
90 # TODO: properly recompose the url instead of using replace()
91 url = url.replace(placeholder.value, good_slug)
93 return self._handle_exception(werkzeug.exceptions.NotFound())
94 if url != request.httprequest.url:
95 werkzeug.exceptions.abort(werkzeug.utils.redirect(url))
97 def _handle_exception(self, exception=None, code=500):
98 if isinstance(exception, werkzeug.exceptions.HTTPException) and hasattr(exception, 'response') and exception.response:
99 return exception.response
100 if getattr(request, 'website_enabled', False) and request.website:
103 traceback=traceback.format_exc(exception),
106 code = getattr(exception, 'code', code)
107 if isinstance(exception, ir_qweb.QWebException):
108 values.update(qweb_exception=exception)
109 if isinstance(exception.qweb.get('cause'), openerp.exceptions.AccessError):
112 logger.error("500 Internal Server Error:\n\n%s", values['traceback'])
113 if 'qweb_exception' in values:
114 view = request.registry.get("ir.ui.view")
115 views = view._views_get(request.cr, request.uid, exception.qweb['template'], request.context)
116 to_reset = [v for v in views if v.model_data_id.noupdate is True]
117 values['views'] = to_reset
119 logger.warn("403 Forbidden:\n\n%s", values['traceback'])
122 status_message=werkzeug.http.HTTP_STATUS_CODES[code],
127 self._auth_method_public()
130 html = request.website._render('website.%s' % code, values)
132 html = request.website._render('website.http_error', values)
133 return werkzeug.wrappers.Response(html, status=code, content_type='text/html;charset=utf-8')
135 return super(ir_http, self)._handle_exception(exception)
137 class ModelConverter(ir.ir_http.ModelConverter):
138 def __init__(self, url_map, model=False):
139 super(ModelConverter, self).__init__(url_map, model)
140 self.regex = r'(?:[A-Za-z0-9-_]+?-)?(\d+)(?=$|/)'
142 def to_url(self, value):
145 def to_python(self, value):
146 m = re.match(self.regex, value)
147 _uid = RequestUID(value=value, match=m, converter=self)
148 return request.registry[self.model].browse(
149 request.cr, _uid, int(m.group(1)), context=request.context)
151 def generate(self, cr, uid, query=None, context=None):
152 return request.registry[self.model].name_search(
153 cr, uid, name=query or '', context=context)
155 class PageConverter(werkzeug.routing.PathConverter):
156 """ Only point of this converter is to bundle pages enumeration logic
158 Sads got: no way to get the view's human-readable name even if one exists
160 def generate(self, cr, uid, query=None, context=None):
161 View = request.registry['ir.ui.view']
162 views = View.search_read(
163 cr, uid, [['page', '=', True]],
164 fields=[], order='name', context=context)
165 xids = View.get_external_id(
166 cr, uid, [view['id'] for view in views], context=context)
169 xid = xids[view['id']]
170 if xid and (not query or query.lower() in xid.lower()):