author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Mon, 16 Nov 2009 17:51:45 +0100 | |
branch | stable |
changeset 3864 | 2fee9151c6b2 |
parent 3856 | 1c9589e46b16 |
child 3865 | f9778a00e47f |
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): |
|
152 |
def do_build_rset(inputurl, uri, req, schema): |
|
153 |
if rql: |
|
154 |
kwargs = args and args.copy() or {} |
|
3864
2fee9151c6b2
fix UnboundLocalError
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3856
diff
changeset
|
155 |
cachekey = cachekey # necessary to avoid UnboundLocalError |
0 | 156 |
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
|
157 |
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
|
158 |
cachekey = (cachekey,) |
0 | 159 |
match = inputurl.match(uri) |
160 |
for key in argsgroups: |
|
161 |
value = match.group(key) |
|
162 |
try: |
|
163 |
kwargs[key] = transforms[key](value) |
|
164 |
except KeyError: |
|
165 |
kwargs[key] = value |
|
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
|
166 |
if key in cachekey: |
1c9589e46b16
fix rgx_action to ensure eids given to .execute are correctly typed
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3592
diff
changeset
|
167 |
kwargs[key] = typed_eid(value) |
0 | 168 |
if setuser: |
169 |
kwargs['u'] = req.user.eid |
|
170 |
rset = req.execute(rql, kwargs, cachekey) |
|
171 |
else: |
|
172 |
rset = None |
|
173 |
form2 = form and form.copy() or {} |
|
174 |
if formgroups: |
|
175 |
match = inputurl.match(uri) |
|
176 |
for key in formgroups: |
|
177 |
form2[key] = match.group(key) |
|
3537
73b5bec579ba
[B] urlrewite: basic patch for i18n vtitle
Julien Jehannet <julien.jehannet@logilab.fr>
parents:
2748
diff
changeset
|
178 |
if "vtitle" in form2: |
3592
4c08780e54ed
[i18n] msgid tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3537
diff
changeset
|
179 |
form2['vtitle'] = req.__(form2['vtitle']) |
0 | 180 |
if form2: |
181 |
req.form.update(form2) |
|
182 |
return controller, rset |
|
183 |
return do_build_rset |
|
184 |
||
185 |
||
186 |
class SchemaBasedRewriter(URLRewriter): |
|
187 |
"""Here, the rules dict maps regexps or plain strings to |
|
188 |
callbacks that will be called with (input, uri, req, schema) |
|
189 |
""" |
|
190 |
id = 'schemabased' |
|
191 |
rules = [ |
|
192 |
# rgxp : callback |
|
193 |
(rgx('/search/(.+)'), build_rset(rql=r'Any X WHERE X has_text %(text)s', |
|
1433 | 194 |
rgxgroups=[('text', 1)])), |
0 | 195 |
] |
196 |
||
197 |
def rewrite(self, req, uri): |
|
198 |
# XXX this could be refacted with SimpleReqRewriter |
|
199 |
for data in self.rules: |
|
200 |
try: |
|
201 |
inputurl, callback, required_groups = data |
|
202 |
except ValueError: |
|
203 |
inputurl, callback = data |
|
204 |
required_groups = None |
|
205 |
if required_groups and not req.user.matching_groups(required_groups): |
|
206 |
continue |
|
207 |
if isinstance(inputurl, basestring): |
|
208 |
if inputurl == uri: |
|
209 |
return callback(inputurl, uri, req, self.schema) |
|
210 |
elif inputurl.match(uri): # it's a regexp |
|
211 |
return callback(inputurl, uri, req, self.schema) |
|
212 |
else: |
|
213 |
self.debug("no schemabased rewrite rule found for %s", uri) |
|
214 |
raise KeyError(uri) |