Flask Cheat Sheet - CodeWithBeri

Dhiraj Beri
0


Flask is a Python web microframework. It provides a simple interface to create HTTP middleware, URLs, views, and more!

This is a quick guide on how to get started with the Flask Framework. This free download will help you create beautiful, responsive websites quickly and easily!

Cheat sheets are important because they allow you to quickly look up information without having to fumble around for the document containing that piece of information. This Cheat Sheet for flask is a great addition to any developer's library.

Importing Flask

from flask import Flask


Most used import functions

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

Boilerplate

from flask import Flask

app = Flask(__name__)

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

app.run()

Route method

methods = ['GET', 'POST']

Debug Mode

app.run(debug=True)

Change Host

app.run(host='0.0.0.0')

Change Port

app.run(port=80)

SQLAlchemy

from flask_sqlalchemy import SQLAlchemy

Database URI

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

Initialization

db = SQLAlchemy(app)

Creating Model

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

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

Filtered data(.first())

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

Send/add data to database

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

Delete data from the database

db.session.delete(data_to_send)
db.session.commit()

Render Template

render_template("file.html")

Method to return database items

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

Printing returned content from the method

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


I hope this cheat sheet is helpful, and I'm always open to discussions in the comments.
Tags

Post a Comment

0Comments
Post a Comment (0)