DEV Community

Shubham Singh
Shubham Singh

Posted on

Flask QuickSheet

Alt Text

Setup Environment

$ python -m venv venv
Enter fullscreen mode Exit fullscreen mode

To activate

$ source venv/Scripts/activate
Enter fullscreen mode Exit fullscreen mode

To Deactivate

$ deactivate
Enter fullscreen mode Exit fullscreen mode

Or

$ pip install pipenv

$ pipenv install
Enter fullscreen mode Exit fullscreen mode

activate

$ pipenv shell
Enter fullscreen mode Exit fullscreen mode

deactivate

$ exit
Enter fullscreen mode Exit fullscreen mode

Package install

$ pipenv install package-name
Enter fullscreen mode Exit fullscreen mode

Install Flask and Setup

$pip install flask
$pip install python-dotenv
$touch .flaskenv
Enter fullscreen mode Exit fullscreen mode

In file .flaskenv :

FLASK_ENV=development
FLASK_APP=main.py 
Enter fullscreen mode Exit fullscreen mode

Or

$ set FLASK_APP=main
$ set FLASK_ENV=development
$ flask run
Enter fullscreen mode Exit fullscreen mode

Note : command prompt use “set” and in bash shell use “export”

Install the dependencies:

$ pip install –r requirements.txt
Enter fullscreen mode Exit fullscreen mode

Basic Structure

Main.py

from flask import Flask
app = Flask(__name__)
@app.route("/")
@app.route("/index")
def index():
    return "<h1>Hello Earth!!</h1>"
Enter fullscreen mode Exit fullscreen mode

*Run Application *

$ flask run
Enter fullscreen mode Exit fullscreen mode

Flask app Configration

Config.py

import os
class Config(object):
    SECRET_KY = os.environ.get('SECRET_KEY') or "secret_string"
Enter fullscreen mode Exit fullscreen mode

main.py

from config import Config
app.config.from_object(Config)
Enter fullscreen mode Exit fullscreen mode

MongoDB Configration and modeling

Main.py

from flask_mongoengine import MongoEngine
db = MongoEngine()
db.init_app(app)
class Course(db.Document):
    course_id   =   db.StringField( max_length=10, unique=True )
    credits     =   db.IntField()
    term        =   db.StringField( max_length=25 )
Enter fullscreen mode Exit fullscreen mode

Postgresql

setup your database in config.py:
SQLALCHEMY_DATABASE_URI = 'postgresql://username:password@localhost:5432/databaseName'
SQLALCHEMY_TRACK_MODIFICATIONS = False
Enter fullscreen mode Exit fullscreen mode

For Database create at PostgreSQL using psql shell

postgres-# CREATE DATABASE learninghub;
Enter fullscreen mode Exit fullscreen mode

You can check the available database list using \l

postgres-# \l
Enter fullscreen mode Exit fullscreen mode

command to connect/select a desired database

postgres=# \c learninghub;
Enter fullscreen mode Exit fullscreen mode

model.py

class User(db.Model):
    __tablename__ = 'user'
    user_id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(), nullable=False)
Enter fullscreen mode Exit fullscreen mode

Database Migration

Main.py

from flask_migrate import Migrate
db = SQLAlchemy(app)
migrate = Migrate(app, db)
Enter fullscreen mode Exit fullscreen mode

Create Migration

  $  flask db init
Enter fullscreen mode Exit fullscreen mode

You can then generate an initial migration

  $ flask db migrate -m "Initial migration."
Enter fullscreen mode Exit fullscreen mode

Then you can apply the migration to the database:

  $ flask db upgrade

Enter fullscreen mode Exit fullscreen mode

POST request

Main.py

@app.route("/enrollment", methods=["GET","POST"])
def enrollment():
    id = request.form.get('courseID')
    term = request.form.get('term')
    return render_template("enrollment.html", enrollment=True, data={"id":id,"term":term})  
Enter fullscreen mode Exit fullscreen mode

html page

<form action="{{url_for('enrollment')}}" method="POST">
                        <input type="hidden" name="courseID" value="{{data['courseID']}}">
                        <input type="hidden" name="term" value="{{data['term']}}">
                    <button>Enroll</button>
                </form>
Enter fullscreen mode Exit fullscreen mode

GET request

id = request.args.get('courseID')
Enter fullscreen mode Exit fullscreen mode

Templates rander

from flask import render_template
return render_template('home.html')
Enter fullscreen mode Exit fullscreen mode

Redirect page

from flask import redirect, url_for
return redirect(url_for('function_name'))
Enter fullscreen mode Exit fullscreen mode

Flash message

Main.py

from flask import flash
flash('welcome to home!!!')
Enter fullscreen mode Exit fullscreen mode

html page

<div>
{% for message in get_flashed_messages() %}
<h2>{{ message }}</h2>
{% endfor %}
</div>
Enter fullscreen mode Exit fullscreen mode

File Upload

Main.py

from werkzeug.utils import secure_filename
import os
if  request.method =='POST':
    f = request.files['file']
    name = secure_filename(f.filename)
    f.save(os.path.join(os.getcwd(),name))
Enter fullscreen mode Exit fullscreen mode

html page

<form action="upload", method="post", enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit">
</form>
Enter fullscreen mode Exit fullscreen mode

Page not found error handle

@app.errorhandler(404)
def page(error):
    return "page not available, please try other url",404
Enter fullscreen mode Exit fullscreen mode

Top comments (0)