Example #1
0
class GetCountryCode(object):
    """Get Country code from string."""

    # dependiencies, country package
    _countries = countries
    _get = safe(countries.get)

    @safe
    def __call__(self, code: str) -> dict:
        """Find country by code or name."""
        code = str(code).strip()
        country = self._countries.get(alpha_2=code.upper())
        country = country or self._countries.get(alpha_3=code.upper())
        country = country or self._countries.get(numeric=code.zfill(3))
        country = country or self._countries.get(name=code)
        country = country or self._countries.get(official_name=code)

        if not country:
            raise ValueError(
                '{message}({country})'.format(
                    message='Could not find country matching value',
                    country=code,
                ), )

        return {
            ALPHA_TWO: country.alpha_2.upper(),
            ALPHA_THREE: country.alpha_3.upper(),
            NAME: country.name,
            NUMERIC: country.numeric,
            OFFICIAL_NAME: self._get_official_name(country).value_or(None),
        }

    @safe
    def _get_official_name(self, country) -> str:
        return country.official_name
Example #2
0
def main():
    """Run kaiba with given args."""
    args = parse_args()

    configuration = read_file(
        args.configuration,
        'r',
    ).bind(safe(simplejson.loads), ).alt(on_failure).unwrap()

    input_data = read_file(
        args.input,
        'r',
    ).bind(safe(simplejson.loads), ).alt(on_failure).unwrap()

    Process()(
        input_data,
        configuration,
    ).bind(safe(simplejson.dumps), ).bind(
        partial(write_file, file_path=args.output), ).alt(on_failure)
Example #3
0
def _fetch_post(
    post_id: int,
) -> RequiresContextFutureResultE[_Post, httpx.AsyncClient]:
    context: RequiresContextFutureResultE[
        httpx.AsyncClient,
        httpx.AsyncClient,
    ] = RequiresContextFutureResultE.ask()

    return context.bind_future_result(
        lambda client: future_safe(client.get)(_URL.format(post_id)),
    ).bind_result(
        safe(tap(httpx.Response.raise_for_status)),
    ).map(
        lambda response: cast(_Post, response.json()),  # or validate it
    )
Example #4
0
    def __init__(self, data: 'data.<class>'):
        print_info = config.api.print_info()

        # Tries to access splitpoint attribute in the data instance
        # If it fails, fix it by calling the read_invis() function
        # Either way, the Success result is inside the Result monad, so unwrap() it
        safe_func: 'func[Result[int]]' = safe(lambda: data.splitpoint)
        splitpoint: int = safe_func().lash(
            lambda _: Success(files.read_invis(data))
        ).unwrap()

        # splitpoint == number of artists
        # Each artist has 3 previews, so the total number of pics is
        # splitpoint * 3 + splitpoint == splitpoint * 4
        self.orders = pure.generate_orders(splitpoint * 4, splitpoint)

        # TODO: Cannot merge yet because generate_users() goes to a new terminal page for every row
        if config.api.use_ueberzug():
            self.generator = generate_users_ueberzug(data.download_path, print_info)
        else:
            self.generator = generate_users(data.download_path, print_info)
        super().__init__()
Example #5
0
def handle_attribute(
    collection: Union[Dict[str, Any], List[Any]],
    cfg: Attribute,
) -> ResultE[AnyType]:
    """Handle one attribute with data fetchers, ifs, casting and default value.

    flow description:

    Fetch once for all data in Attribute.data_fetchers ->
    Apply separator to values if there are more than 1
    Failure -> fix to Success(None)
    Apply if statements
    Success -> Cast Value
    Failure -> apply default value

    Return Result
    """
    fetched_values = [
        fetched.unwrap() for fetched in  # noqa: WPS361
        [
            handle_data_fetcher(collection, data_fetcher)
            for data_fetcher in cfg.data_fetchers
        ] if is_successful(fetched)
    ]

    # partially declare if statement and casting functions
    ifs = partial(apply_if_statements, statements=cfg.if_statements)

    cast = safe(lambda the_value: the_value)
    if cfg.casting:
        cast = partial(apply_casting, casting=cfg.casting)

    return flow(
        apply_separator(fetched_values, separator=cfg.separator),
        fix(lambda _: None),  # type: ignore
        bind(ifs),
        bind(cast),
        rescue(lambda _: apply_default(default=cfg.default), ),
    )
Example #6
0
import json
import os

from attr import dataclass
from jsonschema import Draft7Validator
from returns.result import Failure, ResultE, Success, safe
from typing_extensions import Final, final

from piri.common import ReadLocalFile

SCHEMA: Final[dict] = ReadLocalFile()(
    '{0}/schema.json'.format(os.path.dirname(__file__)),
    'r',
).bind(safe(json.loads)).unwrap()


@final
@dataclass(frozen=True, slots=True)
class SchemaValidator(object):
    """Validates data with given JsonSchema Validator."""

    validator: Draft7Validator = Draft7Validator(SCHEMA)

    def __call__(
        self,
        input_data: dict,
    ) -> ResultE[dict]:
        """If is valid return success(input_data) otherwise list of errors."""
        if self.validator.is_valid(input_data):
            return Success(input_data)
Example #7
0
def schema():
    """Get the schema."""
    return ReadLocalFile()('piri/schema.json',
                           'r').bind(safe(json.loads), ).unwrap()