/ Published in: Python
                    
                                        
Snippet showing a simple Flask application to illustrate the topics covered in the "Quickstart".
                
                            
                                Expand |
                                Embed | Plain Text
                            
                        
                        Copy this code and paste it in your HTML
from flask import Flask, url_for, request, render_template, flash, redirect, abort, session, escape
app = Flask(__name__)
# setting the secret_key generate with: >>> import os; os.urandom(24)
app.secret_key = '\x1eo\xc0\xd84\x8c\xfez\xbc\x0eQ\xc2\xb4we\xa8p\r\x13\\\x88\x97\x8e\xb9'
# route() decorator is used to bind a function to a URL
@app.route('/')
def index():
return '<b>Index Page</b>'
@app.route('/hello')
def helloWorld():
return '<b>Hello World!</b>'
# route() accepts URLs with variable parts
@app.route('/hello/<user>')
def helloUser(user):
return '<b>Hello %s!</b>' % user
# rules may also be specified using a converter. Converter types:
# int accepts integers
# float like int but for floating point values
# path like the default but also accepts slashes
@app.route('/hello/<user>/<int:greetingsCount>')
def helloUserN(user, greetingsCount):
greetingsCount = abs(greetingsCount)
if greetingsCount > 3:
app.logger.warning('Warning! The greetings count %d is above the limit (3).', greetingsCount)
returnValue = ''
while greetingsCount > 0:
returnValue += '<b>Hello %s!</b><br />' % user
greetingsCount -= 1;
return returnValue
# building URLs using the url_for() function. Unknows variables are appended to the URL as query parameters
@app.route('/urls')
def printUrls():
builtUrls = ''
builtUrls += url_for('index') + '<br />'
builtUrls += url_for('helloWorld') + '<br />'
builtUrls += url_for('helloWorld', user='user') + '<br />'
builtUrls += url_for('helloUser', user='user') + '<br />'
builtUrls += url_for('helloUserN', user='user', greetingsCount='3') + '<br />'
return builtUrls
# example on how to access the request object
# To access parameters submitted in the URL (?key=value) you can use the args attribute:
# searchword = request.args.get('key', '')
# by default, a route only answers to GET requests, but it can be changed, as below:
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
if isCredentialsValid(request.form['username'], request.form['password']):
# escape() used here does escaping for you. Can be used when you are not using the template engine
session['username'] = escape(request.form['username'])
return redirect(url_for('ghibliIndex'))
else:
app.logger.error('Invalid username and/or password provided.')
flash('Invalid username and/or password.', 'error')
# the code below this is executed if the request method
# was GET or the credentials were invalid
return render_template('login.html')
def isCredentialsValid(username, password):
if username == 'user' and password == 'pass':
return True
return False
@app.route('/logout')
def logout():
# remove the username from the session if it's there
session.pop('username', None)
return redirect(url_for('ghibliIndex'))
# example of how to deal with templates
@app.route('/ghibli')
@app.route('/ghibli/<name>')
def ghibliIndex(name=None):
return render_template('ghibli.html', name=name, ghibliLogoUrl=url_for('static', filename='ghibli.gif'))
# example of how to deal with templates
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
f = request.files['filename'];
# to save the file, the line below could be used
# f.save('/var/www/uploads/uploaded_file.txt')
# f.filename contains the name of the file on the client, before it was uploaded,
# but it should not be trusted. If it is wanted to use it, pass it though the
# secure_filename function
# from werkzeug import secure_filename
# f.save('/var/www/uploads/' + secure_filename(f.filename))
flash('Content of the uploaded file:', 'message')
messages = []
lines = f.readlines()
for line in lines:
flash(line, 'message')
# example of how to use the redirect() function to guide use to an endpoint
return redirect(url_for('upload'))
return render_template('upload.html')
# useless route to illustrate the usage of abort() function
@app.route('/forbidden')
def forbidden():
abort(401)
@app.errorhandler(404)
def page_not_found(error):
app.logger.debug('Reached page not found handler.')
return render_template('page_not_found.html', makkuroUrl=url_for('static', filename='makkuro.jpg')), 404
# this function could be written using the make_response() function
# resp = make_response(render_template('page_not_found.html', makkuroUrl=url_for('static', filename='makkuro.jpg')), 404)
# resp.headers['X-Something'] = 'A value'
# return resp
if __name__ == '__main__':
# app.run()
# Enabling debug mode - NEVER USE IT IN PRODUCTION
# Almost mandatory in development environments because, if enabled, the server will
# reload itself on code changes
app.run(debug=True)
# or
# app.debug = True
# app.run()
# Making the built-in server externally visible
# It is disabled by default because in debugging mode a user of the application
# can execute arbitrary Python code on the machine
# Enable it if debug is disabled or users on the network can be trusted
# app.run(host='0.0.0.0')
URL: http://flask.pocoo.org/docs/quickstart/
Comments
 Subscribe to comments
                    Subscribe to comments
                
                