Exemplo n.º 1
0
    def get_astronomy(self, q, dt):
        """Does a GET request to /astronomy.json.

        Return Location and Astronomy Object

        Args:
            q (string): Pass US Zipcode, UK Postcode, Canada Postalcode, IP
                address, Latitude/Longitude (decimal degree) or city name.
                Visit [request parameter
                section](https://www.weatherapi.com/docs/#intro-request) to
                learn more.
            dt (date): Date on or after 1st Jan, 2015 in yyyy-MM-dd format

        Returns:
            AstronomyJsonResponse: Response from the API. Ok

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """

        # Prepare query URL
        _url_path = '/astronomy.json'
        _query_builder = Configuration.base_uri
        _query_builder += _url_path
        _query_parameters = {'q': q, 'dt': dt}
        _query_builder = APIHelper.append_url_with_query_parameters(
            _query_builder, _query_parameters,
            Configuration.array_serialization)
        _query_url = APIHelper.clean_url(_query_builder)

        # Prepare headers
        _headers = {'accept': 'application/json'}

        # Prepare and execute request
        _request = self.http_client.get(_query_url, headers=_headers)
        CustomQueryAuth.apply(_request)
        _context = self.execute_request(_request)

        # Endpoint and global error handling using HTTP status codes.
        if _context.response.status_code == 400:
            raise APIException(
                'Error code 1003: Parameter \'q\' not provided.Error code 1005: API request url is invalid.Error code 1006: No location found matching parameter \'q\'Error code 9999: Internal application error.',
                _context)
        elif _context.response.status_code == 401:
            raise APIException(
                'Error code 1002: API key not provided.Error code 2006: API key provided is invalid',
                _context)
        elif _context.response.status_code == 403:
            raise APIException(
                'Error code 2007: API key has exceeded calls per month quota.<br />Error code 2008: API key has been disabled.',
                _context)
        self.validate_response(_context)

        # Return appropriate type
        return APIHelper.json_deserialize(
            _context.response.raw_body, AstronomyJsonResponse.from_dictionary)
Exemplo n.º 2
0
    def get_ip_lookup(self, q):
        """Does a GET request to /ip.json.

        IP Lookup API method allows a user to get up to date information for
        an IP address.

        Args:
            q (string): Pass IP address.

        Returns:
            IpJsonResponse: Response from the API. Ok

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """

        # Prepare query URL
        _url_path = '/ip.json'
        _query_builder = Configuration.base_uri
        _query_builder += _url_path
        _query_parameters = {'q': q}
        _query_builder = APIHelper.append_url_with_query_parameters(
            _query_builder, _query_parameters,
            Configuration.array_serialization)
        _query_url = APIHelper.clean_url(_query_builder)

        # Prepare headers
        _headers = {'accept': 'application/json'}

        # Prepare and execute request
        _request = self.http_client.get(_query_url, headers=_headers)
        CustomQueryAuth.apply(_request)
        _context = self.execute_request(_request)

        # Endpoint and global error handling using HTTP status codes.
        if _context.response.status_code == 400:
            raise APIException(
                'Error code 1003: Parameter \'q\' not provided.Error code 1005: API request url is invalid.Error code 1006: No location found matching parameter \'q\'Error code 9999: Internal application error.',
                _context)
        elif _context.response.status_code == 401:
            raise APIException(
                'Error code 1002: API key not provided.Error code 2006: API key provided is invalid',
                _context)
        elif _context.response.status_code == 403:
            raise APIException(
                'Error code 2007: API key has exceeded calls per month quota.<br />Error code 2008: API key has been disabled.',
                _context)
        self.validate_response(_context)

        # Return appropriate type
        return APIHelper.json_deserialize(_context.response.raw_body,
                                          IpJsonResponse.from_dictionary)
Exemplo n.º 3
0
    def add_query_parameter(self, name, value):
        """ Add a query parameter to the HttpRequest.

        Args:
	        name (string): The name of the query parameter.
            value (string): The value of the query parameter.

        """
        self.query_url = APIHelper.append_url_with_query_parameters(
            self.query_url, {name: value})
        self.query_url = APIHelper.clean_url(self.query_url)
Exemplo n.º 4
0
    def execute_request(self, request, binary=False):
        """Executes an HttpRequest.

        Args:
            request (HttpRequest): The HttpRequest to execute.
            binary (bool): A flag which should be set to True if
                a binary response is expected.

        Returns:
            HttpContext: The HttpContext of the request. It contains,
                both, the request itself and the HttpResponse object.

        """
        # Invoke the on before request HttpCallBack if specified
        if self.http_call_back != None:
            self.http_call_back.on_before_request(request)

        # Add global headers to request
        request.headers = APIHelper.merge_dicts(self.global_headers,
                                                request.headers)

        # Invoke the API call to fetch the response.
        func = self.http_client.execute_as_binary if binary else self.http_client.execute_as_string
        response = func(request)
        context = HttpContext(request, response)

        # Invoke the on after response HttpCallBack if specified
        if self.http_call_back != None:
            self.http_call_back.on_after_response(context)

        return context
Exemplo n.º 5
0
def getWeather(place, lang):
    """
        Returns realtime weather 
    """

    #Create a client by passing the API key
    client = WeatherapiClient(key)
    ap_is_controller = client.ap_is
    #get raw data for weather
    try:
        weather = ap_is_controller.get_realtime_weather(place, lang)
    except:
        return
    #Convert response to python dictionary
    weather_info = APIHelper.to_dictionary(weather)
    return weather_info
