我正在尝试向 Superset(一个数据探索平台)添加一个特殊的数据源。本数据库仅支持HTTP API,返回json格式数据;例如:
> http://localhost/api/sql/query?q="select * from table"
< [{"id": 1, "value":10}, {"id": 2, "value": 30} ...]
因此,我必须在 python SQLAlchemy 中为 Superset 编写自己的适配器。我已经阅读了文档和部分源代码,但仍然需要很好的例子来遵循。
最佳答案
(解决方案由 OP 编辑到问题中)
我已经解决了这个问题。这就是我所做的。
./site-packages/sqlalchemy/dialects
from sqlalchemy.engine.default import DefaultDialect
class ZetaDialect(DefaultDialect):
...
__all__
./site-packages/sqlalchemy/dialects/__init__.py
的部分 from sqlalchemy import create_engine
engine = create_engine('zeta://XXX')
result = engine.execute("select * from table_name")
for row in result:
print(row)
class ZetaDialect(DefaultDialect):
# default_paramstyle = 'qmark'
name = 'zeta'
def __init__(self, **kwargs):
DefaultDialect.__init__(self, **kwargs)
@classmethod
def dbapi(cls):
return zeta_dbapi
@reflection.cache
def get_table_names(self, connection, schema=None, **kw):
return [u'table_1', u'table_2', ...]
@reflection.cache
def get_pk_constraint(self, connection, table_name, schema=None, **kw):
return []
@reflection.cache
def get_foreign_keys(self, connection, table_name, schema=None, **kw):
return []
@reflection.cache
def get_unique_constraints(self, connection, table_name,
schema=None, **kw):
return []
@reflection.cache
def get_indexes(self, connection, table_name, schema=None, **kw):
return []
@reflection.cache
def get_schema_names(self, connection, **kw):
return []
@reflection.cache
def get_columns(self, connection, table_name, schema=None, **kw):
# just an example of the column structure
result = connection.execute('select * from %s limit 1' % table_name)
return [{'default': None, 'autoincrement': False, 'type': TEXT, 'name': colname, 'nullable': False} for colname, coltype in result.cursor.description]
关于python - 如何在 sqlalchemy 中编写自己的方言以适应 HTTP API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43929132/