author | arthur |
Fri, 26 Feb 2010 07:07:28 +0100 | |
branch | stable |
changeset 4706 | 6035e96b64dd |
parent 4436 | 294e084f1263 |
child 5301 | f4219a6e62e3 |
permissions | -rw-r--r-- |
0 | 1 |
"""Rules based url rewriter component, to get configurable RESTful urls |
2 |
||
3 |
:organization: Logilab |
|
4212
ab6573088b4a
update copyright: welcome 2010
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
3865
diff
changeset
|
4 |
:copyright: 2007-2010 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2. |
0 | 5 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1879
diff
changeset
|
6 |
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses |
0 | 7 |
""" |
8 |
import re |
|
9 |
||
3856
1c9589e46b16
fix rgx_action to ensure eids given to .execute are correctly typed
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3592
diff
changeset
|
10 |
from cubicweb import typed_eid |
722 | 11 |
from cubicweb.appobject import AppObject |
0 | 12 |
|
13 |
||
14 |
def rgx(pattern, flags=0): |
|
15 |
"""this is just a convenient shortcout to add the $ sign""" |
|
16 |
return re.compile(pattern+'$', flags) |
|
17 |
||
712
ce49e3885453
remove autoselectors metaclass, __select__ is built during registration
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
688
diff
changeset
|
18 |
class metarewriter(type): |
0 | 19 |
"""auto-extend rules dictionnary""" |
20 |
def __new__(mcs, name, bases, classdict): |
|
21 |
# collect baseclass' rules |
|
22 |
rules = [] |
|
23 |
ignore_baseclass_rules = classdict.get('ignore_baseclass_rules', False) |
|
24 |
if not ignore_baseclass_rules: |
|
25 |
for base in bases: |
|
26 |
rules[0:0] = getattr(base, 'rules', []) |
|
27 |
rules[0:0] = classdict.get('rules', []) |
|
28 |
inputs = set() |
|
29 |
for data in rules[:]: |
|
30 |
try: |
|
31 |
input, output, groups = data |
|
32 |
except ValueError: |
|
33 |
input, output = data |
|
34 |
if input in inputs: |
|
35 |
rules.remove( (input, output) ) |
|
36 |
else: |
|
37 |
inputs.add(input) |
|
38 |
classdict['rules'] = rules |
|
39 |
return super(metarewriter, mcs).__new__(mcs, name, bases, classdict) |
|
40 |
||
41 |
||
42 |
class URLRewriter(AppObject): |
|
43 |
"""base class for URL rewriters |
|
44 |
||
45 |
url rewriters should have a `rules` dict that maps an input URI |
|
46 |
to something that should be used for rewriting. |
|
47 |
||
48 |
The actual logic that defines how the rules dict is used is implemented |
|
49 |
in the `rewrite` method |
|
50 |
||
51 |
A `priority` attribute might be used to indicate which rewriter |
|
52 |
should be tried first. The higher the priority is, the earlier the |
|
53 |
rewriter will be tried |
|
54 |
""" |
|
55 |
__metaclass__ = metarewriter |
|
56 |
__registry__ = 'urlrewriting' |
|
57 |
__abstract__ = True |
|
58 |
priority = 1 |
|
59 |
||
60 |
def rewrite(self, req, uri): |
|
61 |
raise NotImplementedError |
|
62 |
||
63 |
||
64 |
class SimpleReqRewriter(URLRewriter): |
|
65 |
"""The SimpleReqRewriters uses a `rules` dict that maps |
|
66 |
input URI (regexp or plain string) to a dictionary to update the |
|
67 |
request's form |
|
68 |
||
69 |
If the input uri is a regexp, group substitution is allowed |
|
70 |
""" |
|
3377
dd9d292b6a6d
use __regid__ instead of id on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2748
diff
changeset
|
71 |
__regid__ = 'simple' |
0 | 72 |
|
73 |
rules = [ |
|
2748
d2fcf19bfb34
F [registry views] add _registry startup view
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2656
diff
changeset
|
74 |
('/_', dict(vid='manage')), |
d2fcf19bfb34
F [registry views] add _registry startup view
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2656
diff
changeset
|
75 |
('/_registry', dict(vid='registry')), |
d2fcf19bfb34
F [registry views] add _registry startup view
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2656
diff
changeset
|
76 |
# (rgx('/_([^/]+?)/?'), dict(vid=r'\1')), |
0 | 77 |
('/schema', dict(vid='schema')), |
78 |
('/index', dict(vid='index')), |
|
1879
cb3466e08d81
eproperty -> cwproperty, cleanup
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1433
diff
changeset
|
79 |
('/myprefs', dict(vid='propertiesform')), |
cb3466e08d81
eproperty -> cwproperty, cleanup
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1433
diff
changeset
|
80 |
('/siteconfig', dict(vid='systempropertiesform')), |
2433
1d46c016a564
#197873: quick access to info for bug report
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2422
diff
changeset
|
81 |
('/siteinfo', dict(vid='info')), |
0 | 82 |
('/manage', dict(vid='manage')), |
83 |
('/notfound', dict(vid='404')), |
|
84 |
('/error', dict(vid='error')), |
|
2422
96da7dc42eb5
quick and dirty support from simple sparql queries + base ui
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
85 |
('/sparql', dict(vid='sparql')), |
4706
6035e96b64dd
added stats for munin collecting #615844 - from 027bbff3659f
arthur
parents:
4436
diff
changeset
|
86 |
('/processinfo', dict(vid='processinfo')), |
4405
fe31bb5dada5
eschema view is gone away
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4212
diff
changeset
|
87 |
# XXX should be case insensitive as 'create', but I would like to find another way than |
fe31bb5dada5
eschema view is gone away
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4212
diff
changeset
|
88 |
# relying on the etype_selector |
fe31bb5dada5
eschema view is gone away
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4212
diff
changeset
|
89 |
(rgx('/schema/([^/]+?)/?'), dict(vid='primary', rql=r'Any X WHERE X is CWEType, X name "\1"')), |
0 | 90 |
(rgx('/add/([^/]+?)/?'), dict(vid='creation', etype=r'\1')), |
91 |
(rgx('/doc/images/(.+?)/?'), dict(vid='wdocimages', fid=r'\1')), |
|
92 |
(rgx('/doc/?'), dict(vid='wdoc', fid=r'main')), |
|
93 |
(rgx('/doc/(.+?)/?'), dict(vid='wdoc', fid=r'\1')), |
|
94 |
(rgx('/changelog/?'), dict(vid='changelog')), |
|
95 |
] |
|
1433 | 96 |
|
0 | 97 |
def rewrite(self, req, uri): |
98 |
"""for each `input`, `output `in rules, if `uri` matches `input`, |
|
99 |
req's form is updated with `output` |
|
100 |
""" |
|
101 |
for data in self.rules: |
|
102 |
try: |
|
103 |
inputurl, infos, required_groups = data |
|
104 |
except ValueError: |
|
105 |
inputurl, infos = data |
|
106 |
required_groups = None |
|
107 |
if required_groups and not req.user.matching_groups(required_groups): |
|
108 |
continue |
|
109 |
if isinstance(inputurl, basestring): |
|
110 |
if inputurl == uri: |
|
111 |
req.form.update(infos) |
|
112 |
break |
|
113 |
elif inputurl.match(uri): # it's a regexp |
|
114 |
# XXX what about i18n ? (vtitle for instance) |
|
115 |
for param, value in infos.items(): |
|
116 |
if isinstance(value, basestring): |
|
1132 | 117 |
req.form[param] = inputurl.sub(value, uri) |
0 | 118 |
else: |
119 |
req.form[param] = value |
|
120 |
break |
|
121 |
else: |
|
122 |
self.debug("no simple rewrite rule found for %s", uri) |
|
123 |
raise KeyError(uri) |
|
124 |
return None, None |
|
125 |
||
126 |
||
127 |
def build_rset(rql, rgxgroups=None, cachekey=None, setuser=False, |
|
128 |
vid=None, vtitle=None, form={}, **kwargs): |
|
129 |
||
130 |
def do_build_rset(inputurl, uri, req, schema): |
|
131 |
if rgxgroups: |
|
132 |
match = inputurl.match(uri) |
|
133 |
for arg, group in rgxgroups: |
|
134 |
kwargs[arg] = match.group(group) |
|
135 |
req.form.update(form) |
|
136 |
if setuser: |
|
137 |
kwargs['u'] = req.user.eid |
|
138 |
if vid: |
|
139 |
req.form['vid'] = vid |
|
140 |
if vtitle: |
|
141 |
req.form['vtitle'] = req._(vtitle) % kwargs |
|
142 |
return None, req.execute(rql, kwargs, cachekey) |
|
143 |
return do_build_rset |
|
144 |
||
145 |
def update_form(**kwargs): |
|
146 |
def do_build_rset(inputurl, uri, req, schema): |
|
147 |
match = inputurl.match(uri) |
|
148 |
kwargs.update(match.groupdict()) |
|
149 |
req.form.update(kwargs) |
|
150 |
return None, None |
|
151 |
return do_build_rset |
|
152 |
||
153 |
def rgx_action(rql=None, args=None, cachekey=None, argsgroups=(), setuser=False, |
|
154 |
form=None, formgroups=(), transforms={}, controller=None): |
|
3865
f9778a00e47f
actually fix rgx_action
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3864
diff
changeset
|
155 |
def do_build_rset(inputurl, uri, req, schema, |
f9778a00e47f
actually fix rgx_action
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3864
diff
changeset
|
156 |
cachekey=cachekey # necessary to avoid UnboundLocalError |
f9778a00e47f
actually fix rgx_action
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3864
diff
changeset
|
157 |
): |
0 | 158 |
if rql: |
159 |
kwargs = args and args.copy() or {} |
|
160 |
if argsgroups: |
|
3856
1c9589e46b16
fix rgx_action to ensure eids given to .execute are correctly typed
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3592
diff
changeset
|
161 |
if cachekey is not None and isinstance(cachekey, basestring): |
1c9589e46b16
fix rgx_action to ensure eids given to .execute are correctly typed
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3592
diff
changeset
|
162 |
cachekey = (cachekey,) |
0 | 163 |
match = inputurl.match(uri) |
164 |
for key in argsgroups: |
|
165 |
value = match.group(key) |
|
166 |
try: |
|
167 |
kwargs[key] = transforms[key](value) |
|
168 |
except KeyError: |
|
169 |
kwargs[key] = value |
|
3865
f9778a00e47f
actually fix rgx_action
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3864
diff
changeset
|
170 |
if cachekey is not None and key in cachekey: |
3856
1c9589e46b16
fix rgx_action to ensure eids given to .execute are correctly typed
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3592
diff
changeset
|
171 |
kwargs[key] = typed_eid(value) |
0 | 172 |
if setuser: |
173 |
kwargs['u'] = req.user.eid |
|
174 |
rset = req.execute(rql, kwargs, cachekey) |
|
175 |
else: |
|
176 |
rset = None |
|
177 |
form2 = form and form.copy() or {} |
|
178 |
if formgroups: |
|
179 |
match = inputurl.match(uri) |
|
180 |
for key in formgroups: |
|
181 |
form2[key] = match.group(key) |
|
3537
73b5bec579ba
[B] urlrewite: basic patch for i18n vtitle
Julien Jehannet <julien.jehannet@logilab.fr>
parents:
2748
diff
changeset
|
182 |
if "vtitle" in form2: |
3592
4c08780e54ed
[i18n] msgid tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3537
diff
changeset
|
183 |
form2['vtitle'] = req.__(form2['vtitle']) |
0 | 184 |
if form2: |
185 |
req.form.update(form2) |
|
186 |
return controller, rset |
|
187 |
return do_build_rset |
|
188 |
||
189 |
||
190 |
class SchemaBasedRewriter(URLRewriter): |
|
191 |
"""Here, the rules dict maps regexps or plain strings to |
|
192 |
callbacks that will be called with (input, uri, req, schema) |
|
193 |
""" |
|
3377
dd9d292b6a6d
use __regid__ instead of id on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2748
diff
changeset
|
194 |
__regid__ = 'schemabased' |
0 | 195 |
rules = [ |
196 |
# rgxp : callback |
|
197 |
(rgx('/search/(.+)'), build_rset(rql=r'Any X WHERE X has_text %(text)s', |
|
1433 | 198 |
rgxgroups=[('text', 1)])), |
0 | 199 |
] |
200 |
||
201 |
def rewrite(self, req, uri): |
|
202 |
# XXX this could be refacted with SimpleReqRewriter |
|
203 |
for data in self.rules: |
|
204 |
try: |
|
205 |
inputurl, callback, required_groups = data |
|
206 |
except ValueError: |
|
207 |
inputurl, callback = data |
|
208 |
required_groups = None |
|
209 |
if required_groups and not req.user.matching_groups(required_groups): |
|
210 |
continue |
|
211 |
if isinstance(inputurl, basestring): |
|
212 |
if inputurl == uri: |
|
4045
f4a52abb6f4f
cw 3.6 api update
Sandrine Ribeau <sandrine.ribeau@logilab.fr>
parents:
3890
diff
changeset
|
213 |
return callback(inputurl, uri, req, self._cw.vreg.schema) |
0 | 214 |
elif inputurl.match(uri): # it's a regexp |
4045
f4a52abb6f4f
cw 3.6 api update
Sandrine Ribeau <sandrine.ribeau@logilab.fr>
parents:
3890
diff
changeset
|
215 |
return callback(inputurl, uri, req, self._cw.vreg.schema) |
0 | 216 |
else: |
217 |
self.debug("no schemabased rewrite rule found for %s", uri) |
|
218 |
raise KeyError(uri) |