~homeworkprod/byceps

ref: 90357856fb25b54d9e60125d1b658be3514449ae byceps/scripts/_validators.py -rw-r--r-- 2.1 KiB
90357856 — Jochen Kupperschmidt Prepare login-based test with frozen time for Flask v2.x, Werkzeug v2.x 5 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""
byceps.scripts.validators
~~~~~~~~~~~~~~~~~~~~~~~~~

Validators for use with Click_.

.. _Click: https://click.palletsprojects.com/

:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""

from uuid import UUID

import click

from byceps.services.brand.transfer.models import Brand
from byceps.services.brand import service as brand_service
from byceps.services.party.transfer.models import Party
from byceps.services.party import service as party_service
from byceps.services.site.transfer.models import Site, SiteID
from byceps.services.site import service as site_service
from byceps.services.user.dbmodels.user import User as DbUser
from byceps.services.user import service as user_service
from byceps.services.user.transfer.models import User
from byceps.typing import BrandID, PartyID, UserID


def validate_brand(ctx, param, brand_id: BrandID) -> Brand:
    brand = brand_service.find_brand(brand_id)

    if not brand:
        raise click.BadParameter(f'Unknown brand ID "{brand_id}".')

    return brand


def validate_party(ctx, param, party_id: PartyID) -> Party:
    party = party_service.find_party(party_id)

    if not party:
        raise click.BadParameter(f'Unknown party ID "{party_id}".')

    return party


def validate_site(ctx, param, site_id: SiteID) -> Site:
    site = site_service.find_site(site_id)

    if not site:
        raise click.BadParameter(f'Unknown site ID "{site_id}".')

    return site


def validate_user_id(ctx, param, user_id: UserID) -> User:
    user_id = validate_user_id_format(ctx, param, user_id)

    user = user_service.find_user(user_id)

    if not user:
        raise click.BadParameter(f'Unknown user ID "{user_id}".')

    return user


def validate_user_id_format(ctx, param, user_id: UserID) -> UserID:
    try:
        return UUID(user_id)
    except ValueError as e:
        raise click.BadParameter(f'Invalid user ID "{user_id}": {e}')


def validate_user_screen_name(ctx, param, screen_name: str) -> DbUser:
    user = user_service.find_user_by_screen_name(screen_name)

    if not user:
        raise click.BadParameter(f'Unknown user screen name "{screen_name}".')

    return user