flask_sqlalchemy, flask_script, flask_migrate, flask_moment,pipreqs

一 flask_sqlalchemy

  1. pip3 install flask-sqlalchemy
  2. 在__init__中,导入实例化,
    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    db = SQLAlchemy()            
    注意事项:
          - 必须在导入蓝图之前
          - 必须导入models.py 
  3. 初始化
    db.init_app(app)
  4. 在配置文件中写入配置
     # ##### SQLALchemy配置文件 #####
     SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:密码@127.0.0.1:3306/数据库名字?charset=utf8"
     SQLALCHEMY_POOL_SIZE = 10
     SQLALCHEMY_MAX_OVERFLOW = 5
  5. 生成表(使用app上下文)
    from chun import db,create_app

    app = create_app()
    app_ctx = app.app_context() # app_ctx = app/g
     with app_ctx:                                                    # __enter__,通过LocalStack放入Local中
           db.create_all()                                            # 调用LocalStack放入Local中获取app,再去app中获取配置

 

二 flask_script (只在manage.py 里修改)

  1. pip3 install flask-script
  2. from flask_script import Manager
    app = create_app()
    manager = Manager(app)

    if __name__ == '__main__':
           # app.run()
            manager.run()

  3. python manage.py runserver
    python manage.py runserver -h 127.0.0.1
    python manage.py runserver -p 8080
    python manage.py runserver -h 127.0.0.1 -p 8080
  4. 注意: 貌似结构只能时文件里面建文件,可能还需要在Terminal 里用 dir 才能执行正确

三 flask_migrate(依赖 flask_script只在manage.py 里修改)

  1. pip3 install flask-migrate 
  2. 依赖:flask-script 
  3. from flask_script import Manager
    from flask_migrate import Migrate, MigrateCommand

    app = create_app()
    manager = Manager(app)
    Migrate(app, db)
    manager.add_command('db', MigrateCommand)
    if __name__ == '__main__':
         manager.run()
         # app.run()

  4. python manage.py db init             # 执行一次就行  创建一个migrations
    python manage.py db migrate      
    python manage.py db upgrade

四  pipreqs

找到项目所需的组件和版本,不仅flask可用,其他都可用

        pip install pipreqs
        
        pipreqs ./ --encoding=utf-8 

创建一个requirements.txt 文件

 

あの,,,也可以直接执行 pip freeze > xx.txt ,   区别是上一个程序所用到的包,而这个时安装的全部包

__init__.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
# 千万注意 要放在上面

from moban.views.acount import ac
from moban.models import *


def create_app():
    app = Flask(__name__)
    app.config.from_object('settings.ProConfig')     # 注意大写
    app.register_blueprint(ac)
    # Flask-Session: 第一步示例Session
    # Session(app)
    db.init_app(app)
    return app
manage.py


from moban import create_app
from moban import db
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand

app = create_app()
manager = Manager(app)  # 导入Manger从要实例化
Migrate(app, db)

# 自定义命令 python manage.py custom 123
@manager.command
def custom(arg):
    """
    自定义命令
    python manage.py custom 123
    :param arg:
    :return:
    """
    print(arg)


@manager.option('-n', '--name', dest='name')
@manager.option('-u', '--url', dest='url')
def cmd(name, url):
    """
    自定义命令
    执行: python manage.py  cmd -n xx -u http://www.baidu.com
    :param name:
    :param url:
    :return:
    """
    print(name, url)


manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
    # app.run()
    manager.run()


# flask_script
# python manage.py runserver
# python manage.py runserver -h 127.0.0.1
# python manage.py runserver -p 8080
# python manage.py runserver -h 127.0.0.1 -p 8080
settings.py


class BaseConfig(object):
    # Flask-Session: 第二步配置
    # SESSION_TYPE = 'redis'
    # SESSION_REDIS = Redis(host='192.168.0.94', port='6379')

    # ##### SQLALchemy配置文件 #####
    SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:admin@127.0.0.1:3306/sqlacm?charset=utf8"
    SQLALCHEMY_POOL_SIZE = 10
    SQLALCHEMY_MAX_OVERFLOW = 5

    SQLALCHEMY_TRACK_MODIFICATIONS = False

    pass


class ProConfig(BaseConfig):
    pass
create_table.py
# 直接运行它,创建数据库的表结构


from moban import db, create_app

app = create_app()
app_ctx = app.app_context()    
with app_ctx:
    db.create_all()
models.py
 

# 注意是放在里面的


from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column
from sqlalchemy import Integer, String, Text, DateTime, Date
from sqlalchemy import create_engine
from . import db


class Users(db.Model):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=Text)
    name = Column(String(32), index=Text, nullable=False)

    def __repr__(self):
        return '<Users %r>' % self.name

 

views里的视图函数


from flask import Blueprint, render_template
from moban import db
from moban import models

ac = Blueprint('ac', __name__)


@ac.route('/')
def index():
    # 使用SQLAlchemy在数据库中插入一条数据
    # db.session.add(models.Users(name='XX',depart_id=1))
    # db.session.commit()
    # db.session.remove()
    result = db.session.query(models.Users).all()
    for i in result:
        print(i.name)
    db.session.remove()
    return "爸爸ll" \
           "sdasasdadd;;k"

五 flask_moment


__init__.py
 
from flask import Flask
from .views.tset import ac           # test 是个视图
from flask_moment import Moment      # pip3 install  flask_moment
 
 
def create_app():
    app = Flask(__name__)
    moment = Moment(app)             # 实例化
    app.config.from_object('settings.Config')    # 加配置
    app.register_blueprint(ac)
    return app
 
 
manage.py
 
from . import create_app
 
 
app = create_app()
if __name__ == "__main__":
    app.run()
 
 
views/test.py
 
from flask import Blueprint, render_template
from datetime import datetime
 
ac = Blueprint('ac', __name__)
 
 
@ac.route('/')
def index():
    return render_template("index.html", current_time=datetime.utcnow())
 
 
index.html
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    {{ moment.include_jquery() }}   // 导入jQ
    {{ moment.include_moment() }}   // 导入moment
    {{ moment.locale('zh-cn') }}    // 设置语言
 
</head>
<body>
<p>fuck</p>
<p>{{ current_time }}</p>    // 2019-04-28 06:36:55.134961
<p>{{ moment(current_time).format('LLLL') }}</p>  // 2019年4月28日星期日下午2点36分
<p>{{ moment(current_time).fromNow(refresh=True) }}</p> // 几秒前
<p>{{ moment().format('YYYY-MM-DD HH:mm:ss')}}</p>  // 2019-04-28 14:36:55
</body>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值