Using regex in flask restful api route url

I am trying to add regex based url for flask api. but it doesn't seems to work. and i am unable to find a solution on documentation too.

scheduler_blueprint = Blueprint('scheduling_api', __name__)
api = TalentApi()
api.init_app(scheduler_blueprint)
api.route = types.MethodType(api_route, api)

@api.route('/tasks/<string:id>')
class TaskById(Resource):
....

@api.route('/tasks/resume/')
class ResumeTasks(Resource):
....

where string:id should be a hash other than 'resume' as far as i know, regex is the only thing which i can use in this scenario to remove this conflict. how can i use regex in url for flask restful api ?

Answers


Write a custom url converter that recognizes 32 hex characters. Register the converter with the app and use it in the route.

from werkzeug.routing import BaseConverter

class TaskIDConverter(BaseConverter):
    regex = r'[A-Fa-f0-9]{32}'

# register the converter when creating the app
app = Flask(__name__)
app.url_map.converters['task_id'] = TaskIDConverter

# use the converter in the route
@app.route('/user/<task_id:id>')
def process_user(id):
    ...

# will recognize /user/0123456789abcdef0123456789abcdef
# will 404 on /user/123, /user/123abc456, etc.

If the id is really an int, and not a string that happens to have only digits, use the following converter instead. It converts the value to an int, and makes sure that the value doesn't start with 0, which would result in fewer than 32 digits in the int.

class TaskIDConverter(BaseConverter):
    regex = r'[1-9]\d{31,}'

    def to_python(self, value):
        return int(value)

    def to_url(self, value):
        return str(value)

Need Your Help

BufferedReader not reading whole online XML file

java xml bufferedreader

public static void main(String[] args) throws MalformedURLException, IOException

How to merge multiple HTML files into one like Sass do with css using @import?

html rubygems sass

In Sass we can combine multiple partials into single css output like