author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Wed, 02 Dec 2009 16:57:17 +0100 | |
branch | stable |
changeset 3974 | 1d36d9904c41 |
parent 3865 | f9778a00e47f |
child 3890 | d7a270f50f54 |
child 4212 | ab6573088b4a |
permissions | -rw-r--r-- |
0 | 1 |
"""Rules based url rewriter component, to get configurable RESTful urls |
2 |
||
3 |
:organization: Logilab |
|
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1879
diff
changeset
|
4 |
:copyright: 2007-2009 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 |
""" |
|
71 |
id = 'simple' |
|
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')), |
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1132
diff
changeset
|
86 |
(rgx('/schema/([^/]+?)/?'), dict(vid='eschema', rql=r'Any X WHERE X is CWEType, X name "\1"')), |
0 | 87 |
(rgx('/add/([^/]+?)/?'), dict(vid='creation', etype=r'\1')), |
88 |
(rgx('/doc/images/(.+?)/?'), dict(vid='wdocimages', fid=r'\1')), |
|
89 |
(rgx('/doc/?'), dict(vid='wdoc', fid=r'main')), |
|
90 |
(rgx('/doc/(.+?)/?'), dict(vid='wdoc', fid=r'\1')), |
|
91 |
(rgx('/changelog/?'), dict(vid='changelog')), |
|
92 |
] |
|
1433 | 93 |
|
0 | 94 |
def rewrite(self, req, uri): |
95 |
"""for each `input`, `output `in rules, if `uri` matches `input`, |
|
96 |
req's form is updated with `output` |
|
97 |
""" |
|
98 |
for data in self.rules: |
|
99 |
try: |
|
100 |
inputurl, infos, required_groups = data |
|
101 |
except ValueError: |
|
102 |
inputurl, infos = data |
|
103 |
required_groups = None |
|
104 |
if required_groups and not req.user.matching_groups(required_groups): |
|
105 |
continue |
|
106 |
if isinstance(inputurl, basestring): |
|
107 |
if inputurl == uri: |
|
108 |
req.form.update(infos) |
|
109 |
break |
|
110 |
elif inputurl.match(uri): # it's a regexp |
|
111 |
# XXX what about i18n ? (vtitle for instance) |
|
112 |
for param, value in infos.items(): |
|
113 |
if isinstance(value, basestring): |
|
1132 | 114 |
req.form[param] = inputurl.sub(value, uri) |
0 | 115 |
else: |
116 |
req.form[param] = value |
|
117 |
break |
|
118 |
else: |
|
119 |
self.debug("no simple rewrite rule found for %s", uri) |
|
120 |
raise KeyError(uri) |
|
121 |
return None, None |
|
122 |
||
123 |
||
124 |
def build_rset(rql, rgxgroups=None, cachekey=None, setuser=False, |
|
125 |
vid=None, vtitle=None, form={}, **kwargs): |
|
126 |
||
127 |
def do_build_rset(inputurl, uri, req, schema): |
|
128 |
if rgxgroups: |
|
129 |
match = inputurl.match(uri) |
|
130 |
for arg, group in rgxgroups: |
|
131 |
kwargs[arg] = match.group(group) |
|
132 |
req.form.update(form) |
|
133 |
if setuser: |
|
134 |
kwargs['u'] = req.user.eid |
|
135 |
if vid: |
|
136 |
req.form['vid'] = vid |
|
137 |
if vtitle: |
|
138 |
req.form['vtitle'] = req._(vtitle) % kwargs |
|
139 |
return None, req.execute(rql, kwargs, cachekey) |
|
140 |
return do_build_rset |
|
141 |
||
142 |
def update_form(**kwargs): |
|
143 |
def do_build_rset(inputurl, uri, req, schema): |
|
144 |
match = inputurl.match(uri) |
|
145 |
kwargs.update(match.groupdict()) |
|
146 |
req.form.update(kwargs) |
|
147 |
return None, None |
|
148 |
return do_build_rset |
|
149 |
||
150 |
def rgx_action(rql=None, args=None, cachekey=None, argsgroups=(), setuser=False, |
|
151 |
form=None, formgroups=(), transforms={}, controller=None): |
|
3865
f9778a00e47f
actually fix rgx_action
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3864
diff
changeset
|
152 |
def do_build_rset(inputurl, uri, req, schema, |
f9778a00e47f
actually fix rgx_action
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3864
diff
changeset
|
153 |
cachekey=cachekey # necessary to avoid UnboundLocalError |
f9778a00e47f
actually fix rgx_action
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3864
diff
changeset
|
154 |
): |
0 | 155 |
if rql: |
156 |
kwargs = args and args.copy() or {} |
|
157 |
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
|
158 |
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
|
159 |
cachekey = (cachekey,) |
0 | 160 |
match = inputurl.match(uri) |
161 |
for key in argsgroups: |
|
162 |
value = match.group(key) |
|
163 |
try: |
|
164 |
kwargs[key] = transforms[key](value) |
|
165 |
except KeyError: |
|
166 |
kwargs[key] = value |
|
3865
f9778a00e47f
actually fix rgx_action
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3864
diff
changeset
|
167 |
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
|
168 |
kwargs[key] = typed_eid(value) |
0 | 169 |
if setuser: |
170 |
kwargs['u'] = req.user.eid |
|
171 |
rset = req.execute(rql, kwargs, cachekey) |
|
172 |
else: |
|
173 |
rset = None |
|
174 |
form2 = form and form.copy() or {} |
|
175 |
if formgroups: |
|
176 |
match = inputurl.match(uri) |
|
177 |
for key in formgroups: |
|
178 |
form2[key] = match.group(key) |
|
3537
73b5bec579ba
[B] urlrewite: basic patch for i18n vtitle
Julien Jehannet <julien.jehannet@logilab.fr>
parents:
2748
diff
changeset
|
179 |
if "vtitle" in form2: |
3592
4c08780e54ed
[i18n] msgid tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3537
diff
changeset
|
180 |
form2['vtitle'] = req.__(form2['vtitle']) |
0 | 181 |
if form2: |
182 |
req.form.update(form2) |
|
183 |
return controller, rset |
|
184 |
return do_build_rset |
|
185 |
||
186 |
||
187 |
class SchemaBasedRewriter(URLRewriter): |
|
188 |
"""Here, the rules dict maps regexps or plain strings to |
|
189 |
callbacks that will be called with (input, uri, req, schema) |
|
190 |
""" |
|
191 |
id = 'schemabased' |
|
192 |
rules = [ |
|
193 |
# rgxp : callback |
|
194 |
(rgx('/search/(.+)'), build_rset(rql=r'Any X WHERE X has_text %(text)s', |
|
1433 | 195 |
rgxgroups=[('text', 1)])), |
0 | 196 |
] |
197 |
||
198 |
def rewrite(self, req, uri): |
|
199 |
# XXX this could be refacted with SimpleReqRewriter |
|
200 |
for data in self.rules: |
|
201 |
try: |
|
202 |
inputurl, callback, required_groups = data |
|
203 |
except ValueError: |
|
204 |
inputurl, callback = data |
|
205 |
required_groups = None |
|
206 |
if required_groups and not req.user.matching_groups(required_groups): |
|
207 |
continue |
|
208 |
if isinstance(inputurl, basestring): |
|
209 |
if inputurl == uri: |
|
210 |
return callback(inputurl, uri, req, self.schema) |
|
211 |
elif inputurl.match(uri): # it's a regexp |
|
212 |
return callback(inputurl, uri, req, self.schema) |
|
213 |
else: |
|
214 |
self.debug("no schemabased rewrite rule found for %s", uri) |
|
215 |
raise KeyError(uri) |