0

I'm trying to figure out why isinstance doesn't seem to be working for me. Is it because I'm using strings or could the post data format be wrong (I print it to the output and it looks right)

class Dogs(enum.Enum):
    poodle= 'poodle'
    terrier= 'terrier'

@blueprint.route('/test/<int:test_id>', methods=['post'])
def test(int:test_id):
    data = request.json
    print(data) #it's poodle
    if isinstance(data, Dog):        
        return HTTPStatus.OK

return HTTPStatus.BAD_REQUEST
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
NetHawk
  • 1,392
  • 1
  • 15
  • 33
  • 2
    It's because you're using strings. The type of `data` is `str`, not `Dog`. You'd want to instead use [this method](https://stackoverflow.com/questions/63335753/how-to-check-if-string-exists-in-enum-of-strings) to check whether the enum _contains_ the value you want. – Green Cloak Guy Feb 24 '21 at 21:56
  • Side-note: Your enum class is named `Dogs`, your test is against `Dog`. Typo in copying? Or mistake in actual code? – ShadowRanger Feb 24 '21 at 22:07

2 Answers2

1

Your variable data is a string object - it isn't an object instance of class Dogs, which is why isinstance will return false regardless of what's in the data variable. Something like this should work instead of isinstance:

# if isinstance(data, Dog):    
if data in Dogs.__members__:
Adam Oellermann
  • 303
  • 1
  • 7
0

I ended up using a try-catch block.

   try:
     Dogs(data)
   except ValueError:
     return HTTPStatus.BAD_REQUEST
 return HTTPStatus.BAD_REQUEST

I think this is a terrible answer, but it works.

NetHawk
  • 1,392
  • 1
  • 15
  • 33