The birth of a Web application (7)

Source: Internet
Author: User

Now all the PY code is written in the default.py file, it is obvious that in this method, once the program becomes responsible, then no matter for development and maintenance, will bring a lot of problems.

The Flask framework does not force a project to use a specific organizational structure, so the organizational structure used here is not necessarily the same as in other projects.

According to the code in default.py, can be broadly divided into three categories: form model, data model, view method, so the model is also in the network to distinguish. So according to the experience of other languages (Java), each class is a py file, put in the corresponding folder

In a single file, all configurations are written in a single file, and after a multi-file refactoring, it is obviously inappropriate to do so, so it is necessary to create a separate config file:

class Config:    SECRET_KEY="Niu_blog String"    SQLALCHEMY_DATABASE_URI=‘mysql://root:[email protected]/cblog‘    SQLALCHEMY_COMMIT_ON_TEARDOWN=True    LOGIN_PROTECTION="strong"    LOGIN_VIEW="login"

Then the initialization 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

Further modularity to use the blueprint, the blueprint of the function of some similar to ASP. NET MVC area, the different modules of the view method is integrated, and through the URL to distinguish, the first entry is the index page defined as the main blueprint, the method is as follows:

    1. Create a main folder
    2. New Blueprint initialization file in folder __init__.py
    3. Create a View method file view.py
    4. Create error Page view method in the main blueprint errors.py

The initialization file code is as follows:

from flask import Blueprintmain=Blueprint("main",__name__) # 创建蓝本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 slightly

The URL of the main blueprint does not use a prefix

Then log in to register the page set to the Permission Blueprint (auth), the permissions blueprint initialization code is as follows:
From flask Import Blueprint

auth=Blueprint("auth",__name__)from . import views    

The view migrates primarily to previously completed 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 fo        Rm.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 username or password you entered is wrong") return Render_template ("/auth/login.html", Form=form) # returned is still a login Record page return redirect (Url_for ("Main.index")) return Render_template ("/auth/login.html", Form=form) @auth. Route ("/logo  UT ", 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))

Note the two lines marked with an asterisk, be sure to note that the py file and the Py object must be inside the file import object

Where 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("请输入用户名",validators=[DataRequired()])    password=PasswordField("请输入密码")    remember_me=BooleanField("记住我")    submit=SubmitField("登录")

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 flask plug-in method is changed from flask.ext.* to the new version of the recommended flask_* this way, thanks to Bo friends to treat electric cabbage Reminder.

Of course, the blueprint will eventually be registered, so the code for the final 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)                    #无url前缀    app.register_blueprint(auth_blueprint,url_prefix="/auth") #url前缀为/auth    return app

The last modification is how to start the run, create a new manager.py file, 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) #注册shell命令manager.add_command("db", MigrateCommand) #新增db命令用于数据库迁移manager.add_command("shell" ,Shell(make_context=make_shell_context()))if __name__ ==‘__main__‘:    manager.run()

In the most Earth way, run running, running results and the previous only default.py the same time, the system directory is as follows, for reference only:

This chapter does not have much new things, mainly on the previous system directory, the system structure to make some adjustments, this week is busy, to prepare for the interview, to prepare for the interviews, and finally completed the commitment to their own, a weekly blog, but if according to the release time, seems to be late one day, After all, it is now over 0 points: (

The birth of a Web application (7)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.