Including additional validation


#1

I have the following example from https://docs.apistar.com/api-guide/type-system/:

from apistar import App, Route, exceptions, types, validators


class Organisation(types.Type):
    is_premium = validators.Boolean()
    expiry_date = validators.Date(allow_null=True)

    def __init__(self, *args, **kwargs):
        value = super().__init__(*args, **kwargs)
        if value.is_premium and value.expiry_date is not None:
            message = 'premium organisations should not have any expiry_date set.'
            raise exceptions.ValidationError(message)
        return value


def test(o: Organisation)-> dict:
    print(o)
    return {'message': 'OK'}


routes = [
    Route('/test', method='POST', handler=test),
]

app = App(routes=routes)


if __name__ == '__main__':
    app.serve('127.0.0.1', 8000, debug=True)

Running this and doing

curl -X POST -H 'Content-Type: application/json' -i http://localhost:8000/test --data '{"is_premium": false}'

throws an exception:

  File "/home/mkosta/apistar-test/test.py", line 12, in __init__
    if value.is_premium and value.expiry_date is not None:
AttributeError: 'NoneType' object has no attribute 'is_premium'

it seems that the line

value = super().__init__(*args, **kwargs)

sets value to None. How come? What am I doing wrong?
Thank you in advance!


#2

Have you found a solution for this?
I’m having the same problem.


#3

You are having this issue because of the mistake in documentation example. __init__ method in Python never returns any value except None by design.

I’ve made a pull request 2 weeks ago to fix the docs — https://github.com/encode/apistar/pull/597/files

But it is still open.

@tom How can we help you?