Good afternoon, I'm developing a system using the python Flask framework and would like to know how I can create friendly urls for the system? Do I have to use some other framework or something?
Good afternoon, I'm developing a system using the python Flask framework and would like to know how I can create friendly urls for the system? Do I have to use some other framework or something?
Friendly URL is just a term for a standardized URL that is usually easier and more intuitive to the end user, the goal of Flask is this, write URLs as you wish without needing anything else, just like most web frameworks , so just understand the basic concept, this would be a friendly URL:
http://site/usuario/joao
This not would be a friendly (or at least not as user friendly) URL:
http://site/channel/UC2hxYQtGLEkcOMK4h8JRycA
This would be a friendly URL
http://site/channel/stackoverflow
This would not be a friendly URL:
http://site/?pag=channel&id=stackoverflow
Some user-friendly URL examples would look something like this:
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 link
Now an example of dynamic URLs:
Display a name entered 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
Display a name entered 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 HTTP methods, for example:
Only via GET
:
@app.route('/foo/bar', methods=['GET'])
Only via POST
:
@app.route('/foo/bar', methods=['POST'])
Only via HEAD
:
@app.route('/foo/bar', methods=['HEAD'])
Only via GET
and POST
:
@app.route('/foo/bar', methods=['GET', 'POST'])