使用xml;“地图”;要通过python将数据导入MySQL?

使用xml;“地图”;要通过python将数据导入MySQL?,python,mysql,xml,mapping,Python,Mysql,Xml,Mapping,我有许多不同的CSV文件需要每小时处理到MySQL数据库的不同表中。我正在用Python编写一个摄取引擎,它接受一个xml映射文件,如下所示: <table name = "example_table"> <column name = 'test'> <source type = 'sql'>schema.table_name.column_name</source> </column> <

我有许多不同的CSV文件需要每小时处理到MySQL数据库的不同表中。我正在用Python编写一个摄取引擎,它接受一个xml映射文件,如下所示:

<table name = "example_table">
    <column name = 'test'>
        <source type = 'sql'>schema.table_name.column_name</source>
    </column>
    <column name = 'test_2'>
        <source type = 'csv'>column_name</source>
    </column>
</table>

schema.table\u name.column\u name
列名
并使用它来确定将数据插入MySQL数据库的位置。在本例中:

  • 在表“example_table”中查找列“test”,并填写另一个sql表“schema.table_name.column_name”中的数据(这通常是另一个表的主键)

  • 查找“test_2”列,并从由“column_name”键入的csv文件中填写数据

我是不是离基地太远了?这似乎是一种合理的方式吗?目标是拥有一个python引擎和多个xml映射文件,这样我就可以有效地处理每组插入


有更好的方法吗?

这个方案本身没有什么问题。对于这样简单的映射,XML有点冗长,也有点过火,但它是高度标准化的,易于编辑,并且可以很好地工作。您应该能够轻松地循环使用此结构:

from lxml import objectify
table = objectify.fromstring(xml_source)
print "table name:", table.attrib['name']
for col in table.column:
    print "column name:", col.attrib['name']
    print "source type:", col.source.attrib['type']
    print "source col:",  col.source.text
与XML相比,许多开发人员现在更喜欢JSON或YAML配置文件。例如,如果您想要类似的JSON:

{
   "table":"example_table",
   "columns":[
      {
         "name":"test",
         "source_type":"sql",
         "source_col":"schema.table_name.column_name"
      },
      {
         "name":"test_2",
         "source_type":"csv",
         "source_col":"column_name"
      }
   ]
}
您还可以轻松地对其进行迭代:

j = json.loads(json_source)
print "table name:", j['table']
for col in j['columns']:
    print "column name:", col['name']
    print "source type:", col['source_type']
    print "source col:",  col['source_col']

无论选择何种特定格式,使用数据驱动配方都是一种灵活的方式来为您的摄入引擎提供信息。

如果有人试图在文件上使用此代码,它甚至不能与
objectify.parse(xml\u文件名)
一起使用。我必须打开文件并将其内容对象化:
f=open(xml\u文件名,“r”)table=objectify.fromstring(f.read())
然后它就像一个符咒一样工作!谢谢Jonathan!您不需要严格地先读取文件内容;
objectify.parse()
接受一个打开的文件对象。但是在显式打开文件后,读取其内容并传递到
objectify.fromstring()
似乎很自然。Python API通常可以原谅和/或包含多种输入类型(“duck typing”写得很大)。lxml…没有那么多!