Flask – Installation & Basic

Install Flask

pip install flask

Simple App

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

@app.route('/')
def index():
    return 'Hello, World!'

@app.route('/hello/<string:name>')
def hello(name):
    return '<h1> Hello {} </h1>'.format(name)

@app.route('/post/<int:post_id>')
def show_post(post_id):
    return '<h1> Hello {} </h1>'.format(post_id)

@app.route('/about', methods=['POST', 'GET'])
def about():
    return '<h1> About</h1>'

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return 'method is POST'
    else:
        return 'method is GET'

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

Run App

set FLASK_APP=main.py
set FLASK_ENV=development
flask run

# main.py = change with your file name

Redirect & Url_for

from flask import url_for, redirect

return redirect(url_for('hello'))

return redirect(url_for('hello', name=name))
# redirect with parameter 


<a href="{{ url_for('home.homepage') }}"> Home </a>
# HTML link with url_for

Session

from flask import session

app = Flask(__name__)
app.config['SECRET_KEY'] = 'Thisissecret'

# save session:
session['name'] = name

# get session value:
name = session['name']

# delete session:
session.pop('name', None)

Debug Mode

app = Flask(__name__)

app.config['DEBUG'] = True

# if app in development DEBUG = True
# if app in production/live DEBUG = False

Static File (assets: css, js, img)

from flask import render_template, url_for

# import url_for
# Create folder static

<img src="{{ url_for('static', filename='assets/img/logo.jpg') }}">

# static = folder name
# assets/img/logo.jpg = file location

Page Not Found

from flask import render_template

@app.errorhandler(404)
def page_not_found(error):
    return render_template('page_not_found.html'), 404

Request Query String

request url : site.com/query?name=ava&location=bali

@app.route('/query')
def query():
 name = request.args.get('name')
 location = request.args.get('location')

 return '<h1> name : {} - Location : {}
 </h1>'.format(name, location)

Request Form Data

@app.route('/process', methods=['POST'])
def process():
 name = request.form['name']
 location = request.form['location']

 return '<h1> name : {} - Location : {}
 </h1>'.format(name, location) 

Request JSON Data

@app.route('/process_json', methods=['POST'])
def process_json():
 data = request.get_json()
 name = data['name']
 location = data['location']

 jsonify({'result' : 'success'})

Library Jsonify

from flask import jsonify

penggunaan :

dictionary_data = ...
return jsonify({'data' : dictionary_data})

DateTime

import datetime

datetime = datetime.datetime.now()

Requirement.txt

pip freeze > requirements.txt
# create requirements.txt

pip install --upgrade -r requirements.txt
# install all library from requirements.txt

Time Sleep / Delay

import time

time.sleep(60) # Delay for 1 minute (60 seconds).

Clear Screen (CLI)

import os

os.system('cls' if os.name == 'nt' else 'clear')
# Fungsi ini akan kita gunakan untuk membersihkan layar.

Leave a Reply

Your email address will not be published. Required fields are marked *