Best Python code snippet using lisa_python
data_api_accuweather.py
Source:data_api_accuweather.py
...25 '''26 initialize self._location_key for the city and country_code27 if api call fail self._location_key = ""28 '''29 self._get_location_key()30 @staticmethod31 def _parse_current_weather(response: str, units: str) -> List[DataView]:32 '''33 get a summary (date, text and temperature) dict from current weather conditions api response34 @param response: http_response from API call35 @param days: number of days to retrieve forecast data for36 @return: a dict with date, text and temperature fields37 '''38 dataviews = []39 try:40 data_view = DataView()41 conditions = json.loads(response)[0]42 data_view.text = conditions["WeatherText"]43 data_view.date = conditions["LocalObservationDateTime"].split("T")[0]44 if units == Const.METRIC:45 data_view.temperature = conditions["Temperature"]["Metric"]["Value"]46 data_view.units= conditions["Temperature"]["Metric"]["Unit"]47 if units == Const.IMPERIAL:48 data_view.temperature = conditions["Temperature"]["Imperial"]["Value"]49 data_view.units = conditions["Temperature"]["Imperial"]["Unit"]50 dataviews.append(data_view)51 except json.JSONDecodeError as json_errror:52 print(f"{json_errror}")53 except KeyError as key_error:54 print(f"{key_error}")55 return dataviews56 @staticmethod57 def _parse_forecast_weather(response: str, days: int) -> List[DataView]:58 '''59 get a summary (date, text and temperature) from forecast api response60 @param response: http_response from API call61 @param days: number of days to retrieve forecast data for62 @return: a list of dataview objects63 '''64 dataviews = []65 try:66 for forecast in json.loads(response)["DailyForecasts"][:days]:67 data_view = DataView()68 data_view.date = forecast["Date"].split("T")[0]69 data_view.text= forecast["Day"]["LongPhrase"]70 data_view.temperature = forecast["Temperature"]["Maximum"]["Value"]71 data_view.units= forecast["Temperature"]["Maximum"]["Unit"]72 dataviews.append(data_view)73 except json.JSONDecodeError as json_errror:74 print(f"{json_errror}")75 except KeyError as key_error:76 print(f"{key_error}")77 return dataviews78 @staticmethod79 def _parse_location_response(response: str) -> str:80 '''81 get the location_key to use in accweather api calls82 @param response: http_response from location API call83 @return: the location_key or "" if error84 '''85 try:86 locations = json.loads(response)87 if locations and "Key" in locations[0]:88 return locations[0]['Key']89 except json.JSONDecodeError as json_errror:90 print(f"{json_errror}")91 return ""92 def _get_location_key(self) -> None:93 '''94 set self._location_key based on instance properties city and country_code95 if api call faile self._location_key = ""96 '''97 url = f"{self._base_url}/locations/{self._api_version}/cities/{self.country_code}/search"98 query = {"apikey": self._api_key, "q": self.city}99 response = HttpRequest().simple_http_request(url, query)100 if response:101 self._location_key = DataAPIAccuweather._parse_location_response(102 response)103 def current_weather(self, units: str) -> List[DataView]:104 """105 return the current weather conditions106 @param: units for temperature : metric or imperial...
accuweather.py
Source:accuweather.py
...7class AccuWeather(WeatherService):8 def __init__(self, api_url: str, api_key: str):9 self.api_url = api_url.rstrip('/')10 self.api_key = api_key11 def _get_location_key(self, location: Location) -> str:12 response = requests.get(f'{self.api_url}/locations/v1/{location.country}/search', params={13 'apikey': self.api_key,14 'q': location.city15 })16 content = response.json()17 if response.status_code != 200:18 raise WeatherException(f"{content['Message']}", content['Code'], {19 'reference': content['Reference']20 })21 if not content:22 raise WeatherException('Unable to find the location')23 return content[0]['Key']24 def current(self, location: Location) -> Optional[WeatherData]:25 location_key = self._get_location_key(location)26 response = requests.get(f'{self.api_url}/currentconditions/v1/{location_key}', params={27 'apikey': self.api_key,28 })29 content = response.json()30 return WeatherData(31 location=location,32 date=datetime.strptime(content[0]['LocalObservationDateTime'], "%Y-%m-%dT%H:%M:%S%z"),33 description=content[0]['WeatherText'],34 temperature=Temperature(35 value=content[0]['Temperature']['Metric']['Value'],36 unit=TemperatureUnit.CELSIUS37 ),38 )39 def forecast(self, location: Location, days: int) -> Iterable[WeatherData]:40 location_key = self._get_location_key(location)41 response = requests.get(f'{self.api_url}/forecasts/v1/daily/5day/{location_key}', params={42 'apikey': self.api_key,43 'metric': True44 })45 content = response.json()46 weather = []47 for data in content.get('DailyForecasts', []):48 weather.append(WeatherData(49 location=location,50 date=datetime.strptime(data['Date'], "%Y-%m-%dT%H:%M:%S%z"),51 description=data['Day']['IconPhrase'],52 temperature=Temperature(53 value=data['Temperature']['Minimum']['Value'],54 unit=TemperatureUnit.CELSIUS...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!