author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Tue, 13 Oct 2009 08:47:41 +0200 | |
changeset 3645 | 7272b793d7c9 |
parent 3629 | 559cad62c786 |
child 3890 | d7a270f50f54 |
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 |
||
722 | 10 |
from cubicweb.appobject import AppObject |
0 | 11 |
|
12 |
||
13 |
def rgx(pattern, flags=0): |
|
14 |
"""this is just a convenient shortcout to add the $ sign""" |
|
15 |
return re.compile(pattern+'$', flags) |
|
16 |
||
712
ce49e3885453
remove autoselectors metaclass, __select__ is built during registration
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
688
diff
changeset
|
17 |
class metarewriter(type): |
0 | 18 |
"""auto-extend rules dictionnary""" |
19 |
def __new__(mcs, name, bases, classdict): |
|
20 |
# collect baseclass' rules |
|
21 |
rules = [] |
|
22 |
ignore_baseclass_rules = classdict.get('ignore_baseclass_rules', False) |
|
23 |
if not ignore_baseclass_rules: |
|
24 |
for base in bases: |
|
25 |
rules[0:0] = getattr(base, 'rules', []) |
|
26 |
rules[0:0] = classdict.get('rules', []) |
|
27 |
inputs = set() |
|
28 |
for data in rules[:]: |
|
29 |
try: |
|
30 |
input, output, groups = data |
|
31 |
except ValueError: |
|
32 |
input, output = data |
|
33 |
if input in inputs: |
|
34 |
rules.remove( (input, output) ) |
|
35 |
else: |
|
36 |
inputs.add(input) |
|
37 |
classdict['rules'] = rules |
|
38 |
return super(metarewriter, mcs).__new__(mcs, name, bases, classdict) |
|
39 |
||
40 |
||
41 |
class URLRewriter(AppObject): |
|
42 |
"""base class for URL rewriters |
|
43 |
||
44 |
url rewriters should have a `rules` dict that maps an input URI |
|
45 |
to something that should be used for rewriting. |
|
46 |
||
47 |
The actual logic that defines how the rules dict is used is implemented |
|
48 |
in the `rewrite` method |
|
49 |
||
50 |
A `priority` attribute might be used to indicate which rewriter |
|
51 |
should be tried first. The higher the priority is, the earlier the |
|
52 |
rewriter will be tried |
|
53 |
""" |
|
54 |
__metaclass__ = metarewriter |
|
55 |
__registry__ = 'urlrewriting' |
|
56 |
__abstract__ = True |
|
57 |
priority = 1 |
|
58 |
||
59 |
def rewrite(self, req, uri): |
|
60 |
raise NotImplementedError |
|
61 |
||
62 |
||
63 |
class SimpleReqRewriter(URLRewriter): |
|
64 |
"""The SimpleReqRewriters uses a `rules` dict that maps |
|
65 |
input URI (regexp or plain string) to a dictionary to update the |
|
66 |
request's form |
|
67 |
||
68 |
If the input uri is a regexp, group substitution is allowed |
|
69 |
""" |
|
3377
dd9d292b6a6d
use __regid__ instead of id on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2748
diff
changeset
|
70 |
__regid__ = 'simple' |
0 | 71 |
|
72 |
rules = [ |
|
2748
d2fcf19bfb34
F [registry views] add _registry startup view
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2656
diff
changeset
|
73 |
('/_', dict(vid='manage')), |
d2fcf19bfb34
F [registry views] add _registry startup view
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2656
diff
changeset
|
74 |
('/_registry', dict(vid='registry')), |
d2fcf19bfb34
F [registry views] add _registry startup view
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2656
diff
changeset
|
75 |
# (rgx('/_([^/]+?)/?'), dict(vid=r'\1')), |
0 | 76 |
('/schema', dict(vid='schema')), |
77 |
('/index', dict(vid='index')), |
|
1879
cb3466e08d81
eproperty -> cwproperty, cleanup
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1433
diff
changeset
|
78 |
('/myprefs', dict(vid='propertiesform')), |
cb3466e08d81
eproperty -> cwproperty, cleanup
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1433
diff
changeset
|
79 |
('/siteconfig', dict(vid='systempropertiesform')), |
2433
1d46c016a564
#197873: quick access to info for bug report
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2422
diff
changeset
|
80 |
('/siteinfo', dict(vid='info')), |
0 | 81 |
('/manage', dict(vid='manage')), |
82 |
('/notfound', dict(vid='404')), |
|
83 |
('/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
|
84 |
('/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
|
85 |
(rgx('/schema/([^/]+?)/?'), dict(vid='eschema', rql=r'Any X WHERE X is CWEType, X name "\1"')), |
0 | 86 |
(rgx('/add/([^/]+?)/?'), dict(vid='creation', etype=r'\1')), |
87 |
(rgx('/doc/images/(.+?)/?'), dict(vid='wdocimages', fid=r'\1')), |
|
88 |
(rgx('/doc/?'), dict(vid='wdoc', fid=r'main')), |
|
89 |
(rgx('/doc/(.+?)/?'), dict(vid='wdoc', fid=r'\1')), |
|
90 |
(rgx('/changelog/?'), dict(vid='changelog')), |
|
91 |
] |
|
1433 | 92 |
|
0 | 93 |
def rewrite(self, req, uri): |
94 |
"""for each `input`, `output `in rules, if `uri` matches `input`, |
|
95 |
req's form is updated with `output` |
|
96 |
""" |
|
97 |
for data in self.rules: |
|
98 |
try: |
|
99 |
inputurl, infos, required_groups = data |
|
100 |
except ValueError: |
|
101 |
inputurl, infos = data |
|
102 |
required_groups = None |
|
103 |
if required_groups and not req.user.matching_groups(required_groups): |
|
104 |
continue |
|
105 |
if isinstance(inputurl, basestring): |
|
106 |
if inputurl == uri: |
|
107 |
req.form.update(infos) |
|
108 |
break |
|
109 |
elif inputurl.match(uri): # it's a regexp |
|
110 |
# XXX what about i18n ? (vtitle for instance) |
|
111 |
for param, value in infos.items(): |
|
112 |
if isinstance(value, basestring): |
|
1132 | 113 |
req.form[param] = inputurl.sub(value, uri) |
0 | 114 |
else: |
115 |
req.form[param] = value |
|
116 |
break |
|
117 |
else: |
|
118 |
self.debug("no simple rewrite rule found for %s", uri) |
|
119 |
raise KeyError(uri) |
|
120 |
return None, None |
|
121 |
||
122 |
||
123 |
def build_rset(rql, rgxgroups=None, cachekey=None, setuser=False, |
|
124 |
vid=None, vtitle=None, form={}, **kwargs): |
|
125 |
||
126 |
def do_build_rset(inputurl, uri, req, schema): |
|
127 |
if rgxgroups: |
|
128 |
match = inputurl.match(uri) |
|
129 |
for arg, group in rgxgroups: |
|
130 |
kwargs[arg] = match.group(group) |
|
131 |
req.form.update(form) |
|
132 |
if setuser: |
|
133 |
kwargs['u'] = req.user.eid |
|
134 |
if vid: |
|
135 |
req.form['vid'] = vid |
|
136 |
if vtitle: |
|
137 |
req.form['vtitle'] = req._(vtitle) % kwargs |
|
138 |
return None, req.execute(rql, kwargs, cachekey) |
|
139 |
return do_build_rset |
|
140 |
||
141 |
def update_form(**kwargs): |
|
142 |
def do_build_rset(inputurl, uri, req, schema): |
|
143 |
match = inputurl.match(uri) |
|
144 |
kwargs.update(match.groupdict()) |
|
145 |
req.form.update(kwargs) |
|
146 |
return None, None |
|
147 |
return do_build_rset |
|
148 |
||
149 |
def rgx_action(rql=None, args=None, cachekey=None, argsgroups=(), setuser=False, |
|
150 |
form=None, formgroups=(), transforms={}, controller=None): |
|
151 |
def do_build_rset(inputurl, uri, req, schema): |
|
152 |
if rql: |
|
153 |
kwargs = args and args.copy() or {} |
|
154 |
if argsgroups: |
|
155 |
match = inputurl.match(uri) |
|
156 |
for key in argsgroups: |
|
157 |
value = match.group(key) |
|
158 |
try: |
|
159 |
kwargs[key] = transforms[key](value) |
|
160 |
except KeyError: |
|
161 |
kwargs[key] = value |
|
162 |
if setuser: |
|
163 |
kwargs['u'] = req.user.eid |
|
164 |
rset = req.execute(rql, kwargs, cachekey) |
|
165 |
else: |
|
166 |
rset = None |
|
167 |
form2 = form and form.copy() or {} |
|
168 |
if formgroups: |
|
169 |
match = inputurl.match(uri) |
|
170 |
for key in formgroups: |
|
171 |
form2[key] = match.group(key) |
|
3537
73b5bec579ba
[B] urlrewite: basic patch for i18n vtitle
Julien Jehannet <julien.jehannet@logilab.fr>
parents:
2748
diff
changeset
|
172 |
if "vtitle" in form2: |
3592
4c08780e54ed
[i18n] msgid tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3537
diff
changeset
|
173 |
form2['vtitle'] = req.__(form2['vtitle']) |
0 | 174 |
if form2: |
175 |
req.form.update(form2) |
|
176 |
return controller, rset |
|
177 |
return do_build_rset |
|
178 |
||
179 |
||
180 |
class SchemaBasedRewriter(URLRewriter): |
|
181 |
"""Here, the rules dict maps regexps or plain strings to |
|
182 |
callbacks that will be called with (input, uri, req, schema) |
|
183 |
""" |
|
3377
dd9d292b6a6d
use __regid__ instead of id on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2748
diff
changeset
|
184 |
__regid__ = 'schemabased' |
0 | 185 |
rules = [ |
186 |
# rgxp : callback |
|
187 |
(rgx('/search/(.+)'), build_rset(rql=r'Any X WHERE X has_text %(text)s', |
|
1433 | 188 |
rgxgroups=[('text', 1)])), |
0 | 189 |
] |
190 |
||
191 |
def rewrite(self, req, uri): |
|
192 |
# XXX this could be refacted with SimpleReqRewriter |
|
193 |
for data in self.rules: |
|
194 |
try: |
|
195 |
inputurl, callback, required_groups = data |
|
196 |
except ValueError: |
|
197 |
inputurl, callback = data |
|
198 |
required_groups = None |
|
199 |
if required_groups and not req.user.matching_groups(required_groups): |
|
200 |
continue |
|
201 |
if isinstance(inputurl, basestring): |
|
202 |
if inputurl == uri: |
|
3451
6b46d73823f5
[api] work in progress, use __regid__, cw_*, etc.
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
3377
diff
changeset
|
203 |
return callback(inputurl, uri, req, self._cw.schema) |
0 | 204 |
elif inputurl.match(uri): # it's a regexp |
3451
6b46d73823f5
[api] work in progress, use __regid__, cw_*, etc.
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
3377
diff
changeset
|
205 |
return callback(inputurl, uri, req, self._cw.schema) |
0 | 206 |
else: |
207 |
self.debug("no schemabased rewrite rule found for %s", uri) |
|
208 |
raise KeyError(uri) |