|
1 | 1 | # -*- coding: utf-8 -*- |
2 | 2 |
|
3 | 3 | import pprint |
4 | | -from .exceptions import NoSessionError, ModelNotFoundError, APIError |
| 4 | +try: # py3 |
| 5 | + from io import StringIO |
| 6 | +except ImportError: # py2 |
| 7 | + from StringIO import StringIO |
| 8 | +from .exceptions import ( |
| 9 | + NoSessionError, |
| 10 | + ModelNotFoundError, |
| 11 | + APIError, |
| 12 | + ReportNotReadyError, |
| 13 | + NoPandasInstalledError, |
| 14 | +) |
5 | 15 |
|
6 | 16 | __all__ = ['Advertiser', 'Bidder', 'Browser', 'Campaign', 'Category', 'ConnectionType', |
7 | 17 | 'ConversionPixel', 'Country', 'Creative', 'Datacenter', 'DeviceType', |
@@ -94,3 +104,45 @@ def reload(self, session=None): |
94 | 104 |
|
95 | 105 | for m in __all__: |
96 | 106 | locals()[m] = type(m, (AtomxModel,), {}) |
| 107 | + |
| 108 | + |
| 109 | +class Report(object): |
| 110 | + def __init__(self, session, id, fast, status, lines, query, **kwargs): |
| 111 | + self.session = session |
| 112 | + self.id = id |
| 113 | + self.fast = fast |
| 114 | + self.status = status |
| 115 | + self.lines = lines |
| 116 | + self.query = query |
| 117 | + |
| 118 | + @property |
| 119 | + def is_ready(self): |
| 120 | + if hasattr(self, '_is_ready'): |
| 121 | + return self._is_ready |
| 122 | + report_status = self.session.report_status(self) |
| 123 | + self.status = report_status['status'] |
| 124 | + self.lines = report_status['lines'] |
| 125 | + if self.status == 'SUCCESS': |
| 126 | + setattr(self, '_is_ready', True) |
| 127 | + return True |
| 128 | + elif self.status == 'ERROR': |
| 129 | + setattr(self, '_is_ready', True) |
| 130 | + return False |
| 131 | + |
| 132 | + @property |
| 133 | + def content(self): |
| 134 | + if not self.is_ready: |
| 135 | + raise ReportNotReadyError() |
| 136 | + return self.session.report_get(self) |
| 137 | + |
| 138 | + @property |
| 139 | + def pandas(self): |
| 140 | + try: |
| 141 | + import pandas as pd |
| 142 | + except ImportError: |
| 143 | + raise NoPandasInstalledError('To get the report as a pandas dataframe you ' |
| 144 | + 'have to have pandas installed. ' |
| 145 | + 'Do `pip install pandas` in your command line.') |
| 146 | + |
| 147 | + return pd.read_csv(StringIO(self.content), |
| 148 | + names=self.query.get('groups', []) + self.query.get('sums', [])) |
0 commit comments