|
1 | | - |
2 | | -from json import JSONDecodeError |
3 | 1 | import logging |
| 2 | +import requests |
| 3 | +from urllib import parse |
| 4 | +from contentstack import Error |
| 5 | +from json import JSONDecodeError |
| 6 | +from requests.exceptions import Timeout |
4 | 7 |
|
5 | 8 |
|
6 | | -class HTTPConnection: |
| 9 | +class HTTPConnection(object): |
7 | 10 |
|
8 | 11 | def __init__(self, url: str, query: dict, headers: dict): |
9 | | - |
10 | | - if url is not None and query is not None and headers is not None: |
| 12 | + if None not in (url, query, headers): |
11 | 13 | self.url = url |
12 | 14 | self.query = query |
13 | 15 | self.headers = headers |
14 | 16 | else: |
15 | | - raise TypeError('Kindly provide valid Arguments') |
| 17 | + raise ValueError('Kindly provide valid Arguments') |
16 | 18 |
|
17 | 19 | def get_result(self, url: str, query: dict, headers: dict): |
18 | 20 |
|
19 | | - import requests |
20 | | - from urllib import parse |
21 | | - from requests import Response |
22 | | - from contentstack.stack import SyncResult |
23 | | - from contentstack import Error |
| 21 | + """ |
| 22 | + get Results is helpful to make HTTP methods |
| 23 | + :param url: |
| 24 | + :param query: |
| 25 | + :param headers: |
| 26 | + :return: |
| 27 | + """ |
24 | 28 |
|
25 | | - if url is not None and len(url) > 0: |
26 | | - self.url = url |
27 | | - if query is not None and len(query) > 0: |
28 | | - self.query = query |
29 | | - if headers is not None and len(headers) > 0: |
30 | | - self.headers = headers |
| 29 | + if None not in (url, query, headers): |
| 30 | + if len(url) > 0 and len(headers) > 0: |
| 31 | + self.url = url |
| 32 | + self.query = query |
| 33 | + self.headers = headers |
| 34 | + else: |
| 35 | + raise ValueError('Kindly provide a valid input') |
31 | 36 |
|
32 | | - # Adding user agent to headers |
| 37 | + # Headers from locale |
33 | 38 | self.headers.update(self.__user_agents()) |
34 | 39 | payload = parse.urlencode(query=self.query, encoding='UTF-8') |
35 | | - |
36 | 40 | try: |
37 | | - # requesting for url, payload and headers |
38 | | - response: Response = requests.get(self.url, params=payload, headers=self.headers) |
39 | | - # if response.status_code = 200 |
40 | | - # logging.info('Request url :: -> ', response.url) |
41 | | - if response.ok: |
42 | | - |
43 | | - # Decode byte response to json |
44 | | - result = response.json() |
45 | | - logging.info('url={}\nresponse={}'.format(response.url, result)) |
46 | | - # If result contains stack, return json response |
47 | | - if 'stack' in result: |
48 | | - return result['stack'] |
49 | | - # If result contains entry, return Entry |
50 | | - if 'entry' in result: |
51 | | - dict_entry = result['entry'] |
52 | | - return self.__parse_entries(dict_entry) |
53 | | - # If result contains entries, return list[Entry] |
54 | | - if 'entries' in result: |
55 | | - entry_list = result['entries'] |
56 | | - return self.__parse_entries(entry_list) |
57 | | - # If result contains asset, return Asset |
58 | | - if 'asset' in result: |
59 | | - dict_asset = result['asset'] |
60 | | - return self.__parse_assets(dict_asset) |
61 | | - # If result contains assets, return list[Asset] |
62 | | - if 'assets' in result: |
63 | | - asset_list = result['assets'] |
64 | | - return self.__parse_assets(asset_list) |
65 | | - # If result contains content_type,return content_type json |
66 | | - if 'content_type' in result: |
67 | | - return result['content_type'] |
68 | | - # If result contains content_types,return content_types json |
69 | | - if 'content_types' in result: |
70 | | - return result['content_types'] |
71 | | - # If result contains items, return SyncResult json |
72 | | - if 'items' in result: |
73 | | - sync_result = SyncResult().configure(result) |
74 | | - return sync_result |
| 41 | + response = requests.get(self.url, verify=True, timeout=(2, 5), params=payload, headers=self.headers) |
| 42 | + if response.status_code == 200: |
| 43 | + # Check if json dictionary is valid decode and parse the dictionary |
| 44 | + if response.raise_for_status() is None: |
| 45 | + return self.__parse_dict(response) |
75 | 46 | else: |
76 | | - # Decode byte response to json |
| 47 | + # It helps to set Error object to return with Error Message and Error Code |
77 | 48 | err = response.json() |
78 | 49 | if err is not None: |
79 | 50 | return Error().config(err) |
80 | | - |
81 | | - except requests.RequestException as err: |
82 | | - if isinstance(err, ConnectionError): |
83 | | - raise ConnectionError(err) |
| 51 | + except Timeout: |
| 52 | + raise TimeoutError('The request timed out') |
| 53 | + except ConnectionError: |
| 54 | + raise ConnectionError('Connection error occurred') |
84 | 55 | except JSONDecodeError: |
85 | | - raise ValueError("Inappropriate response") |
| 56 | + raise JSONDecodeError('Invalid JSON in request') |
| 57 | + |
| 58 | + def __parse_dict(self, response): |
| 59 | + # This is the private method to parse the response to their respective type |
| 60 | + from contentstack.stack import SyncResult |
| 61 | + # Decode byte response to json |
| 62 | + result = response.json() |
| 63 | + logging.info('url={}\nresponse={}'.format(response.url, result)) |
| 64 | + |
| 65 | + # If result contains stack, return json response |
| 66 | + if 'stack' in result: |
| 67 | + return result['stack'] |
| 68 | + # If result contains entry, return Entry |
| 69 | + if 'entry' in result: |
| 70 | + dict_entry = result['entry'] |
| 71 | + return self.__parse_entries(dict_entry) |
| 72 | + # If result contains entries, return list[Entry] |
| 73 | + if 'entries' in result: |
| 74 | + entry_list = result['entries'] |
| 75 | + return self.__parse_entries(entry_list) |
| 76 | + # If result contains asset, return Asset |
| 77 | + if 'asset' in result: |
| 78 | + dict_asset = result['asset'] |
| 79 | + return self.__parse_assets(dict_asset) |
| 80 | + # If result contains assets, return list[Asset] |
| 81 | + if 'assets' in result: |
| 82 | + asset_list = result['assets'] |
| 83 | + return self.__parse_assets(asset_list) |
| 84 | + # If result contains content_type,return content_type json |
| 85 | + if 'content_type' in result: |
| 86 | + return result['content_type'] |
| 87 | + # If result contains content_types,return content_types json |
| 88 | + if 'content_types' in result: |
| 89 | + return result['content_types'] |
| 90 | + # If result contains items, return SyncResult json |
| 91 | + if 'items' in result: |
| 92 | + sync_result = SyncResult().configure(result) |
| 93 | + return sync_result |
| 94 | + |
| 95 | + return None |
86 | 96 |
|
87 | 97 | @staticmethod |
88 | 98 | def __parse_entries(result): |
@@ -143,9 +153,13 @@ def __user_agents() -> dict: |
143 | 153 | local_headers = {'X-User-Agent': str(header), "Content-Type": 'application/json'} |
144 | 154 | return local_headers |
145 | 155 |
|
146 | | - # def is_json(self, myjson): |
147 | | - # try: |
148 | | - # json.loads(myjson.json()) |
149 | | - # return True |
150 | | - # except JSONDecodeError: |
151 | | - # return False |
| 156 | + import json |
| 157 | + |
| 158 | + @staticmethod |
| 159 | + def is_valid_json(json_string): |
| 160 | + import json |
| 161 | + try: |
| 162 | + json_object = json.loads(json_string) |
| 163 | + except ValueError as e: |
| 164 | + return False |
| 165 | + return True |
0 commit comments