Flask - (1)

Application object in Flask.

2019-12-24
by cS


This is the first of several notes that I will write on how to code your first application, and deploy it to the cloud.

Flask is an open source microframework written with python that makes it very easy for programmers to program websites.

Assuming you know the basics of the console and that you have python > 3.6 installed on you os.

pip install flask

Make a directory for your project cd into it and make an app.py file – for your application code.

mkdir my_site; cd my_site; touch app.py

Launch your code editor of choice and create a Flask appliction object.

# First imports
# - - - - - - -

import os # python built in module to load environment variables, and work with file systems.

from flask import Flask

# Configurations to run the application on a localserver.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

DEBUG = True
HOST  = "127.0.0.1"
PORT  = 8080

# The Flask object is the application object we will use to initialize an application object.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

app = Flask(__name__)

# We need to tell the app object where to look for static files e.g javascript, css, & images
# -- most importantly we need to set a secret key to run the application.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

app.secret_key       = os.getenv("SECRET_KEY", "test**key") # load a key from env or default
app.static_folder    = "static"
app.templates_folder = "templates"
  

# A route is a function that returns a template.
# we use decorators to specify the url of the route, and its HTTP methods
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

@app.route("/", methods=("GET",))
def index():
    greetings = "Hello World"
    return greetings


if __name__ == "__main__":

    # First we test for a truthy boolean value of our constant DEBUG to see if we should run
    # this app with the debugger on, meaning while we are developing the application.
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    if DEBUG: 
        app.run(debug=DEBUG, host=HOST, port=PORT)

    # If DEBUG is not true, we are running on the cloud, just run.
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    else:
        app.run()