TL;DL Udemy attendance record for the following courses
Web application development course with Python + Flask! !! ~ Master Flask from 0 to create SNS ~ https://www.udemy.com/course/flaskpythonweb/
This article describes application management with Flask's BluePrint and password encryption with bcrypt.
A function to be used when you want to manage the created application by grouping it by unit such as function.
For example, if you want to manage the modules of the personal information management function (site1) and the data inquiry function (site2) separately, you can manage them separately using BluePrint so that even one application looks like an internal management. Can be managed separately as multiple applications.
Basic structure
syntax
format | sample | URL example created |
---|---|---|
BluePrint(Site name, __name__, url_prefix='/Character string used as url') | mysite1_bp = Blueprint('mysite1', name, url_prefix='/site1') | http://www.xxxx/site1/hello |
from flask import Blueprint, render_template
'''Create a BlurPrint instance'''
mysite1_bp = Blueprint('mysite1', __name__, url_prefix='/site1')
@mysite1_bp.route('/hello')
def hello():
return render_template('mysite1/hello.html')
from flask import Flask
def create_app():
app = Flask(__name__)
from flaskr.mysite1.views import mysite1_bp
from flaskr.mysite2.views import mysite2_bp
app.register_blueprint(mysite1_bp)
app.register_blueprint(mysite2_bp)
return app
from flaskr import create_app
from flask import render_template
app = create_app() # __init__.Get from app
@app.route('/')
def home():
return render_template('home.html')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
Encrypt passwords using Flask-Bcrypt.
:At the time of inport, "flask"_Note that "bcrypt" and the word feeling are underscore
>>> from flask_bcrypt import Bcrypt
:Creating a bcrypt object
>>> bcrypt = Bcrypt()
>>> testpass = 'password'
:Password hashing
>>> hashed_password = bcrypt.generate_password_hash(password=testpass)
>>> hashed_password
b'$2b$12$3B0I.CHMIEya1OdyI/m44Od7I.TKhRLiOA.EMMWQP3MgUXgr9dkYG'
:Correct / incorrect comparison with hashed password
>>> bcrypt.check_password_hash(hashed_password, 'password')
True
>>> bcrypt.check_password_hash(hashed_password, 'pass')
False
sample
from flask_bcrypt import generate_password_hash, check_password_hash
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(64), unique=True, index=True)
username = db.Column(db.String(64), index=True)
password = db.Column(db.String(128))
def __init__(self, email, username, password):
self.email = email
self.username = username
#Encrypt the password value passed from the form and store it in a variable.
self.password = generate_password_hash(password)
def validate_password(self, password):
#Compare if the password passed to the function is correct.
return check_password_hash(self.password, password)
Recommended Posts