代码之家  ›  专栏  ›  技术社区  ›  Diego-MX

sqlalchemy,我可以创建表类吗?

  •  0
  • Diego-MX  · 技术社区  · 7 年前

    我最近发现 sqlalchemy 在蟒蛇中。我想把它用于数据科学而不是网站应用。
    我一直在读关于它的文章,我喜欢你可以将sql查询转换成python。
    我最困惑的是:

    因为我是从一个已经很好建立的模式中读取数据,所以我希望不必自己创建相应的模型。
    我可以通过读取表的元数据,然后查询表和列来解决这个问题。 问题是,当我想连接到其他表时,每次读取元数据的时间都太长,所以我想知道是否有必要将其pickle缓存到一个对象中,或者是否有其他内置的方法。

    编辑: 包括代码。 注意到等待时间是由于加载函数中的错误造成的,而不是如何使用引擎。仍然保留代码以防人们评论有用的东西。干杯。

    我使用的代码如下:

    def reflect_engine(engine, update):
      store = f'cache/meta_{engine.logging_name}.pkl'
    
      if update or not os.path.isfile(store):
        meta = alq.MetaData()
        meta.reflect(bind=engine)
        with open(store, "wb") as opened:
          pkl.dump(meta, opened)
      else: 
        with open(store, "r") as opened:
          meta = pkl.load(opened)
      return meta
    
    
    def begin_session(engine):
      session = alq.orm.sessionmaker(bind=engine)
      return session()
    

    然后我使用元数据对象来获取我的查询…

    def get_some_cars(engine, metadata): 
      session = begin_session(engine)  
    
      Cars   = metadata.tables['Cars']
      Makes  = metadata.tables['CarManufacturers']
    
      cars_cols = [ getattr(Cars.c, each_one) for each_one in [
          'car_id',                   
          'car_selling_status',       
          'car_purchased_date', 
          'car_purchase_price_car']] + [
          Makes.c.car_manufacturer_name]
    
      statuses = {
          'selling'  : ['AVAILABLE','RESERVED'], 
          'physical' : ['ATOURLOCATION'] }
    
      inventory_conditions = alq.and_( 
          Cars.c.purchase_channel == "Inspection", 
          Cars.c.car_selling_status.in_( statuses['selling' ]),
          Cars.c.car_physical_status.in_(statuses['physical']),)
    
      the_query = ( session.query(*cars_cols).
          join(Makes, Cars.c.car_manufacturer_id == Makes.c.car_manufacturer_id).
          filter(inventory_conditions).
          statement )
    
      the_inventory = pd.read_sql(the_query, engine)
      return the_inventory
    
    0 回复  |  直到 7 年前
    推荐文章