コード例 #1
0
def validate_units(city: str, province: Optional[str], country: Optional[str], units: str) -> \
        Tuple[str, Optional[str], str, str]:

    city = city.lower().strip()
    if not country:
        country = "ca"
    else:
        country = country.lower().strip()

    if len(country) != 2:
        error = f"Invalid country: {country}. It must be a two letter abbreviation such as US or GB."
        raise ValidationError(status_code=400, error_msg=error)

    if province:
        province = province.strip().lower()

    if province and len(province) != 2:
        error = f"Invalid province: {province}. It must be a two letter abbreviation such as CA or KS (use for US only)."
        raise ValidationError(status_code=400, error_msg=error)

    if units:
        units = units.strip().lower()

    valid_units = {'standard', 'metric', 'imperial'}
    if units not in valid_units:
        error = f"Invalid units '{units}', it must be one of {valid_units}."
        raise ValidationError(status_code=400, error_msg=error)

    return city, province, country, units
コード例 #2
0
def validate_units(city: str, state: Optional[str], country: Optional[str],
                   units: str) -> Tuple[str, Optional[str], str, str]:
    """
  Makes sure that the city, state, country and units are valid
  """
    city = city.lower().strip()
    if not country:
        country = "us"
    else:
        country = country.lower().strip()

    if len(country) != 2:
        error = f"Invalid country: {country}. It must be a two letter abbreviation such as US or GB."
        raise ValidationError(status_code=400, error_msg=error)

    if state:
        state = state.strip().lower()

    if state and len(state) != 2:
        error = f"Invalid state: {state}. It must be a two letter abbreviation such as CA or KS (use for US only)."
        raise ValidationError(status_code=400, error_msg=error)

    if units:
        units = units.strip().lower()

    valid_units = {'standard', 'metric', 'imperial'}
    if units not in valid_units:
        error = f"Invalid units '{units}', it must be one of {valid_units}."
        raise ValidationError(status_code=400, error_msg=error)

    return city, state, country, units
コード例 #3
0
def validate_units(city: str, state: str | None, country: str,
                   units: str) -> tuple[str, str | None, str, str]:
    city = city.lower().strip()
    if not country:
        country = "us"
    else:
        country = country.lower().strip()

    if len(country) != 2:
        error_message = (f"Invalid country: {country}."
                         f" It should be two letter abbreviation such as US.")
        raise ValidationError(error_message, status_code=404)

    if state:
        state = state.lower().strip()

    if state and len(state) != 2:
        error_message = (f"Invalid state: {state}."
                         f" It should be two letter abbreviation such as CA.")
        raise ValidationError(error_message, status_code=404)

    if units:
        units = units.lower().strip()

    valid_units = {"standard", "metric", "imperial"}
    if units not in valid_units:
        error_message = (f"Invalid units: {units}."
                         f" Must be one of {valid_units}.")
        raise ValidationError(error_message, status_code=404)

    return city, state, country, units
コード例 #4
0
ファイル: helpers.py プロジェクト: NSLS-II/nsls2-api
async def _call_async_webservice(url: str):
    async with httpx.AsyncClient() as client:
        resp: Response = await client.get(url)
        if resp.status_code != 200:
            raise ValidationError(resp.text, status_code=resp.status_code)
    results = resp.json()
    return results
コード例 #5
0
async def get_current_weather(city: str, province: Optional[str], country: str,
                              units: str) -> dict:
    city, province, country, units = validate_units(city, province, country,
                                                    units)

    forecast = weather_cache.get_weather(city, province, country, units)
    if forecast:
        return forecast

    if province:
        q = f'{city},{province},{country}'
    else:
        q = f'{city},{country}'

    url = f'https://api.openweathermap.org/data/2.5/weather?q={q}&appid={api_key}&units={units}'

    async with httpx.AsyncClient() as client:
        resp: Response = await client.get(url)
        if resp.status_code != 200:
            raise ValidationError(resp.text, status_code=resp.status_code)

    data = resp.json()
    current_weather = data['main']

    weather_cache.set_weather(city, province, country, units, current_weather)
    return current_weather
