author | Adrien Di Mascio <Adrien.DiMascio@logilab.fr> |
Wed, 23 Sep 2009 19:40:19 +0200 | |
changeset 3451 | 6b46d73823f5 |
parent 3377 | dd9d292b6a6d |
child 3589 | a5432f99f2d9 |
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) |
|
172 |
if form2: |
|
173 |
req.form.update(form2) |
|
174 |
return controller, rset |
|
175 |
return do_build_rset |
|
176 |
||
177 |
||
178 |
class SchemaBasedRewriter(URLRewriter): |
|
179 |
"""Here, the rules dict maps regexps or plain strings to |
|
180 |
callbacks that will be called with (input, uri, req, schema) |
|
181 |
""" |
|
3377
dd9d292b6a6d
use __regid__ instead of id on appobject classes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2748
diff
changeset
|
182 |
__regid__ = 'schemabased' |
0 | 183 |
rules = [ |
184 |
# rgxp : callback |
|
185 |
(rgx('/search/(.+)'), build_rset(rql=r'Any X WHERE X has_text %(text)s', |
|
1433 | 186 |
rgxgroups=[('text', 1)])), |
0 | 187 |
] |
188 |
||
189 |
def rewrite(self, req, uri): |
|
190 |
# XXX this could be refacted with SimpleReqRewriter |
|
191 |
for data in self.rules: |
|
192 |
try: |
|
193 |
inputurl, callback, required_groups = data |
|
194 |
except ValueError: |
|
195 |
inputurl, callback = data |
|
196 |
required_groups = None |
|
197 |
if required_groups and not req.user.matching_groups(required_groups): |
|
198 |
continue |
|
199 |
if isinstance(inputurl, basestring): |
|
200 |
if inputurl == uri: |
|
3451
6b46d73823f5
[api] work in progress, use __regid__, cw_*, etc.
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
3377
diff
changeset
|
201 |
return callback(inputurl, uri, req, self._cw.schema) |
0 | 202 |
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
|
203 |
return callback(inputurl, uri, req, self._cw.schema) |
0 | 204 |
else: |
205 |
self.debug("no schemabased rewrite rule found for %s", uri) |
|
206 |
raise KeyError(uri) |