from flask import Flask, request, redirect, url_for
app = Flask(__name__)
@app.route('/')
def method_name():
# Coletando os dados do body da request
body = request.get_json()
return 'Alguma coisa'
# path variable
@app.route('/user/<username>')
def profile(username):
return '{}\'s profile'.format(escape(username))
# Métodos HTTP
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return do_the_login()
else:
return show_the_login_form()
# Redirecionar para outra rota
@app.route('/redirecionar')
def index():
return redirect(url_for('login'))
from flask import make_response, render_template, jsonify, json
app = Flask(__name__)
# Em JSON com jsnoify (jeito mais certo)
@app.route('/json')
def returnJson():
return jsonify(username=g.user.username,
email=g.user.email,
id=g.user.id)
# Em JSON manualmente
@app.route('/manually')
def returnJsonManually():
data = make_summary()
response = app.response_class(
response=json.dumps(data),
status=200,
mimetype='application/json'
)
return response
# Em JSON utilizando dictionary
@app.route("/dictionary")
def returnJsonWithDictionary():
return {
"username": "Nom do usuário",
"theme": "Tema 1",
"image": "https://www.google.com",
}
# Em HTML
@app.route('/html')
def returnHtml():
# Setando o corpo para uma página HTML
response = make_response(render_template('index.html', foo=42))
# Setando os headers
response.headers['X-Parachutes'] = 'parachutes are cool'
return response
from flask import abort, render_template
# Alterando a página de erro 404 (por padrão é uma página preto e branco)
@app.errorhandler(404)
def page_not_found(error):
return render_template('page_not_found.html'), 404
# Retorna mensagem de erro
@app.route('/erro')
def rotaComErro():
return abort(401)