SQLAlchemy 介绍;
SQLAlchemy是Python编程语言下的一款开源软件。提供了SQL工具包及对象关系映射(ORM)工具,使用MIT许可证发行。
SQLAlchemy“采用简单的Python语言,为高效和高性能的数据库访问设计,实现了完整的企业级持久模型”。SQLAlchemy的理念是,SQL数据库的量级和性能重要于对象 集合;而对象集合的抽象又重要于表和行。因此,SQLAlchmey采用了类似于Java里Hibernate的数据映射模型,而不是其他ORM框架采用的Active Record模型。不过,Elixir 和declarative等可选插件可以让用户使用声明语法。
2.主要描述 SQLAlchemy (创建数据表,增,删,改,查)
2.1 配置MYSQL连接器
""" “创建flask mysql 连接配置文件;文件名称 config """ config 文件内容如下: ##########SQLalchemy 连接数据库示例####### #dialect+driver://username:password@host:port/database DIALECT = 'mysql' DRIVER = 'mysqldb' USERNAME = 'python' PASSWORD = '123456' HOST = '192.168.0.104' PORT = '3306' DATABASE = 'Scier' SQLALCHEMY_DATABASE_URI ="{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(DIALECT,DRIVER,USERNAME, PASSWORD,HOST,PORT,DATABASE) SQLALCHEMY_TRACK_MODIFICATIONS = False
2.2 SQLAlchemy 数据库数据表字段设置;
""" 创建数据表和数据字段设置 """ # -*- coding: utf-8 -*- import datetime from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class ipwhilt(db.Model): #######ip 白名单######## __tablename__ = 'bmc_ipwhilt' id = db.Column(db.Integer, primary_key=True, autoincrement=True) ip = db.Column(db.String(24), nullable=True) desc = db.Column(db.String(128), nullable=True) owner = db.Column(db.String(64), nullable=True) create_time = db.Column(db.DateTime(timezone=False), default=datetime.datetime.now()) def to_dict(self): return {"id": self.id, "ip": self.ip, "desc": self.desc,"owner": self.owner} class channel(db.Model): ########认证code########## __tablename__ = 'bmc_channel' id = db.Column(db.Integer, primary_key=True, autoincrement=True) uuid = db.Column(db.String(64), nullable=True) desc = db.Column(db.String(128), nullable=True) ########这个uuid 给谁用########### owner = db.Column(db.String(64), nullable=True) uuid_use = db.Column(db.String(64), nullable=True) #######这个uuid 给那个系统使用(用途) create_time = db.Column(db.DateTime(timezone=False), default=datetime.datetime.now()) def to_dict(self): return {"id": self.id, "uuid": self.uuid, "desc": self.desc, "uuid_use": self.uuid_use,"owner": self.owner}
2.3 数据新增功能实现;
from flask import Blueprint from flask import request, Response channelUrl = Blueprint('channel', __name__) @channelUrl.route('/uuid/v1', methods=['GET', 'POST', 'DELETE','PUT']) def channelMain(): import json if request.method == "GET": return anisbleSelectUuidChanne() elif request.method == "POST": return channelRun() elif request.method == "DELETE": return channelDelete() elif request.method == "PUT": return channelRun(True) else: data = "不支持该方法02" return Response(json.dumps({"code": 1, "data": data}), mimetype='application/json') def channelRun(isUpdate=False): import json Data = request.get_json() channeldesc = Data.get('desc', None) channelOwner = Data.get('owner', None) channelUse = Data.get('uuid_use', None) if channeldesc and channelOwner and channelUse: try: if isUpdate: id = Data.get("id") data = anisbleAddUuidChannel(channeldesc, channelOwner, channelUse,id) else: data = anisbleAddUuidChannel(channeldesc, channelOwner, channelUse) except Exception as e: print(e) data = {"code": 500, "data": "必传参数不能为空", "message": str(e)} else: data = {"code": 1, "data": "必传参数不能为空", "message": "failure"} return Response(json.dumps(data), mimetype='application/json') def anisbleAddUuidChannel(desc, owner, uuid_use, id=None): from models import db from models import channel import uuid uuid = str(uuid.uuid1()) try: if id: channel.query.filter_by(id=id).update({"desc": desc, "owner": owner, "uuid_use": uuid_use}) msg = "Update Success" else: channelDataInsert = channel(desc=desc, owner=owner, uuid=uuid, uuid_use=uuid_use) db.session.add(channelDataInsert) data = """你申请{},认证ID: {}""".format(uuid_use, uuid) db.session.commit() return {"code": 0, "data": data, "message": msg} except Exception as e: print(e) return {"code": 1, "data": None, "message": str(e)}
2.4 数据新增页面测试;
2.5 数据删除功能实现;
def channelDelete(): import json Data = request.get_json() channelId = Data.get('id', None) data = anisbleDeleteUuidChanne(channelId) return Response(json.dumps(data), mimetype='application/json')
2.6 数据修改和新增代码一致;
.........................................略
2.6 数据查询;
def anisbleSelectUuidChanne(): import json from models import channel from tools.config import ChanneUuidHeader,WhilteUuidField queryData = channel.query.all() data=[i.to_dict() for i in queryData] if "opsAdminForm" in request.args: return Response(json.dumps({"code": 0, "data":WhilteUuidField}), mimetype="application/json") else: try: queryData = channel.query.all() return Response(json.dumps( {"code": 0,"isAdmin":True, "data": data, "columns": ChanneUuidHeader, "message": "success"}), mimetype='application/json') except Exception as e: return Response(json.dumps({"code": 1, "data": str(e), "message": "failure"}), mimetype='application/json')