|
9 | 9 | )
|
10 | 10 | from facebook_business.adobjects.abstractobject import AbstractObject
|
11 | 11 |
|
| 12 | + |
12 | 13 | class ObjectParser:
|
13 | 14 | """
|
14 | 15 | Parser for API response
|
@@ -39,30 +40,48 @@ def __init__(
|
39 | 40 | self._custom_parse_method = custom_parse_method
|
40 | 41 | self._api = api
|
41 | 42 |
|
42 |
| - def parse_single(self, response): |
| 43 | + def parse_single(self, response, override_target_class=None): |
43 | 44 | if self._custom_parse_method is not None:
|
44 | 45 | return self._custom_parse_method(response, self._api)
|
45 | 46 |
|
| 47 | + from .ad import Ad |
| 48 | + from .adpreview import AdPreview |
| 49 | + from .adset import AdSet |
| 50 | + from .campaign import Campaign |
| 51 | + |
46 | 52 | data = response
|
47 | 53 | if 'data' in response and isinstance(response['data'], dict):
|
48 | 54 | data = response['data']
|
49 | 55 | elif 'images' in response and not isinstance(data['images'], list):
|
50 | 56 | _, data = data['images'].popitem()
|
51 |
| - if 'campaigns' in data: |
52 |
| - _, data = data['campaigns'].popitem() |
53 |
| - elif 'adsets' in data: |
54 |
| - _, data = data['adsets'].popitem() |
55 |
| - elif 'ads' in data: |
56 |
| - _, data = data['ads'].popitem() |
| 57 | + |
| 58 | + subfields = ( |
| 59 | + ('campaigns', Campaign), |
| 60 | + ('adsets', AdSet), |
| 61 | + ('ads', Ad), |
| 62 | + ('previews', AdPreview), |
| 63 | + ) |
| 64 | + for subfield, _class in subfields: |
| 65 | + if subfield not in data: |
| 66 | + continue |
| 67 | + |
| 68 | + data[subfield] = [ |
| 69 | + self.parse_single( |
| 70 | + item, override_target_class=_class |
| 71 | + ) for item in data[subfield]['data'] |
| 72 | + ] |
| 73 | + |
57 | 74 | if 'success' in data:
|
58 | 75 | del data['success']
|
59 | 76 |
|
| 77 | + target_class = override_target_class or self._target_class |
| 78 | + |
60 | 79 | if self._reuse_object is not None:
|
61 | 80 | self._reuse_object._set_data(data)
|
62 | 81 | return self._reuse_object
|
63 | 82 | elif self._target_class is not None:
|
64 | 83 | return AbstractObject.create_object(self._api, data,
|
65 |
| - self._target_class) |
| 84 | + target_class) |
66 | 85 | else:
|
67 | 86 | raise FacebookBadObjectError(
|
68 | 87 | 'Must specify either target class calling object' +
|
|
0 commit comments