The seventh article on the birth of a flask-based web application mainly introduces the adjustment of the organizational structure, which has some reference value, interested friends can refer to the seventh article about the birth of a flask-based web application. This article mainly introduces the adjustment of the organizational structure, which has a certain reference value, for more information, see
Now all the Py code is written in the default. py file. Obviously, once the program becomes responsible for this method, it will bring a lot of problems for development and maintenance.
The Flask framework does not require a project to use a specific organizational structure, so the organizational structure used here is not necessarily the same as that in other projects.
In a single file, all the configurations are written in a single file. However, it is obviously inappropriate to do so after multi-file reconstruction, therefore, it is necessary to create an independent config file:
class Config: SECRET_KEY="Niu_blog String" SQLALCHEMY_DATABASE_URI='mysql://root:1234@localhost/cblog' SQLALCHEMY_COMMIT_ON_TEARDOWN=True LOGIN_PROTECTION="strong" LOGIN_VIEW="login"
Then initialize the file (app/_ init _. py ):
from flask import Flaskfrom flask_bootstrap import Bootstrapfrom flask_sqlalchemy import SQLAlchemyfrom flask_login import LoginManagerimport pymysqlpymysql.install_as_MySQLdb()from config import Configbootstrap = Bootstrap()db = SQLAlchemy()login_manager=LoginManager();def create_app(): app = Flask(__name__) app.config.from_object(Config) bootstrap.init_app(app) login_manager.init_app(app) login_manager.session_protection=Config.LOGIN_PROTECTION login_manager.login_view=Config.LOGIN_VIEW db.init_app(app) return app
The blueprint is also used for further modularization. the functions of the blueprint are similar to the area in asp.net mvc. The View methods of different modules are integrated and differentiated by URLs, first, the index page is defined as the main blueprint. the method is as follows:
Create main folder
Create a new blueprint in the folder and initialize the file _ init _. py.
Create view method file view. py
Method for creating the error page view in the master blueprint: errors. py
The initialization file code is as follows:
From flask import Blueprintmain = Blueprint ("main" ,__ name _) # create a Blueprint from. import errors, views
Currently, the View method file has only one index method. the code is as follows:
from flask import render_templatefrom . import main@main.route("/")def index(): return render_template("index.html",site_name='myblog')
Error page code omitted
The URL of the master blueprint does not use the prefix.
Then, log on to the registration and logout page to set the permission blueprint (auth). The permission blueprint initialization code is as follows:
from flask import Blueprintauth=Blueprint("auth",__name__)from . import views
Views are migrated from previous views:
From. import authfrom .. import db, login_managerfrom .. forms. loginForm import LoginForm (*) from .. models. user import User (*) from flask_login import login_user, logout_userfrom flask import render_template, flash, redirect, url_for@auth.route ("/login", methods = ["GET", "POST"]) def login (): form = LoginForm () print (url_for ("main. index ") if form. validate_on_submit (): username = form. username. data password = form. password. data print (User) user = User. query. filter_by (username = username, password = password ). first () if user is not None: login_user (user, form. remember_me.data) print (url_for ("main. index ") return redirect (url_for (" main. index ") else: flash (" the user name or password you entered is incorrect ") return render_template ("/auth/login.html ", form = form) # The returned result is still return redirect (url_for ("main. index ") return render_template ("/auth/login.html ", form = form) @ auth. route ("/logout", methods = ["GET", "POST"]) def logout (): logout_user () return redirect (url_for ("main. index ") @ login_manager.user_loaderdef load_user (user_id): return User. query. get (int (user_id ))
Pay attention to the two lines marked with asterisks. Be sure to pay attention to the py file and the py object. the import object must be in the file.
The code in the LoginForm file is as follows:
From flask_wtf import FlaskFormfrom wtforms import StringField, PasswordField, SubmitField, BooleanFieldfrom wtforms. validators import DataRequiredclass LoginForm (FlaskForm): username = StringField ("Enter the user name", validators = [DataRequired ()]) password = PasswordField ("enter the password ") remember_me = BooleanField ("Remember Me") submit = SubmitField ("login ")
The code in the User file is as follows:
from flask_login import UserMixinfrom .. import dbclass User(UserMixin,db.Model): __tablename__="users" id=db.Column(db.Integer,primary_key=True) username=db.Column(db.String(50),unique=True,index=True) password=db.Column(db.String(50)) nickname=db.Column(db.String(50)) email=db.Column(db.String(100)) birthday=db.Column(db.DateTime) gender=db.Column(db.Integer) remark=db.Column(db.String(200)) role_id=db.Column(db.Integer,db.ForeignKey("roles.id"))
Note that the import method of the flask plug-in is changed from flask. ext. * to the flask _ * recommended in the new version. thank you for your reminder.
Of course, you have to register the blueprint, so the code of the create_app method is:
Def create_app (): app = Flask (_ name _) app. config. from_object (Config) bootstrap. init_app (app) login_manager.init_app (app) login_manager.session_protection = Config. LOGIN_PROTECTION login_manager.login_view = Config. LOGIN_VIEW db. init_app (app) from. main import main as main_blueprint from. auth import auth as auth_blueprint app. register_blueprint (main_blueprint) # app with no url prefix. register_blueprint (auth_blueprint, url_prefix = "/auth") # The url prefix is/auth return app
The last modification is to start the running mode. create a new manager. py file and configure the startup code as follows:
From app import create_app, dbfrom flask_script import Manager, Shellfrom flask_migrate import Migrate, MigrateCommandfrom app. models. user import Userfrom app. models. role import Roleimport pymysqlpymysql. install_as_MySQLdb () app = create_app () manager = Manager (app); migrate = Migrate (app, db) def make_shell_context (): return dict (app = app, db = db, user = User, Role = Role) # register shell command manager. add_command ("db", MigrateCommand) # adds a db command for database migration manager. add_command ("shell", Shell (make_context = make_shell_context () if _ name _ = '_ main _': manager. run ()
Run it in the most practical way. The running result is the same as that of default. py. The system directory is as follows for your reference only:
The above is the details of the example of organizational structure adjustment (python). For more information, see other related articles in the first PHP community!