Flask Cheatsheet


What is Flask

Flask is a micro web framework written in Python. It is classified as a microframework because it does not require particular tools or libraries. It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions.

Importing Flask

from flask import Flask
Python

Most used import functions

These are some of the most used import functions

from flask import Flask, render_template, redirect, url_for, request
Python

Boilerplate

This is the basic template or barebone structure of Flask.

from flask import Flask    app = Flask(__name__)     @app.route("/")    def hello_world():    return "<p>Hello, World!</p>"        app.run()
Python

route(endpoint)

This is to make different endpoints in our flask app.

@app.route("/")
Python

Route method

Allowing get and post requests on an endpoint.

methods = ['GET', 'POST']
Python

Re-run while coding

This is used to automatically rerun the program when the file is saved.

app.run(debug=True)
Python

Change host

This is used to change the host.

app.run(host='0.0.0.0')
Python

Change port

This is used to change the port.

app.run(port=80)
Python

SQLAlchemy

from flask_sqlalchemy import SQLAlchemy
Python

Database URI

This is the database's address.

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/db_name'     or app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:/InitializationThis is used to initialize SQLAlchemy.db = SQLAlchemy(app) Creating ModelClass to get data from database and to send data to the database.class TableName(db.Model): 
        column_1 = db.Column(db.Integer, primary_key=True) 
        column_2 = db.Column(db.String(80), nullable=False) 
        column_3 = db.Column(db.String(12), nullable=False)Get all data(.all())This is used to get all the data from the database.data = ClassName.query.filter_by().all()Filtered data(.first())This is used to get the first dataset from the list returned by the filter_by function. You can get targetted data by this.data = ClassName.query.filter_by().first()Send/add data to databaseThis is used to send/add data to the database.data_to_send = ClassName(column_1=dataset1, column_2=dataset2, column_3=dataset3) 
        db.session.add(data_to_send) 
        db.session.commit()Delete data from the databaseThis is used to delete data from the database.data_to_send = ClassName(column_1=dataset1, column_2=dataset2, column_3=dataset3)
        db.session.delete(data_to_send)
        db.session.commit()Request methodThis is used to know what request is made(get/post).request.methodRender TemplateThis is used to pass whole html file directly.render_template("file.html")FSADeprecationWarningapp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True|FalseCreating Database fileThis is used to create a database filefrom yourapplicationname import db 
        db.create_all() 
        exit()Method to return database itemsThis is used to return database items.def __repr__(self) -> str: 
        return f"{self.item}"Printing returned content from the methodThis is used to print returned database items.data = ClassNameWithMethod.query.all() 
        print(data)Flask Documentationhttps://flask.palletsprojects.com/en/latest/Flask SQLAlchemy Documentationhttps://flask-sqlalchemy.palletsprojects.com/en/2.x/
//test.db'
Python

Initialization

This is used to initialize SQLAlchemy.

db = SQLAlchemy(app)
Python

 

Creating Model

Class to get data from database and to send data to the database.

class TableName(db.Model):     column_1 = db.Column(db.Integer, primary_key=True)     column_2 = db.Column(db.String(80), nullable=False)     column_3 = db.Column(db.String(12), nullable=False)
Python

Get all data(.all())

This is used to get all the data from the database.

data = ClassName.query.filter_by().all()
Python

Filtered data(.first())

This is used to get the first dataset from the list returned by the filter_by function. You can get targetted data by this.

data = ClassName.query.filter_by().first()
Python

Send/add data to database

This is used to send/add data to the database.

data_to_send = ClassName(column_1=dataset1, column_2=dataset2, column_3=dataset3)     db.session.add(data_to_send)     db.session.commit()
Python

Delete data from the database

This is used to delete data from the database.

data_to_send = ClassName(column_1=dataset1, column_2=dataset2, column_3=dataset3)    db.session.delete(data_to_send)    db.session.commit()
Python

Request method

This is used to know what request is made(get/post).

request.method
Python

Render Template

This is used to pass whole html file directly.

render_template("file.html")
Python

FSADeprecationWarning

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True|False
Python

Creating Database file

This is used to create a database file

from yourapplicationname import db     db.create_all()     exit()
Python

Method to return database items

This is used to return database items.

def __repr__(self) -> str:     return f"{self.item}"
Python

Printing returned content from the method

This is used to print returned database items.

data = ClassNameWithMethod.query.all()     print(data)
Python

Flask Documentation

https://flask.palletsprojects.com/en/latest/
Python

Flask SQLAlchemy Documentation

https://flask-sqlalchemy.palletsprojects.com/en/2.x/
Python

Comments

Popular posts from this blog

How to make a Snake game using HTML , CSS and JavaScript

Install VS Code in Android

How to Install VS Code in Windows 10