Kensuke Kousaka's Blog

Notes for Developing Software, Service.

Note about Flask: Intro

Write down a note about Flask, Pyhton based lightweight Web Application Framework.

Build Flask environment

First, build environment to use Flask.

Build Python environment

If you don't install python yet, run folloging command to install Python 3.x.

# pacman -S python

And also install pip by running following commands.

$ curl -O https://bootstrap.pypa.io/get-pip.py
# python get-pip.py

Install Flask

Run follow command to install Flask using pip.

# pip install Flask

Use Flask

Create directory structure by following.

- HelloFlask/
  - FlaskApp/
    - app.py
    - static/
      - css/
        - sample.css
      - js/
        - sample.js
    - templates/
      - index.html

Create index.html, sample.js, sample.css by following.

index.html

<!DOCTYPE html>
<html lang="en">
 <head>
   <meta charset="utf-8"></meta>
   <meta http-equiv="X-UA-Compatible" content="IE=edge"></meta>
   <meta content="width=device-width, initial-scale=1" name="viewport"></meta>
   <title>HelloFlask</title>
   <!-- Bootstrap CDN -->
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">

   <link rel="stylesheet" href="../static/css/sample.css">
 </head>
 <body>
   <div class="container-fluid">
     <div class="row">
       <div class="col-sm-12">
         <h1 class="text-center" id="hello">Hello Flask</h1>
         <button class="btn btn-default" id="button">Change text</button>
       </div>
     </div>
   </div>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
   <script src="../static/js/sample.js"></script>
 </body>
</html>

sample.js

$(window).load(init());

function init() {
  $("#button").click(function() {
    $("#hello").text("Yeah!");
  });
}

sample.css

div.container-fluid {
  text-align: center;
}

#hello {
  background-color: #F8F4E6;
}

Implement app.py by following.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def index():
    return render_template('index.html')


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8080)

After editting, run python app.py in the same place as app.py. Succeeded to run Flask if you got Running on http://127.0.0.1:8080/ (Press CTRL+C to quit) message.

Now, Flask is received request and return contents that previously created when connect to that URL with Web browser.

Change app host parameter that is defined in app.py from 127.0.0.1 to 0.0.0.0 if you want to publish this system to the Internet.

This sample app is published at k3nsuk3/HelloFlask.