Multiple URL segment in Flask and other Python frameowrks

前端 未结 3 1745
夕颜
夕颜 2021-02-09 19:24

I\'m building an application in both Bottle and Flask to see which I am more comfortable with as Django is too much \'batteries included\'.

I have read through the routi

相关标签:
3条回答
  • 2021-02-09 20:02

    Splitting the string doesn't introduce any inefficiency to your program. Performance-wise, it's a negligible addition to the URL processing done by the framework. It also fits in a single line of code.

    @app.route('/<path:fullurl>')
    def my_view(fullurl):
        params = fullurl.split('/')
    
    0 讨论(0)
  • 2021-02-09 20:02

    it works:

    @app.route("/login/<user>/<password>")
    def login(user, password):
        app.logger.error('An error occurred')
        app.logger.error(password)
        return "user : %s password : %s" % (user, password)
    

    then:

    http://example.com:5000/login/jack/hi

    output:

    user : jack password : hi
    
    0 讨论(0)
  • 2021-02-09 20:06

    I'm fairly new to Flask myself, but from what I've worked out so far, I'm pretty sure that the idea is that you have lots of small route/view methods, rather than one massive great switching beast.

    For example, if you have urls like this:

    http://example.com/unit/57/
    http://example.com/unit/57/page/23/
    http://example.com/unit/57/page/23/edit
    

    You would route it like this:

    @app.route('/unit/<int:unit_number>/')
    def display_unit(unit_number):
        ...
    
    @app.route('/unit/<int:unit_number>/page/<int:page_number>/')
    def display_page(unit_number, page_number):
        ...
    
    @app.route('/unit/<int:unit_number>/page/<int:page_number>/edit')
    def page_editor(unit_number, page_number):
        ...
    

    Doing it this way helps to keep some kind of structure in your application and relies on the framework to route stuff, rather than grabbing the URL and doing all the routing yourself. You could then also make use of blueprints to deal with the different functions.

    I'll admit though, I'm struggling to think of a situation where you would need a possibly unlimited number of sections in the URL?

    0 讨论(0)
提交回复
热议问题