Fck*_*nda 8 python sqlite amazon-s3 in-memory-database python-3.x
我在 s3 存储桶中有一个小的 sqlite 数据库(110kb)。每次运行python应用程序时,我都想连接到该数据库。
一个选项是每次运行python应用程序时下载数据库并像往常一样连接它。但我想知道是否存在一种通过内存连接到该 sqlite 数据库的方法,使用S3FileSystem和open。我正在使用sqlite3库和 python 3.6
小智 14
正如其他答案所表明的那样,您可能不想将 SQLite 用作云中的主要数据库。
但是,作为一个有趣的副项目的一部分,我编写了一个 Amazon Athena 数据源连接器,它允许您从 Athena查询S3 中的 SQLite 数据库。为了做到这一点,我为 S3 编写了一个只读的 SQLite 接口。
SQLite 有一个OS Interface 或 VFS的概念。使用名为APSW的 Python SQLite 包装器,您可以为任意文件系统编写 VFS 实现。这就是我在我的项目中所做的,我在下面包含了实现。
为了使用它,您将首先注册 VFS,然后使用此实现作为驱动程序创建一个新的 SQLite 连接。
我应该注意到这根本没有优化,因此可能仍然需要根据您的查询从 S3 读取完整的数据库。但在这种特定情况下听起来不像是一个问题。
S3FS = S3VFS() # S3VFS defined below
# This odd format is used due to SQLite requirements
sqlite_uri = "file:/{}/{}.sqlite?bucket={}&immutable=1".format(
S3_PREFIX,
DATABASE_NAME,
S3_BUCKET
)
connection = apsw.Connection(sqlite_uri,
flags=apsw.SQLITE_OPEN_READONLY | apsw.SQLITE_OPEN_URI,
vfs=S3FS.vfsname
)
cursor = connection.cursor()
Run Code Online (Sandbox Code Playgroud)
一旦你有了游标,你就可以像这样执行标准的 SQL 语句:
for x,y,z in cursor.execute("select x,y,z from foo"):
print (cursor.getdescription()) # shows column names and declared types
print (x,y,z)
Run Code Online (Sandbox Code Playgroud)
VFS 实现(需要 APSW 库和 boto3 以实现 S3 连接)
import apsw
import sys
import boto3
VFS_S3_CLIENT = boto3.client('s3')
class S3VFS(apsw.VFS):
def __init__(self, vfsname="s3", basevfs=""):
self.vfsname=vfsname
self.basevfs=basevfs
apsw.VFS.__init__(self, self.vfsname, self.basevfs)
def xOpen(self, name, flags):
return S3VFSFile(self.basevfs, name, flags)
class S3VFSFile():
def __init__(self, inheritfromvfsname, filename, flags):
self.bucket = filename.uri_parameter("bucket")
self.key = filename.filename().lstrip("/")
print("Initiated S3 VFS for file: {}".format(self._get_s3_url()))
def xRead(self, amount, offset):
response = VFS_S3_CLIENT.get_object(Bucket=self.bucket, Key=self.key, Range='bytes={}-{}'.format(offset, offset + amount))
response_data = response['Body'].read()
return response_data
def xFileSize(self):
client = boto3.client('s3')
response = client.head_object( Bucket=self.bucket, Key=self.key)
return response['ContentLength']
def xClose(self):
pass
def xFileControl(self, op, ptr):
return False
def _get_s3_url(self):
return "s3://{}/{}".format(self.bucket, self.key)
Run Code Online (Sandbox Code Playgroud)
不,无法直接连接到存储在云中的 sqlite 数据库。即使您想将数据库托管在内存中,也必须在加载到内存之前完全下载它。要做到这一点仍然需要首先从基于磁盘的文件加载数据库或使用 DDL 命令直接在内存中创建它。据我所知,无法将数据流加载为 sqlite 内存数据库(参见示例 1:加载和保存内存数据库)。
在这种情况下,一旦数据库断开连接,就需要重新上传到云存储。 S3FileSystem.open只返回一个数据流。所有流将允许您做的是将文件下载到本地存储,以便可以在本地打开/操作它。
如果您确实需要云数据库,则需要研究另一种托管数据库。
是的,EFS 是可能的:
https://www.lambrospetrou.com/articles/aws-lambda-and-sqlite-over-efs/
AWS 最近发布了 AWS Lambda 和 Amazon EFS 之间的集成。它支持 SQLite 所需的 NFSv4 锁升级/降级。这意味着 SQLite 引擎可以对存储在 EFS 文件系统上的文件进行读/写访问。
| 归档时间: |
|
| 查看次数: |
8719 次 |
| 最近记录: |