Flask QuickSheet
Tags: python, flask, webdev, restapi
Published: 2020-06-30 06:25:32

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/qsr7rgy3qqcnauwv6r3c.png)

# Setup Environment 
```
$ python -m venv venv
```
To activate
```
$ source venv/Scripts/activate
```
To Deactivate
```
$ deactivate
```
### Or
```
$ pip install pipenv

$ pipenv install
```
activate
```
$ pipenv shell
```

deactivate
```
$ exit
```

# Package install 
```
$ pipenv install package-name
```
### Install Flask and Setup
```
$pip install flask
$pip install python-dotenv
$touch .flaskenv
```

#### In file .flaskenv :
```
FLASK_ENV=development
FLASK_APP=main.py 
```
### Or
```
$ set FLASK_APP=main
$ set FLASK_ENV=development
$ flask run
```
*Note* : command prompt use “set” and in bash shell use “export”

### *Install the dependencies*:
```
$ pip install –r requirements.txt
```

# Basic Structure
*Main.py*
```
from flask import Flask
app = Flask(__name__)
@app.route("/")
@app.route("/index")
def index():
    return "<h1>Hello Earth!!</h1>"
```

*Run Application *
```
$ flask run
```

## Flask app  Configration
*Config.py*
```
import os
class Config(object):
    SECRET_KY = os.environ.get('SECRET_KEY') or "secret_string"
```
*main.py*
```
from config import Config
app.config.from_object(Config)
```

# 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 )
```

### *Postgresql*
##### setup your database in *config.py*:
```
SQLALCHEMY_DATABASE_URI = 'postgresql://username:password@localhost:5432/databaseName'
SQLALCHEMY_TRACK_MODIFICATIONS = False
```
#### For Database create at PostgreSQL using *psql* shell
```
postgres-# CREATE DATABASE learninghub;
```
You can check the available database list using \l
```
postgres-# \l
```
command to connect/select a desired database
```
postgres=# \c learninghub;
```

*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)
```

# Database Migration 
*Main.py*
```
from flask_migrate import Migrate
db = SQLAlchemy(app)
migrate = Migrate(app, db)
```
Create Migration
```
  $  flask db init
```
You can then generate an initial migration
```
  $ flask db migrate -m "Initial migration."
```
Then you can apply the migration to the database:
```
  $ flask db upgrade

```

## 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})  
``` 
*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>
```
## GET  request
```
id = request.args.get('courseID')
```

## Templates rander
```
from flask import render_template
return render_template('home.html')
```
## Redirect page
```
from flask import redirect, url_for
return redirect(url_for('function_name'))
```
## Flash message
*Main.py*
```
from flask import flash
flash('welcome to home!!!')
```
*html page*
```
<div>
{% for message in get_flashed_messages() %}
<h2>{{ message }}</h2>
{% endfor %}
</div>
```
## 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))
```
*html page*
```
<form action="upload", method="post", enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit">
</form>
```
## Page not found error handle
```
@app.errorhandler(404)
def page(error):
    return "page not available, please try other url",404
```