Home > Mobile >  How do I specify an enum type hint for a flask route parameter
How do I specify an enum type hint for a flask route parameter

Time:03-16

I have the following enum

class RequestType(str, Enum):
     type1 = "abc"
     type2 = "xyz"

And the following flask route:

@app.route("/api/v1/<type>", methods=["POST"]
def type(type):
     # do stuff

I want to be able to do something like this:

@app.route("api/v1/<RequestType:type>", methods=["POST"]

But I can't find a way to make something like this work. Is there a good way to do this? Or some other way to restrict the value of type to a limited list of strings?

CodePudding user response:

You need to add a custom converter. This converts the extracted part of the URL to the enum constant you defined or converts the constant passed to a part of a URL. In order to be able to use this, it must be added to the mapping for converters with an identifier. From now on it can be used with the registered name in every rule or a URL can be created with url_for using a passed parameter of the defined enum type.

from flask import Flask
from enum import Enum, unique
from werkzeug.routing import BaseConverter, ValidationError

@unique
class RequestType(str, Enum):
    TYPE1 = 'abc'
    TYPE2 = 'def'

class RequestTypeConverter(BaseConverter):

    def to_python(self, value):
        try:
            request_type = RequestType(value)
            return request_type
        except ValueError as err:
            raise ValidationError()

    def to_url(self, obj):
        return obj.value


app = Flask(__name__)
app.url_map.converters.update(request_type=RequestTypeConverter)

@app.route('/api/v1/<request_type:t>', methods=['POST'])
def root(t):
    return f'{t.name} -> {t.value}'
  • Related