This project is my first flask project. It's based on Corey Schafer series of videos on YouTube.
Before running the project, we need to set the environment variable FLASK_APP
. the command on windows is set
and on
linux it's export
. So we have to write the following command:
set FLASK_APP=<MAIN_FILE>
To enable the debug mode, we have to write the following command:
set FLASK_DEBUG=1
flask run
pip install flask-wtf
pip install email_validator
pip install flask-sqlalchemy
- Open shell
from <FILE> import db
- db.create_all()
<VARIABLE> = <MODEL>(<FIELDS>)
db.session.add(<VARIABLE>)
db.session.commit()
<MODEL>.query.all()
<MODEL>.query.first()
<MODEL>.query.filter_by(<FIELD>=<VALUE>).all()
<MODEL>.query.get(<ID>)
db.drop_all()
pip install flask-bcrypt
from flask_bcrypt import Bcrypt
bcrypt = Bcrypt(<APP>)
bcrypt.generate_password_hash('<PASSWORD>').decode('utf-8')
Note that hash is always different. even on the same password. So how to verify?
bcrypt.check_password_hash(<hashed_password>, <password>)
pip install flask-login
- On
__init__.py
file, addlogin_manager = LoginManager(app)
- On
models.py
, importlogin_manager
. - Now Extension needs to know to find a user by ID. So we create a
def load_user(user_id)
that gets a user from database by ID. Then we add the@login_manager.user_loader
decorator. - The extension expects our user model to have certain attributes:
is_authenticated
,is_active
,is_anonymous
,get_id()
. Therefore, we can importUserMixin
fromflask_login
and finally our user model inherits from that.
posts = Post.query.paginate()
posts.per_page
: Items per pageposts.page
: current pagefor post in posts.items
: iterate over page itemsposts = Post.query.paginate(page=2)
: get the second page's items.posts = Post.query.paginate(per_page=5)
: 5 posts per page.posts.total
: Total number of posts in all pages.for page_number in posts.iter_pages(left_edge=1, right_edge=1, left_current=1, right_current=2)
: iterate over page numbers
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
s = Serializer('secret_key_here', expires_in=30)
# expires in 30 seconds.token = s.dumps({"user_id": 1}).decode('utf-8')
s.loads(token)
# works only within 30 seconds.
pip install flask-mail
.- On
__init__.py
file, addapp.config['MAIL_SERVER'] = 'smtp.gmail.com'
(or your host's smtp server). - Add
app.config['MAIL_PORT'] = 587
. - Add
app.config['MAIL_USE_TLS'] = True
. - Add
app.config['MAIL_USERNAME'] = os.environ.get('EMAIL_USER')
. - Add
app.config['MAIL_PASSWORD'] = os.environ.get('EMAIL_PASS')
. - Add
mail = Mail(app)
. - In your code where you want to send an email, create a
Message(subject=..., sender=..., recipients=..., body=...,)
instance. Then send it usingmail.send(message)
.