Skip to main content

Flask cheatsheet

 


Flask Cheatsheet

Loading...

Importing Flask

from flask import Flask

Most used import functions

These are some of the most used import functions

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

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

route(endpoint)

This is to make different endpoints in our flask app.

@app.route("/")

Route method

Allowing get and post requests on an endpoint.

methods = ['GET', 'POST']

Re-run while coding

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

app.run(debug=True)

Change host

This is used to change the host.

app.run(host='0.0.0.0')

Change port

This is used to change the port.

app.run(port=80)

SQLAlchemy

from flask_sqlalchemy import SQLAlchemy

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:///test.db'

Initialization

This is used to initialize SQLAlchemy.

db = SQLAlchemy(app)

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)

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 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 whole html file directly.

render_template("file.html")

FSADeprecationWarning

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

Creating Database file

This is used to create a database file

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

Method to return database items

This is used to return database items.

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

Printing returned content from the method

This is used to print returned database items.

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

Flask Documentation

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

Flask SQLAlchemy Documentation

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

Comments

Popular posts from this blog

5 Ways to Save Money as a Student

  5 Ways to Save Money as a Student Loading... This article is for those students who are currently studying and wants to save some money; I have gathered these methods by using which students can save up some money. Savings on Shopping If you are a student who shops online and wants to save some money, you should consider the great Indian sale and Flipkart Big Billion Days. You can get products at a huge discount which will help you to save some money. Amazon Great Indian Festival Sale. Flipkart Big Billion Day Sale. Developer Now, If you are a student who loves to code and you are a developer or want to be a developer, this will help you. Github Student Developer Pack:  You can opt for the Github Education pack and get a ton of paid software for free. Like You can get Bootstrap Studio for free, You can get three free domains from big domain providers like Namecheap, .tech, and name.com. The Github education pack has around 200k$+ amount of services, and everything is free fo...

Github has launched a new AI named GITHUB COPILOT which can steal the job of programmers

Join this program with the following link https://github.com/features/copilot/signup Github is  launching a technical preview of   GitHub Copilot , a new AI pair programmer that helps you write better code. GitHub Copilot draws context from the code you’re working on, suggesting whole lines or entire functions. It helps you quickly discover alternative ways to solve problems, write tests, and explore new APIs without having to tediously tailor a search for answers on the internet. As you type, it adapts to the way you write code—to help you complete your work faster. Developed in collaboration with OpenAI, GitHub Copilot is powered by OpenAI Codex, a new AI system created by OpenAI. OpenAI Codex has broad knowledge of how people use code and is significantly more capable than GPT-3 in code generation, in part, because it was trained on a data set that includes a much larger concentration of public source code. GitHub Copilot works with a broad set of frameworks and languages, ...

BGMI tips and tricks to enhance your game experience

  BEST BGMI SETTINGS: GRAPHICS, FOOTSTEPS, SMOOTH GAME 1 month ago   by  Alex David As you all know that Battlegrounds Mobile India has been publicly made available . Many of you might have even started playing the game on your smartphones. The good thing is that we can transfer all our old PUBG data to BGMI. So even after having the new game, we can enjoy our old outfits and actions. However, as we mentioned in our earlier article, there are some drawbacks. We don’t get some of the things back. This article will revolve around the best graphics settings for BGMI, also, we will mention the best settings for footsteps in BGMI. Even best BGMI settings for smooth gameplay if you are having less specs device. We will discuss the best BGMI settings. It might vary upon each smartphone, yet you need not worry as we have covered it all for you. So without any further ado, let’s head into the article. Table of Content  [ hide ] 1  Best BGMI Settings 1.1  Best Graphi...