Flask is a micro web framework, having a core functionality includes WSGI and routing based on Werkzeug and template engine based on Jinja2. In addition, Flask framework has support for cookie and sessions as well as web helpers like JSON, static files etc. And Flask extensions give extensibility to Flask framework to develop a full-fledged web application.

  • A very good tutorial that walk you through creating a flask application.
  • routing
  • url_for()
  • http method
  • html form data
  • render_template()
    • jinjia2 template, doc:
      • {% … %} for statements
      • {{ … }} for expressions to print to the template output
      • {# … #} for comments not included in the template output
      • Line Statements and Comments are also possible, though they don’t have default prefix characters. To use them, set line_statement_prefix and line_comment_prefix when creating the Environment.
  • static files
    • url_for(‘static’, filename=’hello.js’)
    • static/ folder, where stores javascript file and css file
  • Request Object
    • Important attributes
      • form - dictionary object of form parameters and their values
      • args - parsed contents of query string which is part of URL after question mark.
      • cookies - dictionary object holding Cookie names and values
      • files - uploaded files
      • method - current request methods
    • A cookie is stored on a client’s computer in the form of a text file. Its purpose is to remember and track data pertaining to a client’s usage for better visitor experience and site statistics. ```python resp = make_response(render_template(‘readcookie.html’)) resp.set_cookie(‘userID’, userID)

    uid = request.cookies.get(‘userID’) ```

  • Sessions
    • Like Cookie, Session data is stored on client. Session is the time interval when a client logs into a server and logs out of it. The data, which is needed to be held across this session, is stored in the client browser.
    • A session with each client is assigned a Session ID. The Session data is stored on top of cookies and the server signs them cryptographically. For this encryption, a Flask application needs a defined SECRET_KEY.
      from flask import Flask, session, redirect, url_for, escape, request
    
      app = Flask(__name__)
      app.secret_key = 'your_secret_key'
    
      @app.route('/')
      def index():
          if 'username' in session:
              username = session['username']
                  return 'Logged in as ' + username + '<br>' + \
                  "<b><a href = '/logout'>click here to log out</a></b>"
          return "You are not logged in <br><a href = '/login'></b>" + \
              "click here to log in</b></a>"
    
      @app.route('/login', methods = ['GET', 'POST'])
      def login():
          if request.method == 'POST':
              session['username'] = request.form['username']
              return redirect(url_for('index'))
          return '''
                
          <form action = "" method = "post">
              <p><input type = text name = username/></p>
              <p><input type = submit value = Login/></p>
          </form>
                
          '''
    
      @app.route('/logout')
      def logout():
          # remove the username from the session if it is there
          session.pop('username', None)
          return redirect(url_for('index'))
    
  • Redirect & Errors
    • Flask.redirect(location, status_code, response)
    • Flask.abort(code)
  • Message Flashing
  • File Uploading
    • app.config[‘UPLOAD_FOLDER’]: Defines path for upload folder
    • app.config[‘MAX_CONTENT_PATH’]: Specifies maximum size of file to be uploaded in bytes.
      f = request.files['file_name']
      f.save(secure_filename(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))) # Or you can hard-coded the destination.
    
  • Flask Extensions
    • Flask Mail: provides SMTP interface to Flask application
    • Flask WTF: adds rendering and validation of WTForms
    • Flask SQLAlchemy − adds SQLAlchemy support to Flask application
    • Flask Sijax − Interface for Sijax - Python/jQuery library that makes AJAX easy to use in web applications
  • SQLite
    • Python has a built-in support for SQLite. SQLite3 module is shipped with Python distribution.
  • Deployment