Wednesday, 11 September 2019

Flask - How can I reuse the URL parameters replacing function?

I'm trying to build a view class that automatically builds the redirect url based on a string, for example :

class DeleteBook(RedirectView):
    route = "/library/<int:library_id>/book/<int:book_id>/delete"
    redirect_url = "/library/<int:library_id>/book"

    def context(self, library_id, book_id):
        book = Book(book_id)
        book.delete()

And RedirectView (please consider that BaseView is unimportant for the question)

class RedirectView(BaseView):

    def replace_parameters(self, url, **params):
        raise NotImplementedError()

    def get(self, **params):
        try:
            self.context(**params)
            flash('Book deleted')
        except:
            flash('Could not delete book')
        finally:
            redirect_url = self.replace_parameters(self.redirect_url, params)
            return redirect(redirect_url)

How can I implement replace_parameters in my RedirectView class so that it behaves exactly like Flask's route parameter replacing function?

This question I think is mostly related to knowing the Flask internal API, I couldn't find the method that does this part.



from Flask - How can I reuse the URL parameters replacing function?

No comments:

Post a Comment