Exemplo n.º 6
0
def getForecast(place, days):
    """
        Returns json Forecast by taking input of place anf number of days
    """

    #Create a client by passing the API key
    client = WeatherapiClient(key)
    ap_is_controller = client.ap_is
    #get forecast raw data
    try:
        forecast = ap_is_controller.get_forecast_weather(place, days)
    except:
        return
    #Convert data to python dictionary
    forecast_info = APIHelper.to_dictionary(forecast)
    return forecast_info
Exemplo n.º 7
0
    def get_forecast_weather(self,
                             q,
                             days,
                             dt=None,
                             unixdt=None,
                             hour=None,
                             lang=None):
        """Does a GET request to /forecast.json.

        Forecast weather API method returns upto next 10 day weather forecast
        and weather alert as json. The data is returned as a Forecast
        Object.<br />Forecast object contains astronomy data, day weather
        forecast and hourly interval weather information for a given city.

        Args:
            q (string): Pass US Zipcode, UK Postcode, Canada Postalcode, IP
                address, Latitude/Longitude (decimal degree) or city name.
                Visit [request parameter
                section](https://www.weatherapi.com/docs/#intro-request) to
                learn more.
            days (int): Number of days of weather forecast. Value ranges from
                1 to 10
            dt (date, optional): Date should be between today and next 10 day
                in yyyy-MM-dd format
            unixdt (int, optional): Please either pass 'dt' or 'unixdt' and
                not both in same request.<br />unixdt should be between today
                and next 10 day in Unix format
            hour (int, optional): Must be in 24 hour. For example 5 pm should
                be hour=17, 6 am as hour=6
            lang (string, optional): Returns 'condition:text' field in API in
                the desired language. Visit [request parameter
                section](https://www.weatherapi.com/docs/#intro-request) to
                check 'lang-code'.

        Returns:
            ForecastJsonResponse: Response from the API. Ok

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """

        # Prepare query URL
        _url_path = '/forecast.json'
        _query_builder = Configuration.base_uri
        _query_builder += _url_path
        _query_parameters = {
            'q': q,
            'days': days,
            'dt': dt,
            'unixdt': unixdt,
            'hour': hour,
            'lang': lang
        }
        _query_builder = APIHelper.append_url_with_query_parameters(
            _query_builder, _query_parameters,
            Configuration.array_serialization)
        _query_url = APIHelper.clean_url(_query_builder)

        # Prepare headers
        _headers = {'accept': 'application/json'}

        # Prepare and execute request
        _request = self.http_client.get(_query_url, headers=_headers)
        CustomQueryAuth.apply(_request)
        _context = self.execute_request(_request)

        # Endpoint and global error handling using HTTP status codes.
        if _context.response.status_code == 400:
            raise APIException(
                'Error code 1003: Parameter \'q\' not provided.Error code 1005: API request url is invalid.Error code 1006: No location found matching parameter \'q\'Error code 9999: Internal application error.',
                _context)
        elif _context.response.status_code == 401:
            raise APIException(
                'Error code 1002: API key not provided.Error code 2006: API key provided is invalid',
                _context)
        elif _context.response.status_code == 403:
            raise APIException(
                'Error code 2007: API key has exceeded calls per month quota.<br />Error code 2008: API key has been disabled.',
                _context)
        self.validate_response(_context)

        # Return appropriate type
        return APIHelper.json_deserialize(_context.response.raw_body,
                                          ForecastJsonResponse.from_dictionary)
Exemplo n.º 8
0
    def get_realtime_weather(self, q, lang=None):
        """Does a GET request to /current.json.

        Current weather or realtime weather API method allows a user to get up
        to date current weather information in json and xml. The data is
        returned as a Current Object.Current object contains current or
        realtime weather information for a given city.

        Args:
            q (string): Pass US Zipcode, UK Postcode, Canada Postalcode, IP
                address, Latitude/Longitude (decimal degree) or city name.
                Visit [request parameter
                section](https://www.weatherapi.com/docs/#intro-request) to
                learn more.
            lang (string, optional): Returns 'condition:text' field in API in
                the desired language. Visit [request parameter
                section](https://www.weatherapi.com/docs/#intro-request) to
                check 'lang-code'.

        Returns:
            CurrentJsonResponse: Response from the API. Ok

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """

        # Prepare query URL
        _url_path = '/current.json'
        _query_builder = Configuration.base_uri
        _query_builder += _url_path
        _query_parameters = {'q': q, 'lang': lang}
        _query_builder = APIHelper.append_url_with_query_parameters(
            _query_builder, _query_parameters,
            Configuration.array_serialization)
        _query_url = APIHelper.clean_url(_query_builder)

        # Prepare headers
        _headers = {'accept': 'application/json'}

        # Prepare and execute request
        _request = self.http_client.get(_query_url, headers=_headers)
        CustomQueryAuth.apply(_request)
        _context = self.execute_request(_request)

        # Endpoint and global error handling using HTTP status codes.
        if _context.response.status_code == 400:
            raise APIException(
                'Error code 1003: Parameter \'q\' not provided.Error code 1005: API request url is invalid.Error code 1006: No location found matching parameter \'q\'Error code 9999: Internal application error.',
                _context)
        elif _context.response.status_code == 401:
            raise APIException(
                'Error code 1002: API key not provided.Error code 2006: API key provided is invalid',
                _context)
        elif _context.response.status_code == 403:
            raise APIException(
                'Error code 2007: API key has exceeded calls per month quota.<br />Error code 2008: API key has been disabled.',
                _context)
        self.validate_response(_context)

        # Return appropriate type
        return APIHelper.json_deserialize(_context.response.raw_body,
                                          CurrentJsonResponse.from_dictionary)