南大通用GBase 8a MPP Cluster开发接口之python篇

原文链接:https://www.gbase.cn/community/post/4311
更多精彩内容尽在南大通用GBase技术社区,南大通用致力于成为用户最信赖的数据库产品供应商。

今天给大家介绍下南大通用python驱动接口,GBase-connector-python接口是Python语言连接GBase数据库的接口驱动程序(以下简称GBase Connector)。

1 简介

1.1 GBase-connector-python简介

GBase Connector接口是基于Python Database API Specification 2.0标准编写。接口兼容标准的同时支持如下特性:

  • 完全支持GBase 8a及8a集群的特性
  • 完全支持GBase 8a及的字段类型
  • 完全支持SQL标准语法
  • 支持二进制流插入、更新
  • 支持批量插入优化
  • 支持多SQL语句执行和获取多结果集
  • 支持TCP/IP协议
  • 支持连接池操作
  • 支持SQLAlchemy、Flask、Django等主流框架
  • 支持Superset框架的使用

1.2版本信息

GBase Connector当前版本为9.5.3,是在原接口GBasePython3-9.5.2版本的基础上升级而来,增加了对Django框架和Flask框架的适配。

GBase Connector接口对应产品版本和Python版本信息如下表所示:

接口版本

GBase版本

Python版本

版本兼容性

GBase-connector-python-9.5.3

GBase 8a单机

GBase 8a集群

Python3.8、Python3.9、Python3.10、Python3.11

GBase-connector-python接口对应框架版本信息如下表所示:

接口版本

框架信息

支持框架版本

GBase-connector-python-9.5.3

SQLAlchemy

1.4.30—1.4.50

Superset

3.0.0

Flask

2.3.x、2.2.5

Django

4.2.x

1.3架构信息

2基本用法

2.1安装

GBase Connector接口可以免安装使用,也可以安装后,在Python脚本文件中进行导入使用。如果与框架结合使用,则必须安装使用。

2.1.1解压使用

在获取到GBase Connector源码压缩包后进行解压操作,将解压目录下的“lib/gbase”目录拷贝到项目工程下,并在“gbase”同级目录下创建Python脚本文件使用接口,如图所示:

2.1.2安装使用

安装时需要确保当前Python环境中已经安装了pip、setuptools和wheel(安装Python后默认自带的包)。

2.1.2.1 Windows环境下安装

进入解压后的源码目录,在setup.py文件所在目录执行如下命令:

cd GBase-connector-python-9.5.3-src
python setup.py install

显示以下信息,表示安装完成:

Installed c:\users\zqh\.conda\envs\django-42611\lib\site-packages\gbase_connector_python-9.5.3-py3.11.egg
Processing dependencies for gbase-connector-python==9.5.3
Finished processing dependencies for gbase-connector-python==9.5.3


注:ubuntu环境下不建议此安装方法。

2.1.2.2 Linux环境下安装

进入解压后的源码目录,在setup.py文件所在目录执行如下命令:

cd GBase-connector-python-9.5.3-src
# 生成whl文件(当前目录下会生成dist/gbase_connector_python-9.5.3-py3-none-any.whl)
python setup.py bdist_wheel
# 使用生成的whl文件进行安装
cd dist
pip install gbase_connector_python-9.5.3-py3-none-any.whl

显示以下信息,表示安装完成:

Processing ./gbase_connector_python-9.5.3-py3-none-any.whl
Installing collected packages: gbase-connector-python
Successfully installed gbase-connector-python-9.5.3

2.2 创建数据库连接

2.2.1 连接参数

下表描述了用于连接GBase时可用参数的定义及约束,参数后面的*表示同义参数名称:

参数名称

参数类型

默认值

描述

user(username*)

string

用户名,登录数据库的用户名

password(passwd*)

string

密码,登录数据库的密码

host

string

127.0.0.1

主机地址,GBase服务gcluster节点地址

port

int

5258

端口号,连接GBase服务使用的端口号

database(db*)

string

数据库名称,连接后默认使用的数据库

charset

string

utf8mb4

连接数据库使用的字符集

use_unicode

bool

True

是否使用 Unicode

autocommit

bool

False

是否使用自动提交,GBase开启事务功能时该参数生效

pool_name

string

连接池名称,名称限制为字母数字和特殊字符.、_、 *、 $、#,且长度不能超过64

pool_size

int

5

连接池大小,必须大于0且小于或等于32

pool_reset_session

bool

True

是否在连接返回到连接池时重置会话变量

auth_plugin

string

指定创建连接时的身份验证方式

2.2.2 创建/关闭连接
具体操作如下所示:
from gbase.connector import (connection)
# 连接兼容模式集群
conn = connection.GBaseConnection(user='gbase', password='gbase20110531',
                                host='192.168.11.121',
                                database='test')
