• Flask学习笔记(大型程序结构)


    1、项目结构

    |-FFlask
        |-config.py
        |-manage.py
        |-app/
            |-templates/
                |-base.html
                |-index.html
                |-404.html
                |-500.html
            |-static/
                |-images/
                    |-404.jpg
            |-main/
                |-__intit__.py
                |-errors.py
                |-forms.py
                |-views.py
            |-__init__.py
            |-models.py
        

    2、程序

    管理文件

     1 from flask_script import Manager
     2 from flask_migrate import Migrate, MigrateCommand
     3 from app import app
     4 from app01 import db
     5 
     6 migrate = Migrate(app, db)
     7 
     8 manager = Manager(app)
     9 manager.add_command('db', MigrateCommand)
    10 
    11 if __name__ == '__main__':
    12     manager.run()
    manger.py

    配置文件

     1 import os
     2 
     3 basedir = os.path.abspath(os.path.dirname(__file__))
     4 
     5 class Config:
     6     SECRET_KEY = os.environ.get('SECRET_KEY') or '1'
     7     SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@127.0.0.1/world?charset=utf8'
     8 #    orm操作自动commit
     9 #    SQLALCHEMY_COMMIT_ON_TEARDOWN = True
    10     SQLALCHEMY_TRACK_MODIFICATIONS = True
    11     @staticmethod
    12     def init_app(app):
    13         pass
    config.py

    使用工厂函数完成初始化,在调用create_app()时创建app,并在函数中注册蓝本,完成配置等所有的初始化工作

     1 from flask import Flask,render_template
     2 from flask_sqlalchemy import SQLAlchemy
     3 from config import Config
     4 
     5 db = SQLAlchemy()
     6 
     7 def create_app():
     8     app = Flask(__name__)
     9     app.config.from_object(Config)
    10     Config.init_app(app)
    11     db.init_app(app)
    12     from .main import main as main_blueprint
    13     app.register_blueprint(main_blueprint)
    14     return app
    app/__init__.py

    创建蓝本,蓝本就是app01、app02这种子程序

    1 from flask import Blueprint
    2 
    3 main = Blueprint('main',__name__)
    4 from . import views,errors
    app/main/__init__/py

    蓝本中的错误处理程序

     1 from flask import render_template
     2 from . import main
     3 
     4 @main.app_errorhandler(404)
     5 def page_not_found(e):
     6     return render_template('404.html'),404
     7 
     8 @main.app_errorhandler(500)
     9 def internal_server_error(e):
    10     return render_template('500.html'),500
    app/main/errors.py

    蓝本中的主逻辑

     1 from datetime import datetime
     2 from  flask import render_template,session,redirect,url_for
     3 
     4 from . import main
     5 from .forms import NameForm
     6 from .. import db
     7 from .. import models
     8 
     9 @main.route('/',methods=['GET','POST'])
    10 def index():
    11     form = NameForm()
    12     if form.validate_on_submit():
    13         session['name'] = form.name.data
    14         session['ip'] = form.ip.data
    15         form.name.data=''
    16         form.ip.data=''
    17         return redirect(url_for('.index'))
    18     return render_template('index.html',form=form,name=session.get('name'),ip=session.get('ip'))
    app/main/views.py

    蓝本的模型

     1 from app import db
     2 
     3 
     4 class Role(db.Model):
     5     __tablename__ = 'roles'
     6     id = db.Column(db.Integer,primary_key=True)
     7     name = db.Column(db.String(64),unique=True)
     8     users = db.relationship('User',backref='role')
     9     def __repr__(self):
    10         return '<Role %r>'%self.name
    11 
    12 class User(db.Model):
    13     __tablename__ = 'users'
    14     id = db.Column(db.Integer,primary_key=True)
    15     username = db.Column(db.String(64),unique=True,index=True)
    16     role_id = db.Column(db.Integer,db.ForeignKey('roles.id'))
    17     def __repr__(self):
    18         return '<Role %r>'%self.username
    app/main/models.py

    蓝本的forms

    1 from flask_wtf import FlaskForm
    2 from wtforms import StringField,SubmitField
    3 from wtforms.validators import DataRequired,IPAddress
    4 
    5 
    6 class NameForm(FlaskForm):
    7     name = StringField('你叫啥:',validators=[DataRequired()])
    8     ip = StringField('IP地址:',validators=[IPAddress()])
    9     submit = SubmitField('提交;-)')
    app/main/forms.py

    蓝本中的html

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     {% block head %}
     6     <title>----{% block title %}{% endblock %}----</title>
     7     {% endblock %}
     8 </head>
     9 <body>
    10 <p>Flask的Base页面</p>
    11     {% block body %}
    12     {% endblock %}
    13 </body>
    14 </html>
    base.html
     1 {% extends 'base.html' %}
     2 <!--head在基模板中不是空的,使用super()获取原本内容-->
     3 {% block head %}{{ super() }}{% endblock %}
     4 {% block title %}首页{% endblock %}
     5 {% block body %}
     6     <p>首页的body</p>
     7     <div>
     8     Hello!{{ name }}--{{ ip }}
     9     </div>
    10     <div>
    11     <form method="post" action="">
    12         {{ form.hidden_tag() }}
    13         {{ form.name.label }}{{ form.name() }}<br>
    14         {{ form.ip.label }}{{ form.ip() }}<br>
    15         {{ form.submit() }}
    16     </form>
    17     </div>
    18 {% endblock %}
    index.html
    1 {% extends 'base.html' %}
    2 {% block head %}{{ super() }}{% endblock %}
    3 {% block title %}404{% endblock %}
    4 {% block body %}
    5     <image src="{{ url_for('static',filename='images/404.jpg') }}"></image>
    6 {% endblock %}
    404.html
    1 {% extends 'base.html' %}
    2 {% block head %}{{ super() }}{% endblock %}
    3 {% block title %}500{% endblock %}
    4 {% block body %}<h1>500</h1>{% endblock %}
    500.html

    启动脚本

    1 import os
    2 from app import create_app,db
    3 from app.models import User,Role
    4 
    5 app = create_app()
    6 
    7 if __name__=='__main__':
    8     app.run()
    manage.py

    3、结构化的项目是为了更好的管理文件,可读性更强,功能上与《基础》相同

  • 相关阅读:
    分布式架构高可用架构篇_activemq高可用集群(zookeeper+leveldb)安装、配置、高可用测试
    @interface [SpringMVC+redis]自定义aop注解实现控制器访问次数限制
    ActiveMQ安装与持久化消息
    activemq 5.13.2 jdbc 数据库持久化 异常 找不到驱动程序
    java通过Comparable接口实现字符串比较大小排序的简单实例
    微信小程序--火车票查询
    【调试】如何使用javascript的debugger命令进行调试(重要)
    【调试】js调试console.log使用总结图解(重要)
    ajax提交表单
    一个项目的404错误处理页面
  • 原文地址:https://www.cnblogs.com/cx59244405/p/9747881.html
Copyright © 2020-2023  润新知