Skip to content

Instantly share code, notes, and snippets.

@lukasjuhrich
Last active October 7, 2016 15:24
Show Gist options
  • Select an option

  • Save lukasjuhrich/28d976c44fd38bfc5ca407f27632c192 to your computer and use it in GitHub Desktop.

Select an option

Save lukasjuhrich/28d976c44fd38bfc5ca407f27632c192 to your computer and use it in GitHub Desktop.
Some thoughts on column refactoring in pycroft (#52)
# pylint: disable=all
# Original idea:
@bp.route("/<int:user_id>/hosts")
def user_show_hosts_json(user_id):
list_items = []
for user_host in User.q.get(user_id).user_hosts:
# …
for ip in user_host.ips:
# use the classmethod create_json_dict:
list_items.append(UserHostsTableInfo.create_json_dict(
id=str(user_host.id),
ip=str(ip.address),
mac=ip.interface.mac,
switch=switches,
port=ports,
action=foo
**rest,
))
return jsonify(items=list_items)
# the template needs to get the url + cols:
# url_for(info.url), info.cols
# the json endpoint wants to generate something strictly following
# this scheme. This means: a valid list of dicts having some columns.
# should the json view do the work? yeah, that isn't so bad. Perhaps
# we can move it to lib tho. couldn't we abstract this into a
# higher-level lib function plus something accessing the cols dict?
# or better: can't we extract the cols from the function (coming from
# an object) creating said json content?
class UserTableInfoExtractor:
def create_one_entry(self, ip):
return {'ip': ip}
@property
def cols(self):
return self.create_one_entry(MagicMock()).keys()
# or with a namedtuple:
class UserTableInfoExtractor:
_info = namedtuple('UserHostTableInfo', ['ip'])
def create_one_entry(self, *a, **kw):
return self._info(*a, **kw)._asdict()
@property
def cols(self):
return self._info._fields
# perhaps, we don't need the entry creation after all, and directly
# use the namedtuple
# or, even better, we implement __call__() and just call
# `EserTableInfo` (naming it `extractor` doesn't really make sense)
@bp.route("/<int:user_id>/hosts")
def user_show_hosts_json(user_id):
list_items = []
for user_host in User.q.get(user_id).user_hosts:
# …
for ip in user_host.ips:
list_items.append(UserTableInfo(
id=str(user_host.id),
ip=str(ip.address),
mac=ip.interface.mac,
switch=switches,
port=ports,
action=foo
))
return jsonify(items=list_items)
# however, directly using the namedtuple is better for the linter.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment