Friendly Urls with flask

Asked

Viewed 229 times

0

Good afternoon, I am developing a system using the Flask python framework and would like to know how I can create system-friendly urls? I have to use some other framework or something?

1 answer

1

URL friendly is just a term for a standardized URL that is usually easier and intuitive to the end user, the goal of Flask is this same, write Urls as you wish without needing anything else, as well as most web frameworks, so just understand the basic concept, this would be a friendly URL:

http://site/usuario/joao

This already nay would be a friendly URL (or at least not as friendly):

http://site/channel/UC2hxYQtGLEkcOMK4h8JRycA

This would be a friendly URL

http://site/channel/stackoverflow

This already nay would be a friendly URL:

http://site/?pag=channel&id=stackoverflow

Some examples of user-friendly URL would be something like:

from flask import Flask
app = Flask(__name__)

@app.route("/") # acessivel via http://site/
def home():
    return "Olá mundo!"

@app.route("/sobre") # acessivel via http://site/sobre
def sobre():
    return "Somos uma empresa!"

@app.route("/contato") # acessivel via http://site/contato
def contato():
    return "Fale conosco!"

@app.route("/foo/bar/baz") # acessivel via http://site/foo/bar/baz
def hello():
    return "Fale conosco!"

More details on http://flask.pocoo.org/docs/0.12/quickstart/#routing

Now an example of dynamic Urls:

  1. Display a name typed in the URL as http://site/usuario/joão or http://site/usuario/mario

    @app.route('/usuario/<user>')
    def exibir_perfil(user):
        return 'Usuário %s' % user
    
  2. Display a name typed in the URL as http://site/postagem/123 or http://site/postagem/456

    @app.route('/postagem/<int:id>')
    def exibir_postagem(id):
        return 'Postagem %s' % id
    

If you want to limit by HTTP methods, for example:

  1. Only via GET:

    @app.route('/foo/bar', methods=['GET'])
    
  2. Only via POST:

    @app.route('/foo/bar', methods=['POST'])
    
  3. Only via HEAD:

    @app.route('/foo/bar', methods=['HEAD'])
    
  4. Only via GET and POST:

    @app.route('/foo/bar', methods=['GET', 'POST'])
    

Browser other questions tagged

You are not signed in. Login or sign up in order to post.