|
| 1 | +import requests |
| 2 | +import pyodata |
| 3 | + |
| 4 | +SERVICE_URL = 'https://ws.parlament.ch/odata.svc/' |
| 5 | + |
| 6 | + |
| 7 | +class SwissParlClient(object): |
| 8 | + def __init__(self, session=None): |
| 9 | + if not session: |
| 10 | + session = requests.Session() |
| 11 | + self.client = pyodata.Client(SERVICE_URL, session) |
| 12 | + self.cache = {} |
| 13 | + self.get_overview() |
| 14 | + |
| 15 | + def get_tables(self): |
| 16 | + if self.cache: |
| 17 | + return self.cache.keys() |
| 18 | + return [es.name for es in self.client.schema.entity_sets] |
| 19 | + |
| 20 | + def get_variables(self, table): |
| 21 | + if self.cache and table in self.cache: |
| 22 | + return self.cache[table] |
| 23 | + return [p.name for p in self.client.schema.entity_type(table).proprties()] |
| 24 | + |
| 25 | + def get_overview(self): |
| 26 | + if self.cache: |
| 27 | + return self.cache |
| 28 | + self.cache = {} |
| 29 | + for t in self.get_tables(): |
| 30 | + self.cache[t] = self.get_variables(t) |
| 31 | + return self.cache |
| 32 | + |
| 33 | + def get_glimpse(self, table, rows=5): |
| 34 | + entities = self._get_entities(table) |
| 35 | + return SwissParlResponse( |
| 36 | + entities.top(rows).count(inline=True), |
| 37 | + self.get_variables(table) |
| 38 | + ) |
| 39 | + |
| 40 | + def get_data(self, table, **kwargs): |
| 41 | + entities = self._get_entities(table) |
| 42 | + return SwissParlResponse( |
| 43 | + entities.count(inline=True).filter(**kwargs), |
| 44 | + self.get_variables(table) |
| 45 | + ) |
| 46 | + |
| 47 | + def _get_entities(self, table): |
| 48 | + return getattr(self.client.entity_sets, table).get_entities() |
| 49 | + |
| 50 | + |
| 51 | +class SwissParlResponse(object): |
| 52 | + def __init__(self, entity_request, variables): |
| 53 | + self.entities = entity_request.execute() |
| 54 | + self.count = self.entities.total_count |
| 55 | + self.variables = variables |
| 56 | + |
| 57 | + self.data = [] |
| 58 | + self._setup_proxies() |
| 59 | + |
| 60 | + |
| 61 | + def _setup_proxies(self): |
| 62 | + for e in self.entities: |
| 63 | + row = {k: SwissParlDataProxy(e, k) for k in self.variables} |
| 64 | + self.data.append(row) |
| 65 | + |
| 66 | + def __len__(self): |
| 67 | + return self.count |
| 68 | + |
| 69 | + def __iter__(self): |
| 70 | + for row in self.data: |
| 71 | + yield {k: v() for k,v in row.items()} |
| 72 | + |
| 73 | + def __getitem__(self, key): |
| 74 | + items = self.data[key] |
| 75 | + if isinstance(key, slice): |
| 76 | + return [{k: v() for k,v in i.items()} for i in items] |
| 77 | + return {k: v() for k,v in items.items()} |
| 78 | + |
| 79 | + |
| 80 | +class SwissParlDataProxy(object): |
| 81 | + def __init__(self, proxy, attribute): |
| 82 | + self.proxy = proxy |
| 83 | + self.attribute = attribute |
| 84 | + |
| 85 | + def __call__(self): |
| 86 | + return getattr(self.proxy, self.attribute) |
0 commit comments