# 连接多VC模式集群
conn = connection.GBaseConnection(user='gbase', password='gbase20110531',
                                host='192.168.11.121',
                                database='vc_name.test')
conn.close()
from gbase.connector import connect, Error
config = {
   'user': 'gbase',
   'passwd': 'gbase20110531',
   'host': '192.168.11.121',
   'db': 'test', # 多VC模式下为:vc_name.test
   'port': 5258
}
try:
   conn = connect(**config)
except Error as e:
   print(e)
finally:
   conn.close
import gbase.connector
from gbase.connector import errorcode, Error
try:
   conn = gbase.connector.connect(user='gbase',
                               database='test', host='192.168.43.121')
except Error as err:
   if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
       print("用户名或密码错误")
   elif err.errno == errorcode.ER_BAD_DB_ERROR:
       print("数据库不存在")
   else:
       print(err)
else:
   conn.close()

3第三方框架支持

3.1SQLAlchemy

SQLAlchemy 是python中通过ORM操作数据库的框架。使用SQLAlchemy不需要再去写原生的sql语句,只需要用Python的语法来操作对象,就能被自动映射为sql语句。GBase Connector的9.5.3版本针对SQLAlchemy的1.4.49版本开发了适配GBase 8a的方言包。用户通过GBase Connector驱动可以使用SQLAlchemy直接用Python语法对数据库进行操作。

3.2Superset

当前GBase Connector版本及GBase方言包是在Superset3.0.0及SQLAlchemy-1.4.49版本基础上进行适配的,Superset创建GBase的连接需要先安装GBase的方言包,安装过程参考3.1.1GBase方言包安装。

3.3Flask

在Flask中使用ORM框架需要借助SQLAlchemy框架和Flask-SQLAlchemy第三方包,在GBase Connector当前版本支持的Flask框架版本中所使用的环境中SQLAlchemy版本为1.4.49,Flask-SQLAlchemy版本为2.5.1。

3.4Django

由于Django框架自带的admin、auth、contenttypes、sessions等模块所创建的表需要依赖数据库中主键、唯一主键、外键、索引等约束,而GBase 8a作为分析型数据库是不支持这些约束功能的。所以在Django框架中使用GBase 8a需要弃用Django框架中的admin后台(参考使用案例一);如果开发需求不能舍弃admin后台,则需要借助MySQL、PostgreSQL等事务型数据库,利用Django可以连接多个数据库的特性,将admin后台所使用的表生成在事务型数据库中(参考使用案例二)。

3.4.1使用说明

在Django框架中使用ORM框架连接GBase数据库之前需要先在当前Python开发环境下安装GBase Connector。获取GBase Connector适配Djnago框架的GBase方言包源码文件,用户进入目录“gbase-dialect-Django_4.2.6”下:

  • 将名为“gbase”的目录拷贝到当前Python开发环境的Django的方言包目录下:PYTHON_HOME/.../site-packages/django/db/backends。
  • 或者下载Django-4.2.6源码文件,将“gbase”方言包文件拷贝到Django方言包目录下:Django-4.2.6/django/db/backends,然后手动安装Django框架。

然后创建Django项目,在settings.py文件中配置数据库连接路由:

DATABASES = {
   'gbase_db': {
       'ENGINE': 'gbase.connector.django',
       'NAME': 'test', # 多VC模式下为:vc_name.test
       'USER': 'gbase',
       'PASSWORD': 'gbase20110531',
       'HOST': '127.0.0.1',
       'PORT': '5258'
   }
}
3.4.2使用案例一

