从Python中的SQLAlchemy了解MetaData() [英] Understanding MetaData() from SQLAlchemy in Python

查看:337
本文介绍了从Python中的SQLAlchemy了解MetaData()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解什么是MetaData()创建的对象.当在Python中反射和创建数据库时使用它(使用SQLAlchemy包).

I am trying to understand what the MetaData() created object is in essence. It is used when reflecting and creating databases in Python (using SQLAlchemy package).

考虑以下工作代码:

/带有预加载的Engine(sqlite:///chapter5.sqlite)和元数据= MetaData():当我在控制台中调用元数据时,它返回'MetaData(bind = None)'/

/ with preloaded Engine(sqlite:///chapter5.sqlite) and metadata = MetaData(): when I call metadata in the console, it returns 'MetaData(bind=None)' /

# Import Table, Column, String, and Integer
from sqlalchemy import Table, Column, String, Integer

# Build a census table: census
census = Table('census', metadata,
               Column('state', String(30)),
               Column('sex', String(1)),
               Column('age', Integer()),
               Column('pop2000', Integer()),
               Column('pop2008',Integer()))

# Create the table in the database
metadata.create_all(engine)

当然,通过键入type(metadata),我可以确切地知道对象元数据的类型是:sqlalchemy.sql.schema.MetaData.在 SQLAlchemy文档

Of course by typing type(metadata) I get exactly what type of object metadata is: sqlalchemy.sql.schema.MetaData. In SQLAlchemy documentation it is written

MetaData是一个容器对象,它将描述的一个数据库(或多个数据库)的许多不同功能组合在一起.

MetaData is a container object that keeps together many different features of a database (or multiple databases) being described.

但是,我很困惑,因为在代码中我们仅创建一个指向"元数据的表.之后,当我们在元数据上调用create_all方法(到目前为止为空)时,指向数据库(由引擎指向).

However, I am confused, because in the code we only create a table that "points" to metadata. After that, when we call the create_all method on metadata (empty by far), pointing to the database (which is pointed by engine).

我的问题可能很愚蠢,但是:

Probably my question is silly, but:

python如何精确连接这些实例?普查表的声明可能以双向方式将元数据链接到列名称.

How does python exactly connect these instances? Probably the declaration of the census table links metadata to the column names in a two-sided way.

注意:该代码来自 datacamp 课程的一个练习.

Note: The code is from an exercise from datacamp course.

推荐答案

我想您问python(您大概是说SQLAlchemy)如何将表连接到元数据,将元数据连接到数据库和引擎.

I think you asked how does python (SQLAlchemy you presumably mean) connect the table to the metadata and the metadata to the database and engine.

因此,SQLAlchemy中的数据库表属于(链接到)元数据对象.该表将自身添加到元数据中.在元数据对象上有一个表属性,其行为很像一个列表:

So database tables in SQLAlchemy belong (are linked to) a metadata object. The table adds itself to the metadata; there is a tables property on the metadata object that acts a lot like a list:

rue,nullable = False),Column('host_id',Integer(),ForeignKey('slots.id'),table =,nullable = False),Column('active',Boolean(),table =) ,上校 umn('port',Integer(),table =,nullable = False),Column('description',String(length = 120),table =),Column('username',String(length = 40),制表符 le =),列('password',字符串(length = 40),table =),schema = None),'network_location_associations':表('network_location_associations',M etaData(bind = None),Column('network_id',Integer(),ForeignKey('networks.id'),table =),Column('location_id',Integer(),ForeignKey('locations. id'),table =),schema = None),'machines':Table('machines',MetaData(bind = None),Column('id',Integer(),ForeignKey('items.id'),表=

rue, nullable=False), Column('host_id', Integer(), ForeignKey('slots.id'), table=, nullable=False), Column('active', Boolean(), table=), Col umn('port', Integer(), table=, nullable=False), Column('description', String(length=120), table=), Column('username', String(length=40), tab le=), Column('password', String(length=40), table=), schema=None), 'network_location_associations': Table('network_location_associations', M etaData(bind=None), Column('network_id', Integer(), ForeignKey('networks.id'), table=), Column('location_id', Integer(), ForeignKey('locations. id'), table=), schema=None), 'machines': Table('machines', MetaData(bind=None), Column('id', Integer(), ForeignKey('items.id'), table=

,primary_key = True,nullable = False),Column('eth0',String(),table =),Column('eth1',String(),table =),Column('eth2',String() ,table =),Colu mn('eth3',String(),table =),Column('wlan0',String(),table =),Column('ipmi',String(),table =),schema = None),'machine_profiles' :桌子(马赫 ine_profiles',MetaData(bind = None),Column('id',Integer(),table =,primary_key = True,nullable = False),Column('DisplayPort',Integer(),table =),Column('HDMI ',Integer(),table =),Column('RAM',String(length = 10),table =),schema = None),'geometry':Table('geometry',MetaData(b) ind = None),Column('slot_id',Integer(),ForeignKey('slots.id'),table =,primary_key = True,nullable = False),Column('room_id',Integer(),ForeignKey('rooms .id'),表格 e =,nullable = False),Column('x_mm',Float(),table =,nullable = False),Column('y_mm',Float(),table =,nullable = False),Column('z_mm', Float(),t 能力=,可空= False),列('rotation_deg',Float(),表=,可空= False),列('tilt_deg',Float(),表=,可空= False),列('ro ll_deg',Float(),table =,nullable = False),Column('on_floor',Boolean(),table =,nullable = False),schema = None),'publicaddresses':Table('publicaddresses' ,MetaData(bind = None),Column('id',Integer(),table =,primary_key = True,nullable = False),Column('ip',Integer(),table =,nullable = False),C olumn('slot_id',Integer(),ForeignKey('slots.id'),table =,nullable = False),schema = None),'connections':Table('connections',MetaData(bind = None),Column ('一世 d',Integer(),table =,primary_key = True,nullable = False),Column('src_slot_id',Integer(),ForeignKey('slots.id'),table =),Column('src_index',Inte ger(),table =),Column('src_type',Enum('HDMI','DisplayPort','miniDP','VGA','DVI','Power','CAT6','WallNet','Hybrid ','UnknownVideo'),table = ),Column('dst_slot_id',Integer(),ForeignKey('slots.id'),table =),Column('dst_index',Integer(),table =),Column('dst_type',Enum('HDMI' ,'Displa yPort','miniDP','VGA','DVI','Power','CAT6','WallNet','Hybrid','UnknownVideo'),table =),schema = None),'types':表(类型",MetaData(bind = None),列 ('type',Integer(),table =,primary_key = True,nullable = False),Column('name',String(length = 60),table =),schema = None),'角色':Table('角色',MetaData(bind = No ne),Column('id',Integer(),table =,primary_key = True,nullable = False),Column('name',String(),table =,nullable = False),Column('description',String (),表格= ,nullable = False),Column('display_driver',Boolean(),table =,nullable = False),schema = None),'rooms':Table('rooms',MetaData(bind = None),Column('id ', 整数( ),table =,primary_key = True,nullable = False),Column('location_id',Integer(),ForeignKey('locations.id'),table =,nullable = False),Column('parent_id',Integer( ),table =),Column('name',String(length = 50),table =),Column('x_mm',Float(),table =,nullable = False),Column('y_mm',Float() ,table =,nullable = F alse),Column('z_mm',Float(),table =,nullable = False),Column('rotation_deg',Float(),table =,nullable = False),Column('width_mm',Float(),table =,null able = False),Column('height_mm',Float(),table =,nullable = False),Column('depth_mm',Float(),table =,nullable = False),Column('has_workstations',Boolean() ,TA ble =,nullable = False),schema = None),'displays':Table('displays',MetaData(bind = None),Column('id',Integer(),table =,primary_key = True,nullable = False ),公司 lumn('hostname',String(length = 100),table =),Column('formation',Enum('2x3','1x2','corkboard','desktop','desktop-shared'),table = ,nullable = False),s chema = None),'slots':Table('slots',MetaData(bind = None),Column('id',Integer(),table =,primary_key = True,nullable = False),Column('location_id', Integer(),ForeignKe y('locations.id'),table =,nullable = False),Column('hostname',String(),table =),Column('item_id',Integer(),ForeignKey('items.id'), table =),列('r ole_id',Integer(),ForeignKey('roles.id'),table =),Column('parent_id',Integer(),ForeignKey('slots.id'),table =),Column('ip',Integer (),table =),列 umn('ip_ipmi',Integer(),table =),Column('ip_wlan',Integer(),table =),Column('optional',Boolean(),table =),Column('notes',String( ),table =), Column('classification',Enum('U','S','TS'),table =),Column('os',String(),table =),Column('release',String(),table =),Column('track',String(),t 能够=),列('uuid',二进制(),表=),列('displaydata',字符串(),表=),模式=无)})

, primary_key=True, nullable=False), Column('eth0', String(), table=), Column('eth1', String(), table=), Column('eth2', String(), table=), Colu mn('eth3', String(), table=), Column('wlan0', String(), table=), Column('ipmi', String(), table=), schema=None), 'machine_profiles': Table('mach ine_profiles', MetaData(bind=None), Column('id', Integer(), table=, primary_key=True, nullable=False), Column('DisplayPort', Integer(), table=), Column('HDMI', Integer(), table=), Column('RAM', String(length=10), table=), schema=None), 'geometry': Table('geometry', MetaData(b ind=None), Column('slot_id', Integer(), ForeignKey('slots.id'), table=, primary_key=True, nullable=False), Column('room_id', Integer(), ForeignKey('rooms.id'), tabl e=, nullable=False), Column('x_mm', Float(), table=, nullable=False), Column('y_mm', Float(), table=, nullable=False), Column('z_mm', Float(), t able=, nullable=False), Column('rotation_deg', Float(), table=, nullable=False), Column('tilt_deg', Float(), table=, nullable=False), Column('ro ll_deg', Float(), table=, nullable=False), Column('on_floor', Boolean(), table=, nullable=False), schema=None), 'publicaddresses': Table('publicaddresses' , MetaData(bind=None), Column('id', Integer(), table=, primary_key=True, nullable=False), Column('ip', Integer(), table=, nullable=False), C olumn('slot_id', Integer(), ForeignKey('slots.id'), table=, nullable=False), schema=None), 'connections': Table('connections', MetaData(bind=None), Column('i d', Integer(), table=, primary_key=True, nullable=False), Column('src_slot_id', Integer(), ForeignKey('slots.id'), table=), Column('src_index', Inte ger(), table=), Column('src_type', Enum('HDMI', 'DisplayPort', 'miniDP', 'VGA', 'DVI', 'Power', 'CAT6', 'WallNet', 'Hybrid', 'UnknownVideo'), table= ), Column('dst_slot_id', Integer(), ForeignKey('slots.id'), table=), Column('dst_index', Integer(), table=), Column('dst_type', Enum('HDMI', 'Displa yPort', 'miniDP', 'VGA', 'DVI', 'Power', 'CAT6', 'WallNet', 'Hybrid', 'UnknownVideo'), table=), schema=None), 'types': Table('types', MetaData(bind=None), Column ('type', Integer(), table=, primary_key=True, nullable=False), Column('name', String(length=60), table=), schema=None), 'roles': Table('roles', MetaData(bind=No ne), Column('id', Integer(), table=, primary_key=True, nullable=False), Column('name', String(), table=, nullable=False), Column('description', String(), table= , nullable=False), Column('display_driver', Boolean(), table=, nullable=False), schema=None), 'rooms': Table('rooms', MetaData(bind=None), Column('id', Integer( ), table=, primary_key=True, nullable=False), Column('location_id', Integer(), ForeignKey('locations.id'), table=, nullable=False), Column('parent_id', Integer( ), table=), Column('name', String(length=50), table=), Column('x_mm', Float(), table=, nullable=False), Column('y_mm', Float(), table=, nullable=F alse), Column('z_mm', Float(), table=, nullable=False), Column('rotation_deg', Float(), table=, nullable=False), Column('width_mm', Float(), table=, null able=False), Column('height_mm', Float(), table=, nullable=False), Column('depth_mm', Float(), table=, nullable=False), Column('has_workstations', Boolean(), ta ble=, nullable=False), schema=None), 'displays': Table('displays', MetaData(bind=None), Column('id', Integer(), table=, primary_key=True, nullable=False), Co lumn('hostname', String(length=100), table=), Column('formation', Enum('2x3', '1x2', 'corkboard', 'desktop', 'desktop-shared'), table=, nullable=False), s chema=None), 'slots': Table('slots', MetaData(bind=None), Column('id', Integer(), table=, primary_key=True, nullable=False), Column('location_id', Integer(), ForeignKe y('locations.id'), table=, nullable=False), Column('hostname', String(), table=), Column('item_id', Integer(), ForeignKey('items.id'), table=), Column('r ole_id', Integer(), ForeignKey('roles.id'), table=), Column('parent_id', Integer(), ForeignKey('slots.id'), table=), Column('ip', Integer(), table=), Col umn('ip_ipmi', Integer(), table=), Column('ip_wlan', Integer(), table=), Column('optional', Boolean(), table=), Column('notes', String(), table=), Column('classification', Enum('U', 'S', 'TS'), table=), Column('os', String(), table=), Column('release', String(), table=), Column('track', String(), t able=), Column('uuid', Binary(), table=), Column('displaydata', String(), table=), schema=None)})

