Skip to content

Commit 5792e2b

Browse files
committed
add common files
1 parent a0ebce7 commit 5792e2b

6 files changed

Lines changed: 416 additions & 0 deletions

File tree

bigbang/api/controller/base.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class APIBase(object):
2+
def __init__(self, **kwargs):
3+
for field in self.fields:
4+
if field in kwargs:
5+
value = kwargs[field]
6+
setattr(self, field, value)
7+
8+
def __setattr__(self, field, value):
9+
if field in self.fields:
10+
validator = self.fields[field]['validate']
11+
kwargs = self.fields[field].get('validate_args', {})
12+
value = validator(value, **kwargs)
13+
super(APIBase, self).__setattr__(field, value)
14+
15+
def as_dict(self):
16+
"""Render this object as a dict of its fields."""
17+
return {f: getattr(self, f)
18+
for f in self.fields
19+
if hasattr(self, f)}
20+
21+
def __json__(self):
22+
return self.as_dict()
23+
24+
def unset_fields_except(self, except_list=None):
25+
"""Unset fields so they don't appear in the message body.
26+
27+
:param except_list: A list of fields that won't be touched.
28+
29+
"""
30+
if except_list is None:
31+
except_list = []
32+
33+
for k in self.as_dict():
34+
if k not in except_list:
35+
setattr(self, k, None)

bigbang/api/controller/link.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import pecan
2+
3+
from bigbang.api.controllers import base
4+
from bigbang.api.controllers import types
5+
6+
7+
def build_url(resource, resource_args, bookmark=False, base_url=None):
8+
if base_url is None:
9+
base_url = pecan.request.host_url
10+
11+
template = '%(url)s/%(res)s' if bookmark else '%(url)s/v1/%(res)s'
12+
# FIXME(lucasagomes): I'm getting a 404 when doing a GET on
13+
# a nested resource that the URL ends with a '/'.
14+
# https://groups.google.com/forum/#!topic/pecan-dev/QfSeviLg5qs
15+
template += '%(args)s' if resource_args.startswith('?') else '/%(args)s'
16+
return template % {'url': base_url, 'res': resource, 'args': resource_args}
17+
18+
19+
class Link(base.APIBase):
20+
"""A link representation."""
21+
22+
fields = {
23+
'href': {
24+
'validate': types.Text.validate
25+
},
26+
'rel': {
27+
'validate': types.Text.validate
28+
},
29+
'type': {
30+
'validate': types.Text.validate
31+
},
32+
}
33+
34+
@staticmethod
35+
def make_link(rel_name, url, resource, resource_args,
36+
bookmark=False, type=None):
37+
href = build_url(resource, resource_args,
38+
bookmark=bookmark, base_url=url)
39+
if type is None:
40+
return Link(href=href, rel=rel_name)
41+
else:
42+
return Link(href=href, rel=rel_name, type=type)
43+
44+
@classmethod
45+
def sample(cls):
46+
sample = cls(href="http://localhost:8080/containers/"
47+
"eaaca217-e7d8-47b4-bb41-3f99f20eed89",
48+
rel="bookmark")
49+
return sample

bigbang/api/controller/root.py

Whitespace-only changes.

0 commit comments

Comments
 (0)