3

Want a quick and dirty Flask test server where I can type in a url path

0.0.0.0/**something**

and get it to call a corresponding method of the same name.

Something like this:

from flask import Flask
app = Flask(__name__)

@app.route('/<action>')
def do_it(action=None):

    if {PSEUDO: The method exists, call it}
    else:
        return 'Action not found'

def something():

    return 'Did something'

if __name__ == '__main__':
    app.run()

Does Flask have a mechanism to help with this or do I have to get messy with reflection?

2 Answers 2

4

It is a really bad idea to allow the client to run arbitrary code on your server. Instead, consider putting all the available actions in a class, and restricting the choice to the methods of the class:

from flask import Flask
app = Flask(__name__)

class Actions:
    def something(self):
        return 'Did something'

    def something_else(self):
        return 'Did something else'

my_actions = Actions()

@app.route('/<action>')
def do_it(action = None):
    op = getattr(my_actions, action, None)
    if callable(op):
        return op()
    else:
        return 'Action not found'

if __name__ == '__main__':
    app.run(debug = True)
Sign up to request clarification or add additional context in comments.

1 Comment

@Miguel- Thanks, yeah i know it's bad- just needed something Q&D but yours is def the smarter way
3

Not sure how messy that is, but it seems pretty straight forward:

  try:                                                                        
      return globals()[action]()                                              
  except KeyError:                                                           
      return 'Action not found' 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.