sqlalchemy 的 xml 配置

发布于 2025-01-03 19:52:00 字数 253 浏览 1 评论 0原文

有没有办法从模型类中取出 python sqlalchemy 映射?到目前为止,我一直在使用声明性映射,其中类将扩展声明性基础。但现在我想在生成的 python 模块中映射一些模型。所以我无法修改模型类。

  1. 我应该使用经典映射器,即 mapper() 函数吗?
  2. 经典映射是否提供了与声明性映射相同的所有选项?
  3. 是否有像 hibernate hbm.xml 文件那样的 xml 配置方式?

问候, 利蒂

Is there a way to take out the python sqlalchemy mappings from the model classes? Till now I was using Declarative mapping where the class will extend Declarative base. But now I want to map some models in a generated python module. So I can't modify the model classes.

  1. Should I be using the classical mapper that is the mapper() function?
  2. Does the classical mapping gives all the options as the declarative mapping?
  3. Is there a xml configuration way like the hibernate hbm.xml files?

Regards,
Litty

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱已欠费 2025-01-10 19:52:00

下面是如何为基于 xml 的 orm 类手工制作自己的解决方案的示例。它从本教程读取 User.hbm.xml 文件。这是一个 hack - 我对 Hibernate 一无所知。希望这适合您或其他人对您的问题的理解。

#!/usr/bin/env python3                                                                                                 
# -*- coding: utf-8 -*-                                                                                                

import sqlalchemy as sqAl
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import xml.etree.ElementTree as ET

def generate_class(class_el):                                                                                          

    type_map = {'java.lang.String': sqAl.String,                                                                       
                'java.util.Date': sqAl.Date,                                                                           
                'java.lang.Double': sqAl.Float,                                                                        
                'java.lang.Long': sqAl.Integer}                                                                        

    dynclass_dict = {                                                                                                  
        'id': sqAl.Column(sqAl.Integer, primary_key=True),                                                             
        '__tablename__': class_el.attrib['table']                                                                      
        }                                                                                                              
    for field_el in class_el.findall('property'):                                                                      
        field = field_el.attrib                                                                                        
        if field['type'] in type_map:                                                                                  
            dynclass_dict[field['name']] = sqAl.Column(field['column'], type_map[field['type']])                       

    return type(class_el.attrib['table'].capitalize(), (declarative_base(sqAl.MetaData()),), dynclass_dict)            

classe = ET.parse('User.hbm.xml').getroot().find('class')
User = generate_class(classe)


if __name__ == '__main__':
    # the two following lines create the table (if not already existing)                                                                                             
    engine = sqAl.create_engine('sqlite:///data.db', echo=True)                                                        
    User.__base__.metadata.create_all(engine, checkfirst=True)                                                         

    session = sessionmaker(bind=engine)()                                                                              
    u = User(userFirstName="John F.", userLastName="Kennicknich", userName="jfk")                                      
    session.add(u)                                                                                                     
    session.commit()          

Here a sample how to hand-craft your own solution for an xml-based orm class. It reads the User.hbm.xml-file from this tutorial. This is a hack - I don't know anything about Hibernate. Hope this fits your or maybe somebody elses understanding of your question.

#!/usr/bin/env python3                                                                                                 
# -*- coding: utf-8 -*-                                                                                                

import sqlalchemy as sqAl
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import xml.etree.ElementTree as ET

def generate_class(class_el):                                                                                          

    type_map = {'java.lang.String': sqAl.String,                                                                       
                'java.util.Date': sqAl.Date,                                                                           
                'java.lang.Double': sqAl.Float,                                                                        
                'java.lang.Long': sqAl.Integer}                                                                        

    dynclass_dict = {                                                                                                  
        'id': sqAl.Column(sqAl.Integer, primary_key=True),                                                             
        '__tablename__': class_el.attrib['table']                                                                      
        }                                                                                                              
    for field_el in class_el.findall('property'):                                                                      
        field = field_el.attrib                                                                                        
        if field['type'] in type_map:                                                                                  
            dynclass_dict[field['name']] = sqAl.Column(field['column'], type_map[field['type']])                       

    return type(class_el.attrib['table'].capitalize(), (declarative_base(sqAl.MetaData()),), dynclass_dict)            

classe = ET.parse('User.hbm.xml').getroot().find('class')
User = generate_class(classe)


if __name__ == '__main__':
    # the two following lines create the table (if not already existing)                                                                                             
    engine = sqAl.create_engine('sqlite:///data.db', echo=True)                                                        
    User.__base__.metadata.create_all(engine, checkfirst=True)                                                         

    session = sessionmaker(bind=engine)()                                                                              
    u = User(userFirstName="John F.", userLastName="Kennicknich", userName="jfk")                                      
    session.add(u)                                                                                                     
    session.commit()          
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文