0% found this document useful (0 votes)
14 views4 pages

Flask Cheatsheet _ CodeWithHarry

The Flask Cheatsheet provides essential code snippets and explanations for using Flask, including importing Flask, creating routes, setting allowed methods, and initializing SQLAlchemy. It covers basic operations such as creating a model, querying data, and handling database transactions. Additionally, it includes tips for debugging and rendering templates, along with links to official documentation.

Uploaded by

meejanani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views4 pages

Flask Cheatsheet _ CodeWithHarry

The Flask Cheatsheet provides essential code snippets and explanations for using Flask, including importing Flask, creating routes, setting allowed methods, and initializing SQLAlchemy. It covers basic operations such as creating a model, querying data, and handling database transactions. Additionally, it includes tips for debugging and rendering templates, along with links to official documentation.

Uploaded by

meejanani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

2/18/25, 1:29 PM Flask Cheatsheet | CodeWithHarry

Flask Cheatsheet
Haris Ali Khan

July 1, 2022 2 min read

Importing Flask

from flask import Flask

Most used import functions


These are some of the most used import functions by flask developers

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

Boilerplate code
This is the basic template or barebone structure of a Flask app

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"

app.run()

Creating a route
This is to make different endpoints in our flask app.

@app.route("/")

Setting Allowed methods


Used to specify which methods are allowed for a request. Allowing get and post requests on an endpoint.

methods = ['GET', 'POST']

Re-run while coding


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

app.run(debug=True)

https://www.codewithharry.com/blogpost/flask-cheatsheet/ 1/5
2/18/25, 1:29 PM Flask Cheatsheet | CodeWithHarry

Change host
This is used to change the host.

app.
app.run
run(
(host
host=
='0.0.0.0'
'0.0.0.0')
)

Change port
This is used to change the port.

app.
app.run
run(
(port
port=
=80
80)
)

Importing SQLAlchemy

from flask_sqlalchemy import SQLAlchemy

Database URI
This is the database's address.

app.
app.config
config[
['SQLALCHEMY_DATABASE_URI'
'SQLALCHEMY_DATABASE_URI']
] = 'mysql://username:password@localhost/db_name'

or

app.
app.config[
config['SQLALCHEMY_DATABASE_URI']
'SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'

Initialization
This is used to initialize SQLAlchemy.

SQLAlchemy(
db = SQLAlchemy (app
app))

2024 Global Threat Report

CrowdStrike® Download

Creating a Model
Class used to get data from the database and to send data to the database.

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

Get all data - all() method

https://www.codewithharry.com/blogpost/flask-cheatsheet/ 2/5
2/18/25, 1:29 PM Flask Cheatsheet | CodeWithHarry
This is used to get all the data from the database.

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

Filtered data - first() method


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 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()

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()

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

request.method

Render Template
This is used to pass and render an html file directly.

render_template("file.html")

Solving FSADeprecationWarning
SQLALCHEMY_TRACK_MODIFICATIONS allows you to disable the modification tracking system using this line:

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

Creating Database files


This is used to create database files

from yourapplicationname import db


db.create_all()
exit()

Method to return database items


This is used to return database items.

https://www.codewithharry.com/blogpost/flask-cheatsheet/ 3/5
2/18/25, 1:29 PM Flask Cheatsheet | CodeWithHarry

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

Printing returned content from the method


This is used to print returned database items.

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

Flask Documentation
Visit the Flask documentation here

Flask SQLAlchemy Documentation


Visit the Flask SQLAlchemy documentation here

Download this Cheatsheet

Add a new comment


</> CodeWithHarry Mobile app development resources Menu Login

Type Your Comment

Post Comment

Comments (17)

zeeshanulhaq04 2025-02-15

this Cheatsheet is not downloading from my side kindly send this code
on my Gmail([email protected]), i'm begginer and follow
your course and youtube channel. Full-stack development courses

REPLY

sharmaaditya8463 2025-01-31

if anyone get this cheatsheet can you please share it on this email
([email protected]) Thanks in advance. :)

REPLY

hamoabbasi3256_gm 2024-12-25

Thanks Harry bhaiyaa

REPLY

https://www.codewithharry.com/blogpost/flask-cheatsheet/ 4/5

You might also like