コード例 #6
0
async def get_report_async(city: str, state: Optional[str], country: str,
                           units: str) -> dict:

    city, state, country, units = validate_units(city, state, country, units)

    forecast = weather_cache.get_weather(city, state, country, units)

    if forecast:
        return forecast

    if state:
        q = f"{city}, {state}, {country}"
    else:
        q = f"{city}, {country}"

    url = f"https://api.openweathermap.org/data/2.5/weather?q={q}&appid={api_key}&units={units}"

    async with httpx.AsyncClient() as client:
        resp: httpx.Response = await client.get(url)

        if resp.status_code != 200:
            raise ValidationError(resp.text, status_code=resp.status_code)

    data = resp.json()
    print(data)
    forecast = data['main']

    weather_cache.set_weather(city, state, country, units, forecast)

    return forecast
コード例 #7
0
async def __do_request(req: Request):
    backend_url = os.getenv("BACKEND_URL")
    backend_port = os.getenv("BACKEND_PORT")
    url = f"{backend_url}:{backend_port}"
    resp = None

    async with httpx.AsyncClient() as client:
        print(req.method)
        if req.method == "GET":

            resp: Response = await client.request(req.method, url)
        else:
            resp: Response = await client.request(req.method,
                                                  url,
                                                  data=req.body())
        if resp.status_code != 200:
            raise ValidationError(resp.text, status_code=resp.status_code)
    if resp:
        resp = resp.json()
    try:
        ip_cache.save_request(req, hash_request(req))
    except Exception as e:
        raise e

    return await resp
コード例 #8
0
def validate_units(city: str, state: Optional[str], country: Optional[str], units: str) -> \
        Tuple[str, Optional[str], str, str]:
    """
    Function to validate (and if needed raise errors) for provided parameters
    :param city: str, name of the city.
    :param state: (str - optional), name of the state.
    :param country: str, name of the country.
    :param units: str, unit system to use.
    :return: Tuple, modified and validated parameters
    """
    city = city.lower().strip()
    if not country:
        country = "us"
    else:
        country = country.lower().strip()

    if len(country) != 2:
        error = f"Invalid country: {country}. It must be a two letter abbreviation such as US or GB."
        raise ValidationError(status_code=400, error_message=error)

    if state:
        state = state.strip().lower()

    if state and len(state) != 2:
        error = f"Invalid state: {state}. It must be a two letter abbreviation such as CA or KS (use for US only)."
        raise ValidationError(status_code=400, error_message=error)

    if units:
        units = units.strip().lower()

    valid_units = {'standard', 'metric', 'imperial'}
    if units not in valid_units:
        error = f"Invalid units '{units}', it must be one of {valid_units}."
        raise ValidationError(status_code=400, error_message=error)

    return city, state, country, units
コード例 #9
0
    forecast: dict
    if forecast := get_weather(city, state, country, units):
        return forecast

    if state:
        q = f"{city},{state},{country}"
    else:
        q = f"{city},{country}"

    key = api_key
    url = f"http://api.openweathermap.org/data/2.5/weather?q={q}&appid={key}"

    async with httpx.AsyncClient() as client:
        resp: Response = await client.get(url)
        if resp.status_code != 200:
            raise ValidationError(resp.text, status_code=resp.status_code)

    data = resp.json()
    forecast = data['main']

    set_weather(city, state, country, units, forecast)

    return forecast


def validate_units(city: str, state: Optional[str], country: Optional[str],
                   units: str) -> Tuple[str, Optional[str], str, str]:
    """
  Makes sure that the city, state, country and units are valid
  """
    city = city.lower().strip()
コード例 #10
0
    if forecast := cache.get_weather(city, state, country, units):
        return forecast

    base_url = "https://api.openweathermap.org/data/2.5/weather"
    if state:
        query = f"{city},{state},{country}"
    else:
        query = f"{city},{country}"
    url = f"{base_url}?q={query}&appid={api_key}&units={units}"

    async with httpx.AsyncClient() as client:
        response: Response = await client.get(url)

        if response.status_code != 200:
            raise ValidationError(response.text, response.status_code)

    data = response.json()
    forecast = data["main"]

    cache.set_weather(city, state, country, units, forecast)
    return forecast


def validate_units(city: str, state: str | None, country: str,
                   units: str) -> tuple[str, str | None, str, str]:
    city = city.lower().strip()
    if not country:
        country = "us"
    else:
        country = country.lower().strip()
コード例 #11
0
def test_ValidationError():
    ve = ValidationError(error_msg="test", status_code=400)
    assert ve.status_code == 400
    assert ve.error_msg == "test"
コード例 #12
0
def validate_input(userID):
    if userID.isnumeric():
        return userID
    raise ValidationError(status_code=400,
                          error_msg="userID is invalid. Must be an integer.")