flask-script 离线脚本
1 from flask_demo import create_app 2 from flask_script import Manager 3 app = create_app() 4 manager = Manager(app) 5 6 @manager.command 7 def custom(arg): 8 """ 9 自定义命令 10 python manage.py custom 123 11 :param arg: 12 :return: 13 """ 14 print(arg) 15 16 17 @manager.option('-n', '--name', dest='name') 18 @manager.option('-u', '--url', dest='url') 19 def cmd(name, url): 20 """ 21 自定义命令 22 执行: python manage.py cmd -n wupeiqi -u http://www.oldboyedu.com 23 执行: python manage.py cmd --name wupeiqi --url http://www.oldboyedu.com 24 :param name: 25 :param url: 26 :return: 27 """ 28 print(name, url) 29 30 31 32 33 34 if __name__ == '__main__': 35 app.run() 36 manager.run()
- 使其具有类似django启动的方式
- Flask Script扩展提供向Flask插入外部脚本的功能,包括运行一个开发用的服务器,一个定制的Python shell,设置数据库的脚本,cronjobs,及其他运行在web应用之外的命令行任务;使得脚本和系统分开;
在控制台执行命令:
python manage.py 命令名 参数1 参数2 ...
flask-sqlalchemy 专属于flask的 alchemy
将sqlalchemy 的engine session Base 操作封装在db 对象,从而使得代码更加简洁
from flask import Flask from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() def create_app(): app = Flask(__name__) app.config.from_object('setting.DevelopmentConfig') from flask_demo.views.account import ac app.register_blueprint(ac) db.init_app(app) db.create_all(app=app) # 初始化创建表 return app
from sqlalchemy import Column, Integer, String, UniqueConstraint, Index,DateTime,ForeignKey from flask_demo import db class Users(db.Model): __tablename__ = 'users' id = Column(Integer, primary_key=True,autoincrement=True) name = Column(String(32),nullable=False,unique=True)
离线脚本之操作数据库
""" Web运行时,flask程序运行起来,用户通过浏览器访问 离线脚本,自定义的一个py文件+使用flask中定义好的功能 """ from flask_demo import db from flask_demo import create_app from flask_demo import models app = create_app() with app.app_context(): # db.drop_all() # 删除数据库 # db.create_all() # 创建数据库 data = db.session.query(models.Users).all() # 查询数据库 print(data)
创建orm session 的两种方法
import time import threading from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy import create_engine from db import Users engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/s6", max_overflow=0, pool_size=5) Session = sessionmaker(bind=engine) def task(arg): session = Session() obj1 = Users(name="alex1") session.add(obj1) session.commit() for i in range(10): t = threading.Thread(target=task, args=(i,)) t.start()
方式二(推荐): import models from threading import Thread from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session engine =create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/s8day128db?charset=utf8",pool_size=2,max_overflow=0) XXXXXX = sessionmaker(bind=engine) session = scoped_session(XXXXXX) def task(): # 1. 原来的session对象 = 执行session.registry() # 2. 原来session对象.query data = session.query(models.Classes).all() print(data) session.remove() for i in range(10): t = Thread(target=task) t.start() flask-session默认也是使用的第二种方式:scoped_session
flask-migrate 组件
from flask_migrate import Migrate,MigrateCommand app = create_app() manager = Manager(app) Migrate(app, db) """ # 数据库迁移命名 python manage.py db init python manage.py db migrate # makemigrations python manage.py db upgrade # migrate """ manager.add_command('db', MigrateCommand)
flask自定义组件
from flask import request,session,redirect class Auth(object): def __init__(self,app=None): self.app = app if app: self.init_app(app) def init_app(self,app): app.auth_manager = self self.app = app app.before_request(self.check_login) app.context_processor(self.context_processor) def check_login(self): """ 检查用户是否已经登录 :return: """ if request.path == '/login': return user = session.get('user') if not user: return redirect('/login') def context_processor(self): user = session.get('user') return dict(current_user=user) def login(self,data): """ 将用户登录信息,放入session :param data: :return: """ session['user'] = data def logout(self): """ 将用户登录信息,放入session :param data: :return: """ del session['user']
@ac.route('/login',methods=['GET','POST']) def login(): if request.method == 'GET': return render_template('login.html') else: user = request.form.get('user') pwd = request.form.get('pwd') obj = db.session.query(models.Users).filter(models.Users.name==user,models.Users.pwd==pwd).first() db.session.remove() if not obj: return render_template('login.html',msg='用户名或密码错误') current_app.auth_manager.login(user) return redirect('/index') @ac.route('/logout') def logout(): current_app.auth_manager.logout() return redirect('/login')
flask多app离线脚本多app应用
with app01.app_context(): print(current_app) with app02.app_context(): print(current_app) print(current_app)
- 多app应用(url进行处理和分发) from flask import Flask from werkzeug.wsgi import DispatcherMiddleware from werkzeug.serving import run_simple app01 = Flask('app01') app02 = Flask('app02') @app01.route('/login') def login(): return 'app01.login' @app02.route('/index') def index(): return 'app02.index' dm = DispatcherMiddleware(app01,{ '/app02': app02, }) if __name__ == '__main__': run_simple('localhost', 5000,dm)
flask的信号blinker
Flask框架中的信号基于blinker,其主要就是让开发者可是在flask请求过程中定制一些用户行为。
pip3 install blinker
request_started = _signals.signal('request-started') # 请求到来前执行 request_finished = _signals.signal('request-finished') # 请求结束后执行 before_render_template = _signals.signal('before-render-template') # 模板渲染前执行 template_rendered = _signals.signal('template-rendered') # 模板渲染后执行 got_request_exception = _signals.signal('got-request-exception') # 请求执行出现异常时执行 request_tearing_down = _signals.signal('request-tearing-down') # 请求执行完毕后自动执行(无论成功与否) appcontext_tearing_down = _signals.signal('appcontext-tearing-down')# 请求上下文执行完毕后自动执行(无论成功与否) appcontext_pushed = _signals.signal('appcontext-pushed') # 请求上下文push时执行 appcontext_popped = _signals.signal('appcontext-popped') # 请求上下文pop时执行 message_flashed = _signals.signal('message-flashed') # 调用flask在其中添加数据时,自动触发
#!/usr/bin/env python # -*- coding:utf-8 -*- from flask import Flask, current_app, flash, render_template from flask.signals import _signals app = Flask(import_name=__name__) # 自定义信号 xxxxx = _signals.signal('xxxxx') def func(sender, *args, **kwargs): print(sender) # 自定义信号中注册函数 xxxxx.connect(func) @app.route("/x") def index(): # 触发信号 xxxxx.send('123123', k1='v1') return 'Index' if __name__ == '__main__': app.run()