Skip to content

Instantly share code, notes, and snippets.

@quachngocxuan
Last active January 8, 2018 06:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quachngocxuan/69614b67023fa27694d06b32e1d50a4d to your computer and use it in GitHub Desktop.
Save quachngocxuan/69614b67023fa27694d06b32e1d50a4d to your computer and use it in GitHub Desktop.
Learn enough to be dangerous - Flask

Learn enough to be dangerous - Flask

Based on Tutorialspoint - Flask.

CORE CONCEPTS

Intro

  • Flask is a web application framework written in Python.
  • Flask is based on Werkzeug WSGI toolkit and Jinja2 template engine.
  • Flask is often referred to as a micro framework. It aims to keep the core of an application simple yet extensible. Flask does not have built-in abstraction layer for database handling, nor does it have form a validation support. Instead, Flask supports the extensions to add such functionality to the application. Some of the popular Flask extensions are discussed later in the tutorial.

Installation

  • Python 2.6 or higher is usually required for installation of Flask. Although Flask and its dependencies work well with Python 3 (Python 3.3 onwards), many Flask extensions do not support it properly. Hence, it is recommended that Flask should be installed on Python 2.7.
  • virtualenv is a virtual Python environment builder. It helps a user to create multiple Python environments side-by-side.
$ pip install Flask

Hello application

from flask import Flask
app = Flask(__name__)

@app.route('/hello')
def hello_world():
   return 'Hello Worldif __name__ == '__main__':
   app.run()

Running server

$ python hello.py

Debug mode

A Flask application is started by calling the run() method. However, while the application is under development, it should be restarted manually for each change in the code. To avoid this inconvenience, enable debug support. The server will then reload itself if the code changes. It will also provide a useful debugger to track the errors if any, in the application.

The Debug mode is enabled by setting the debug property of the application object to True before running or passing the debug parameter to the run() method.

app.debug = True
app.run()

or

app.run(debug = True)

Routing

The route() function of the Flask class is a decorator, which tells the application which URL should call the associated function.

The add_url_rule() function of an application object is also available to bind a URL with a function as in the above example, route() is used.

def hello_world():
   returnhello worldapp.add_url_rule(‘/’, ‘hello’, hello_world)

Variable rules

If the http://localhost:5000/hello/TutorialsPoint is entered as a URL in the browser, ‘TutorialPoint’ will be supplied to hello() function as argument.

@app.route('/hello/<name>')
def hello_name(name):
   return 'Hello %s!' % name

Other converters: int, float, path

@app.route('/blog/<int:postID>')
def show_blog(postID):
   return 'Blog Number %d' % postID

@app.route('/rev/<float:revNo>')
def revision(revNo):
   return 'Revision Number %f' % revNo

URL building

The url_for() function is very useful for dynamically building a URL for a specific function.

from flask import Flask, redirect, url_for
app = Flask(__name__)

@app.route('/admin')
def hello_admin():
   return 'Hello Admin'

@app.route('/guest/<guest>')
def hello_guest(guest):
   return 'Hello %s as Guest' % guest

@app.route('/user/<name>')
def hello_user(name):
   if name =='admin':
      return redirect(url_for('hello_admin'))
   else:
      return redirect(url_for('hello_guest',guest = name))

if __name__ == '__main__':
   app.run(debug = True)

HTTP methods

from flask import Flask, redirect, url_for, request
app = Flask(__name__)

@app.route('/success/<name>')
def success(name):
   return 'welcome %s' % name

@app.route('/login',methods = ['POST', 'GET'])
def login():
   if request.method == 'POST':
      user = request.form['nm']
      return redirect(url_for('success',name = user))
   else:
      user = request.args.get('nm')
      return redirect(url_for('success',name = user))

if __name__ == '__main__':
   app.run(debug = True)

Templating (Jinja2)

from flask import Flask
app = Flask(__name__)

@app.route('/hello/<user>')
def hello_name(user):
   return render_template('hello.html', name = user)

if __name__ == '__main__':
   app.run(debug = True)

Flask will try to find the HTML file in the templates folder, in the same folder in which this script is present.

Application folder Hello.py templates hello.html

Placeholders

<h1>Hello {{ name }}!</h1>

The Jinga2 template engine uses the following delimiters for escaping from HTML.

  • {% ... %} for Statements
  • {{ ... }} for Expressions to print to the template output
  • {# ... #} for Comments not included in the template output
  • ... ## for Line Statements

{% if marks>50 %}
<h1> Your result is pass!</h1>
{% else %}
<h1>Your result is fail</h1>
{% endif %}

Flashing

  • A Flask module contains flash() method. It passes a message to the next request, which generally is a template.
  • In order to remove message from session, template calls get_flashed_messages().

Code in Flask's controller:

flash('You were successfully logged in')
return redirect(url_for('index'))

Code in html

{% with messages = get_flashed_messages() %}
   {% if messages %}
         {% for message in messages %}
            {{ message }}
         {% endfor %}
   {% endif %}
{% endwith %}

Print information of an object

Import pprint

from pprint import pprint

And then print the object by this

pprint(obj)

JSON APIs

See this source

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment