Skip to content
kk edited this page Apr 5, 2020 · 1 revision

Scenario - Validate Request Parameters

UserSchema = T.dict(
    id=T.int,
    username=T.str,
    avatar=T.url,
    token=T.str,
)


# Option 1: Use decorator to validate request parameters and returns
# Note: You need implement the decorator for your web framework
@app.route('/api/login')
@parameters(
    username=T.str,
    password=T.str.minlen(6),
)
@returns(UserSchema)
def do_login(username, password):
    user = models.User.query(username=username)
    user.login(password)
    return user


# Option 2: Use annotation to validate request parameters and returns
# Note: You need integrate validr to your web framework
@app.route('/api/login')
def do_login(username: T.str, password: T.str.minlen(6)) -> UserSchema:
    user = models.User.query(username=username)
    user.login(password)
    return user

Scenario - Validate Configs

@modelclass
class EnvConfig:

    debug: bool = T.bool.default(False)
    host: str = T.str.default('localhost')
    port: int = T.int.default(8080)

    @classmethod
    def load(cls):
        config = {}
        for name in fields(EnvConfig):
            key = ('PREFIX_' + name).upper()
            config[name] = os.environ.get(key, None)
        return EnvConfig(config)

CONFIG = EnvConfig.load()