datapungibea 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,93 @@
1
+ r'''
2
+ Code snippet generation for reproducing queries with requests directly.
3
+ Simplified to always use environment variable pattern.
4
+ '''
5
+
6
+ import json
7
+ import logging
8
+ from textwrap import dedent
9
+ from typing import Any, Dict, Optional
10
+
11
+ import pyperclip
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class transformIncludeCodeSnippet:
17
+ def transformIncludeCodeSnippet(
18
+ self,
19
+ query: Dict[str, Any],
20
+ baseRequest: Dict[str, Any],
21
+ pandasCode: str = "",
22
+ ) -> str:
23
+ '''
24
+ Generate a reproducible code snippet for a query.
25
+
26
+ Always generates code that uses environment variable pattern:
27
+ import os
28
+ key = os.getenv("API_KEY_BEA")
29
+
30
+ Args:
31
+ query: the query dict with url and params
32
+ baseRequest: the base request dict
33
+ pandasCode: additional pandas code for data transformation
34
+
35
+ Returns:
36
+ Complete Python code string that reproduces the query
37
+ '''
38
+ apiCode = self.getApiCode(query)
39
+ queryCode = self.getQueryCode(query, baseRequest, pandasCode)
40
+ return apiCode + queryCode
41
+
42
+ def getQueryCode(self, query: Dict[str, Any], baseRequest: Dict[str, Any], pandasCode: str = "") -> str:
43
+ '''
44
+ Generate the query execution code.
45
+ '''
46
+ queryClean = {'url': query['url'], 'params': query['params']}
47
+ queryClean['url'] = 'url'
48
+
49
+ # Replace API key with variable
50
+ if 'UserID' in queryClean['params'] and 'UserID' in baseRequest.get('params', {}):
51
+ queryClean['params']['UserID'] = '{}'
52
+
53
+ queryCode = dedent('''\
54
+ query = {}
55
+ retrivedData = requests.get(**query)
56
+
57
+ {} # replace json by xml if this is the request format
58
+ ''').format(json.dumps(queryClean), pandasCode)
59
+
60
+ queryCode = queryCode.replace('"url": "url"', '"url": url')
61
+ queryCode = queryCode.replace('"UserID": "{}"', '"UserID": key')
62
+
63
+ return queryCode
64
+
65
+ def getApiCode(self, query: Dict[str, Any]) -> str:
66
+ '''
67
+ Generate the API setup code using environment variable pattern.
68
+ '''
69
+ url = query.get('url', 'https://apps.bea.gov/api/data/')
70
+
71
+ code = dedent('''\
72
+ import requests
73
+ import os
74
+ import pandas as pd
75
+
76
+ url = "{url}"
77
+ key = os.getenv("API_KEY_BEA")
78
+ ''').format(url=url)
79
+
80
+ return code
81
+
82
+ def clipcode(self, lastLoad: Dict[str, Any]) -> None:
83
+ r'''
84
+ Copy the string to the user's clipboard
85
+ '''
86
+ try:
87
+ pyperclip.copy(lastLoad['code'])
88
+ logger.info("Code copied to clipboard")
89
+ except (KeyError, TypeError):
90
+ logger.warning(
91
+ "Loaded session does not have a code entry. "
92
+ "Re-run with verbose option set to True, e.g.: data.NIPA(..., verbose=True)"
93
+ )