在Django框架中弃用admin后台需要借助Django框架可以支持多个数据库连接的特性,配置自定义数据库路由器来实现(详细使用说明请参考Django官方使用文档:https://docs.djangoproject.com/en/4.2/topics/db/multi-db/#multiple-databases),具体配置方法如下所示:

  • 创建app
# 在当前django项目的python环境下执行创建app的命令
python manage.py startapp appName
  • settings.py配置内容
# 注册app
INSTALLED_APPS = [
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'appName',
]
# 配置数据库连接配置
DATABASES = {
   # 默认数据库连接为空
'default': {
},
   # 添加连接GBase 8a的数据库配置
   'other': {
       'ENGINE': 'gbase.connector.django',
       'NAME': 'test',
       'USER': 'gbase',
       'PASSWORD': 'gbase20110531',
       'HOST': '127.0.0.1',
       'charset': 'utf8',
       'PORT': '5258'
   }
}
# 配置app模块与数据库的映射
# admin、auth、contenttypes、sessions模块为Django自带admin后台
# admin_db是一个不存在的数据库配置,目的是为了放弃生成admin后台所需要的表
# appName是用户创建的模块,指定为连接GBase 8a的数据库配置
# other是指定当前模块使用的数据库配置
DATABASE_APPS_MAPPING = {
   "admin": "admin_db",
   "auth": "admin_db",
   "contenttypes": "admin_db",
   "sessions": "admin_db",
   "appName": "other",
}
# 数据库路由配置
# GBaseDjangoDemo: 项目名称
# database_router: 路由配置py文件
# GBaseRouter: 数据库路由配置类
DATABASE_ROUTERS = ['GBaseDjangoDemo.database_router.GBaseRouter']
  • database_router.py,该文件创建在与 settings.py 文件同目录下
# 自定义数据库路由配置类
class GBaseRouter:
   """
   数据库路由,指定 model 类型操作的数据库
"""
# admin后台模块列表
admin_route_app_labels = {"admin", "auth", "contenttypes", "sessions"}
# 使用GBase 8a作为存储库的app名称列表
   other_route_app_labels = {"appName"}
   def db_for_read(self, model, **hints):
       """
       指定 model 类型对象读操作应该使用的数据库
       """
       if model._meta.app_label in self.admin_route_app_labels:
           return "admin_db"
       if model._meta.app_label in self.other_route_app_labels:
           return "other_db"
       return None
   def db_for_write(self, model, **hints):
       """
       指定 model 类型对象写操作应该使用的数据库
       """
       if model._meta.app_label in self.admin_route_app_labels:
           return "admin_db"
       if model._meta.app_label in self.other_route_app_labels:
           return "other_db"
       return None
   def allow_relation(self, obj1, obj2, **hints):
       """
       如果 obj1 和 obj2 间允许关联则返回 true,否则返回 false,无法判断返回 None
       """
       if (
           obj1._meta.app_label in self.other_route_app_labels
           or obj2._meta.app_label in self.other_route_app_labels
       ):
           return True
       return None
   def allow_migrate(self, db, app_label, model_name=None, **hints):
       """
       定义迁移操作是否允许在别名为 db 的数据库上运行,可以就返回 true,不可以则返回 false,无法判断返回None
       此处限制 django 默认生成的表只能在 admin_db 中,如果执行数据库迁移命令时没有指定 admin_db,即使配置默认的数据库也不会生成当前表
       """
       if app_label in self.admin_route_app_labels:
           return False
       return None
  • models.py,用户自定义表结构
from django.db import models
# Create your models here.
class Test(models.Model):
test_id = models.AutoField(primary_key=True)
test_small_int = models.SmallIntegerField(null=True)
test_int = models.IntegerField(default=0, null=False)
test_big_int = models.BigIntegerField(default=0)
test_decimal = models.DecimalField(max_digits=5, decimal_places=2)
test_float = models.FloatField(null=True)
   # 对应GBase中的longblob类型
   test_binary = models.BinaryField(max_length=1024)
test_bool = models.BooleanField(default=False)
# 对应GBase中的varchar类型
test_str = models.CharField(max_length=255, default='', db_index=True)
# 对应GBase中的longtext类型
   test_text = models.TextField(max_length=1000, null=True)
   test_date = models.DateField(auto_now=True)
   
   test_time = models.TimeField(auto_now=True)
   test_date_time = models.DateTimeField(auto_now=True)
   class Meta:
       app_label = "appName"
       db_table = “test”
  • 生成数据库表
# 生成迁移文件
python manage.py makemigrations
# 指定生成表的数据库
python manage.py migrate --database=other
3.4.3 使用案例二

在Django框架中使用GBase 8a的同时需要保留admin后台需要借助Django框架可以支持多个数据库连接的特性,通过配置自定义数据库路由器来实现(详细使用说明请参考Django官方使用文档:https://docs.djangoproject.com/en/4.2/topics/db/multi-db/#multiple-databases),将admin后台的存储数据放在MySQL、PostgreSQL等事务型数据库中,具体配置方法如下所示:

  • 创建app
# 在当前django项目的python环境下执行创建app的命令
python manage.py startapp appName
  • settings.py配置内容
# 注册app
INSTALLED_APPS = [
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'appName',
]
# 配置数据库连接配置
DATABASES = {
   # 默认数据库连接为空
'default': {
},
# 添加连接mysql的数据库配置
'admin_db': {
   'ENGINE': 'django.db.backends.mysql',
   'NAME': 'admin_info',
   'USER': 'root',
   'PASSWORD': 'pass',
    'HOST': '127.0.0.1',
    'PORT': '3306'
},
   # 添加连接GBase 8a的数据库配置
   'other_db': {
       'ENGINE': 'gbase.connector.django',
       'NAME': 'other_info',
       'USER': 'gbase',
       'PASSWORD': 'gbase20110531',
       'HOST': '127.0.0.1',
       'charset': 'utf8',
       'PORT': '5258'
   }
}
# 配置app模块与数据库的映射
# admin、auth、contenttypes、sessions模块为Django自带admin后台
# admin_db用来存储admin后台所需要的表
# appName是用户创建的模块,指定为连接GBase 8a的数据库配置
# other_db是指定当前模块使用的数据库配置
DATABASE_APPS_MAPPING = {
   "admin": "admin_db",
   "auth": "admin_db",
   "contenttypes": "admin_db",
   "sessions": "admin_db",
   "appName": "other_db",
}
# 数据库路由配置
# GBaseDjangoDemo: 项目名称
# database_router: 路由配置py文件
# GBaseRouter: 数据库路由配置类
DATABASE_ROUTERS = ['GBaseDjangoDemo.database_router.GBaseRouter']
  • database_router.py,该文件创建在与 settings.py 文件同目录下
# 自定义数据库路由配置类
# 该文件创建在与 settings.py 文件同目录下
class GBaseRouter:
   """
   数据库路由,指定 model 类型操作的数据库
"""
# admin后台模块列表
admin_route_app_labels = {"admin", "auth", "contenttypes", "sessions"}
# 使用GBase 8a作为存储库的app名称列表
   other_route_app_labels = {"appName"}
   def db_for_read(self, model, **hints):
       """
       指定 model 类型对象读操作应该使用的数据库
       """
       if model._meta.app_label in self.admin_route_app_labels:
           return "admin_db"
       if model._meta.app_label in self.other_route_app_labels:
           return "other_db"
       return None
   def db_for_write(self, model, **hints):
       """
       指定 model 类型对象写操作应该使用的数据库
       """
       if model._meta.app_label in self.admin_route_app_labels:
           return "admin_db"
       if model._meta.app_label in self.other_route_app_labels:
           return "other_db"
       return None
   def allow_relation(self, obj1, obj2, **hints):
       """
       如果 obj1 和 obj2 间允许关联则返回 true,否则返回 false,无法判断返回 None
       """
       # db_set = self.admin_route_app_labels.union(self.other_route_app_labels)
       if (
           obj1._meta.app_label in self.admin_route_app_labels
           or obj2._meta.app_label in self.admin_route_app_labels
       ):
           return True
       if (
           obj1._meta.app_label in self.other_route_app_labels
           or obj2._meta.app_label in self.other_route_app_labels
       ):
           return True
       return None
   def allow_migrate(self, db, app_label, model_name=None, **hints):
       """
       定义迁移操作是否允许在别名为 db 的数据库上运行,可以就返回 true,不可以则返回 false,无法判断返回None
       此处限制 django 默认生成的表只能在 admin_db 中,如果执行数据库迁移命令时没有指定 admin_db,即使配置默认的数据库也不会生成当前表
       """
       if app_label in self.admin_route_app_labels:
           return db == "admin_db"
       return None
  • models.py,用户自定义表结构
from django.db import models
class Test(models.Model):
   test_id = models.IntegerField()
   test_name = models.CharField(max_length=50)
   text = models.TextField(max_length=1000, null=True)
create_time = models.DateTimeField(auto_now_add=True)
   class Meta:
       app_label = "appName"
       db_table = “test”
  • admin.py,配置admin后台显示的表字段信息
from django.contrib import admin
from appName.models import Test

# Register your models here.
class TestAdmin(admin.ModelAdmin):
   # 设置admin后台显示该表的字段信息
   list_display = ["test_id", "test_name", "text", "create_time"]
admin.site.register(Test, TestAdmin)
  • 生成数据库表
# 生成迁移文件
python manage.py makemigrations
# 指定生成表的数据库
python manage.py migrate --database=admin_db
python manage.py migrate --database=other_db
# 创建管理员用户
python manage.py createsuperuser --database=admin_db

附:

SQLAlchemy官方文档地址

SQLAlchemy Documentation — SQLAlchemy 1.4 Documentation

Superset官方文档地址

Quickstart | Superset

Flask官方文档地址

Installation — Flask Documentation (2.3.x)

Django官方文档地址

Django documentation | Django documentation | Django

关于python接口就先给大家介绍这么多,欢迎大家到南大通用官网下载试用:GBase 8a MPP Cluster V9|下载中心|天津南大通用数据技术股份有限公司|GBASE-致力于成为用户最信赖的数据库产品供应商,谢谢~

原文链接:https://www.gbase.cn/community/post/4311
更多精彩内容尽在南大通用GBase技术社区,南大通用致力于成为用户最信赖的数据库产品供应商

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值