1+ import copy
12import json
23import os
34from dataclasses import dataclass
45from urllib .request import urlopen , Request
56import urllib .parse
67import urllib .error
7- from typing import Dict , Optional
8+ from typing import Optional
89
910import solcast
1011
@@ -24,10 +25,11 @@ class Response:
2425 url : str
2526 data : Optional [bytes ]
2627 success : bool
28+ method : str
2729 exception : Optional [str ] = None
2830
2931 def __repr__ (self ):
30- return f"status code={ self .code } , url={ self .url } "
32+ return f"status code={ self .code } , url={ self .url } , method= { self . method } "
3133
3234 def to_dict (self ):
3335 if self .code != 200 :
@@ -78,22 +80,26 @@ def __init__(self, base_url: str, endpoint: str):
7880 self .url = self .make_url ()
7981
8082 @staticmethod
81- def check_params (params : dict ) -> (dict , str ):
82- """runs some basic checks on the parameters that will be passed in the
83- GET request."""
83+ def _check_params (params : dict ) -> (dict , str ):
84+ """Run basic checks on the parameters that will be passed to the HTTP request."""
8485 assert isinstance (params , dict ), "parameters needs to be a dict"
86+ params = copy .deepcopy (params )
8587
86- if "api_key" not in params :
87- params .update ({"api_key" : os .getenv ("SOLCAST_API_KEY" )})
88+ if "api_key" in params :
89+ # api key in the header for secrecy
90+ key = params ["api_key" ]
91+ del params ["api_key" ]
92+ else :
93+ key = os .getenv ("SOLCAST_API_KEY" )
8894
89- if params [ "api_key" ] is None :
95+ if key is None :
9096 raise ValueError (
9197 "no API key provided. Either set it as an environment "
9298 "variable SOLCAST_API_KEY, or provide `api_key` "
9399 "as an argument. Visit https://solcast.com to get an API key."
94100 )
95101
96- if len (params [ "api_key" ] ) <= 1 :
102+ if len (key ) <= 1 :
97103 raise ValueError ("API key is too short." )
98104
99105 if "output_parameters" in params .keys () and isinstance (
@@ -109,18 +115,15 @@ def check_params(params: dict) -> (dict, str):
109115
110116 # only json supported
111117 if "format" in params .keys ():
112- assert (
113- params ["format" ] == "json"
114- ), "only json response format is currently supported."
115-
116- # api key in the header for secrecy
117- key = params ["api_key" ]
118- del params ["api_key" ]
118+ if params ["format" ] != "json" :
119+ raise NotImplementedError (
120+ "Only json response format is currently supported."
121+ )
119122
120123 return params , key
121124
122125 def make_url (self ) -> str :
123- """composes the full URL."""
126+ """Compose the full URL."""
124127 return "/" .join ([self .base_url , self .endpoint ])
125128
126129 def get (self , params : dict ) -> Response :
@@ -183,7 +186,7 @@ def delete(self, params: dict) -> Response:
183186 """
184187 return self ._make_request (params , method = "DELETE" )
185188
186- def _make_request (self , params : Dict , method : str ) -> Response :
189+ def _make_request (self , params : dict , method : str ) -> Response :
187190 """Make a request using urllib with the HTTP method specified
188191
189192 Args:
@@ -194,7 +197,7 @@ def _make_request(self, params: Dict, method: str) -> Response:
194197 a Response object.
195198 """
196199
197- params , key = self .check_params (params )
200+ params , key = self ._check_params (params )
198201 url = self .url + "?" + urllib .parse .urlencode (params )
199202 req = Request (
200203 url ,
@@ -205,7 +208,12 @@ def _make_request(self, params: Dict, method: str) -> Response:
205208 with urlopen (req ) as response :
206209 body = response .read ()
207210 return Response (
208- code = response .code , url = url , data = body , success = True , exception = None
211+ code = response .code ,
212+ url = url ,
213+ data = body ,
214+ success = True ,
215+ exception = None ,
216+ method = method ,
209217 )
210218 except urllib .error .HTTPError as e :
211219 try :
@@ -218,4 +226,5 @@ def _make_request(self, params: Dict, method: str) -> Response:
218226 data = None ,
219227 exception = exception_message ,
220228 success = False ,
229+ method = method ,
221230 )
0 commit comments