len()models.Base.metadata.tables 文件",第1行 len()models.Base.metadata.tables ^ SyntaxError:语法无效 len(models.Base.metadata.tables) 22

len()models.Base.metadata.tables File "", line 1 len()models.Base.metadata.tables ^ SyntaxError: invalid syntax len(models.Base.metadata.tables) 22

您需要元数据对象的原因是:

The reason you need the metadata object is:

  • 只有一个工作单元来创建和删除相关表

  • To have a single unit of work for creating and dropping related tables

有一个地方可以收集反射操作的所有结果

To have a place to collect all the results of a reflection operation

根据相关性对相关表进行排序,以便可以按正确的顺序创建外键约束.

To sort related tables based on their dependencies so that foreign key constraints can be created in the right order.

因此,元数据对象包含SQLAlchemy'sidea,它认为数据库可能看起来像.通常是通过反射或创建表对象(可能是通过声明性基本扩展)填充的.

So, the metadata object contains SQLAlchemy'sidea of what it thinks a database might look like. It's typically populated either from reflection or from you creating table objects (possibly through the declarative base extension).

您可以通过在元数据构造函数中设置bind参数直接将元数据对象与真实的数据库引擎关联.或者,可以在创建调用或反射调用中使用元数据时建立链接.

You can directly associate a metadata object with a real database engine by setting the bind parameter in the metadata constructor. Alternitevly, you can make the link when you use the metadata either in create calls or in reflection calls.

这篇关于从Python中的SQLAlchemy了解MetaData()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