0

I want to associate a few methods of a (real world) object to Flask URL routes:

class Door:
    def __init__(self, location):
        pass
    def open(self):
        pass
    def close(self):
        pass
    def openlater(self, waitseconds=2):
        pass

d = Door(location="kitchen")

app.add_url_rule("/door/open", view_func=lambda: d.open())
app.add_url_rule("/door/close", view_func=lambda: d.close())
app.add_url_rule("/door/openlater", view_func=lambda: d.openlater(waitseconds=10))

# or (if we don't override optional parameters):

for func in ['open', 'close', 'openlater']:
    app.add_url_rule(f"/door/{func}", view_func=lambda: getattr(d, func)())

But this does not work:

AssertionError: View function mapping is overwriting an existing endpoint function:

How to do this properly with Python Flask?

Note:

I could do

app.add_url_rule(f"/door/{func}", view_func=getattr(d, func))

but then I don't have any lambda anymore and I cannot set parameters.

Basj
  • 41,386
  • 99
  • 383
  • 673
  • 1
    Django has an `as_view()`...and I'm not familiar with Flask but it looks to have a similar method too...https://flask.palletsprojects.com/en/2.1.x/api/#flask.views.View.as_view – ViaTech May 24 '22 at 15:07
  • @ViaTech In my example, `Myobj` is not a `View` class with methods get, post, etc. but rather `Myobj` is a real-world model for an object. – Basj May 24 '22 at 15:16
  • Check this out https://stackoverflow.com/questions/35107885/how-to-generate-dynamic-urls-in-flask – NoNameAv May 24 '22 at 15:22

1 Answers1

1

To create views and map them to a URL, you should create routes. Do this the following way:

@app.route('/')
def index():
    return "Hello World!"

Now when you access your webpage you get Hello World on screen. The add_url_rule is hardly use anymore.

If you want your URL to be dynamic you can do the following:

@app.route('/func/<func>')
def index(func):
    return "Hello World!"
NoNameAv
  • 423
  • 2
  • 14
  • I used this solution before, but since I have **many** methods in my object, I would have a lot of duplicated code with your solution. I'm looking for a way to create 15 routes for most methods of an object with a single loop. – Basj May 24 '22 at 15:19
  • I edited my code, you can use dynamic url's to overcome this and not have 15 different methods, just and if statement in the route depending on what the user typed – NoNameAv May 24 '22 at 15:21
  • @OlauPla does whatever is passed in the `` also get passed as an argument in `index(func)`? – user14773854 May 24 '22 at 15:23
  • Yes it's the same, If you type example.com/func/example. "Example" will get passed – NoNameAv May 24 '22 at 15:24