author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Wed, 10 Feb 2010 10:48:33 +0100 | |
changeset 4541 | 4bf6ed206206 |
parent 4436 | 294e084f1263 |
child 4706 | 6035e96b64dd |
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')), |
4405
fe31bb5dada5
eschema view is gone away
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4212
diff
changeset
|
86 |
# 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
|
87 |
# relying on the etype_selector |
fe31bb5dada5
eschema view is gone away
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4212
diff
changeset
|
88 |
(rgx('/schema/([^/]+?)/?'), dict(vid='primary', rql=r'Any X WHERE X is CWEType, X name "\1"')), |
0 | 89 |
(rgx('/add/([^/]+?)/?'), dict(vid='creation', etype=r'\1')), |
90 |
(rgx('/doc/images/(.+?)/?'), dict(vid='wdocimages', fid=r'\1')), |
|
91 |
(rgx('/doc/?'), dict(vid='wdoc', fid=r'main')), |
|
92 |
(rgx('/doc/(.+?)/?'), dict(vid='wdoc', fid=r'\1')), |
|
93 |
(rgx('/changelog/?'), dict(vid='changelog')), |
|
94 |
] |
|
1433 | 95 |
|
0 | 96 |
def rewrite(self, req, uri): |
97 |
"""for each `input`, `output `in rules, if `uri` matches `input`, |
|
98 |
req's form is updated with `output` |
|
99 |
""" |
|
100 |
for data in self.rules: |
|
101 |
try: |
|
102 |
inputurl, infos, required_groups = data |
|
103 |
except ValueError: |
|
104 |
inputurl, infos = data |
|
105 |
required_groups = None |
|
106 |
if required_groups and not req.user.matching_groups(required_groups): |
|
107 |
continue |
|
108 |
if isinstance(inputurl, basestring): |
|
109 |
if inputurl == uri: |
|
110 |
req.form.update(infos) |
|
111 |
break |
|
112 |
elif inputurl.match(uri): # it's a regexp |
|
113 |
# XXX what about i18n ? (vtitle for instance) |
|
114 |
for param, value in infos.items(): |
|
115 |
if isinstance(value, basestring): |
|
1132 | 116 |
req.form[param] = inputurl.sub(value, uri) |
0 | 117 |
else: |
118 |
req.form[param] = value |
|
119 |
break |
|
120 |
else: |
|
121 |
self.debug("no simple rewrite rule found for %s", uri) |
|
122 |
raise KeyError(uri) |
|
123 |
return None, None |
|
124 |
||
125 |
||
126 |
def build_rset(rql, rgxgroups=None, cachekey=None, setuser=False, |
|
127 |
vid=None, vtitle=None, form={}, **kwargs): |
|
128 |
||
129 |
def do_build_rset(inputurl, uri, req, schema): |
|
130 |
if rgxgroups: |
|
131 |
match = inputurl.match(uri) |
|
132 |
for arg, group in rgxgroups: |
|
133 |
kwargs[arg] = match.group(group) |
|
134 |
req.form.update(form) |
|
135 |
if setuser: |
|
136 |
kwargs['u'] = req.user.eid |
|
137 |
if vid: |
|
138 |
req.form['vid'] = vid |
|
139 |
if vtitle: |
|
140 |
req.form['vtitle'] = req._(vtitle) % kwargs |
|
141 |
return None, req.execute(rql, kwargs, cachekey) |
|
142 |
return do_build_rset |
|
143 |
||
144 |
def update_form(**kwargs): |
|
145 |
def do_build_rset(inputurl, uri, req, schema): |
|
146 |
match = inputurl.match(uri) |
|
147 |
kwargs.update(match.groupdict()) |
|
148 |
req.form.update(kwargs) |
|
149 |
return None, None |
|
150 |
return do_build_rset |
|
151 |
||
152 |
def rgx_action(rql=None, args=None, cachekey=None, argsgroups=(), setuser=False, |
|
153 |
form=None, formgroups=(), transforms={}, controller=None): |
|
3865
f9778a00e47f
actually fix rgx_action
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3864
diff
changeset
|
154 |
def do_build_rset(inputurl, uri, req, schema, |
f9778a00e47f
actually fix rgx_action
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3864
diff
changeset
|
155 |
cachekey=cachekey # necessary to avoid UnboundLocalError |
f9778a00e47f
actually fix rgx_action
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3864
diff
changeset
|
156 |
): |
0 | 157 |
if rql: |
158 |
kwargs = args and args.copy() or {} |
|
159 |
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
|
160 |
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
|
161 |
cachekey = (cachekey,) |
0 | 162 |
match = inputurl.match(uri) |
163 |
for key in argsgroups: |
|
164 |
value = match.group(key) |
|
165 |
try: |
|
166 |
kwargs[key] = transforms[key](value) |
|
167 |
except KeyError: |
|
168 |
kwargs[key] = value |
|
3865
f9778a00e47f
actually fix rgx_action
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3864
diff
changeset
|
169 |
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
|
170 |
kwargs[key] = typed_eid(value) |
0 | 171 |
if setuser: |
172 |
kwargs['u'] = req.user.eid |
|
173 |
rset = req.execute(rql, kwargs, cachekey) |
|
174 |
else: |
|
175 |
rset = None |
|
176 |
form2 = form and form.copy() or {} |
|
177 |
if formgroups: |
|
178 |
match = inputurl.match(uri) |
|
179 |
for key in formgroups: |
|
180 |
form2[key] = match.group(key) |
|
3537
73b5bec579ba
[B] urlrewite: basic patch for i18n vtitle
Julien Jehannet <julien.jehannet@logilab.fr>
parents:
2748
diff
changeset
|
181 |
if "vtitle" in form2: |
3592
4c08780e54ed
[i18n] msgid tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3537
diff
changeset
|
182 |
form2['vtitle'] = req.__(form2['vtitle']) |
0 | 183 |
if form2: |
184 |
req.form.update(form2) |
|
185 |
return controller, rset |
|
186 |
return do_build_rset |
|
187 |
||
188 |
||
189 |
class SchemaBasedRewriter(URLRewriter): |
|
190 |
"""Here, the rules dict maps regexps or plain strings to |
|
191 |
callbacks that will be called with (input, uri, req, schema) |
|
192 |
""" |
|
3377
dd9d292b6a6d
use __regid__ instead of id on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2748
diff
changeset
|
193 |
__regid__ = 'schemabased' |
0 | 194 |
rules = [ |
195 |
# rgxp : callback |
|
196 |
(rgx('/search/(.+)'), build_rset(rql=r'Any X WHERE X has_text %(text)s', |
|
1433 | 197 |
rgxgroups=[('text', 1)])), |
0 | 198 |
] |
199 |
||
200 |
def rewrite(self, req, uri): |
|
201 |
# XXX this could be refacted with SimpleReqRewriter |
|
202 |
for data in self.rules: |
|
203 |
try: |
|
204 |
inputurl, callback, required_groups = data |
|
205 |
except ValueError: |
|
206 |
inputurl, callback = data |
|
207 |
required_groups = None |
|
208 |
if required_groups and not req.user.matching_groups(required_groups): |
|
209 |
continue |
|
210 |
if isinstance(inputurl, basestring): |
|
211 |
if inputurl == uri: |
|
4045
f4a52abb6f4f
cw 3.6 api update
Sandrine Ribeau <sandrine.ribeau@logilab.fr>
parents:
3890
diff
changeset
|
212 |
return callback(inputurl, uri, req, self._cw.vreg.schema) |
0 | 213 |
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
|
214 |
return callback(inputurl, uri, req, self._cw.vreg.schema) |
0 | 215 |
else: |
216 |
self.debug("no schemabased rewrite rule found for %s", uri) |
|
217 |
raise KeyError(uri) |