欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

flask/django 動(dòng)態(tài)查詢表結(jié)構(gòu)相同表名不同數(shù)據(jù)的Model實(shí)現(xiàn)方法

 更新時(shí)間:2019年08月29日 09:38:23   作者:pushiqiang  
今天小編就為大家分享一篇flask/django 動(dòng)態(tài)查詢表結(jié)構(gòu)相同表名不同數(shù)據(jù)的Model實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

1.問題

為了控制數(shù)據(jù)的增長(zhǎng),經(jīng)常需要分表,數(shù)據(jù)庫(kù)中存在多張結(jié)構(gòu)相同,表名相關(guān)的表,如:

table_201706
table_201707
table_201708

怎么通過SQLAlchemy 或者django查詢相關(guān)的數(shù)據(jù)表,而不用每次都創(chuàng)建Model呢

2.解決方法

分別在flask和django下實(shí)現(xiàn),代碼如下

2.1 flask+sqlalchemy

# -*-coding:utf-8


class NewDynamicModel(object):
 """
 動(dòng)態(tài)產(chǎn)生模型和表的對(duì)應(yīng)關(guān)系模型
 :param base_cls: 基類模型,虛類,如TemplateModel
 :param tb_name: 數(shù)據(jù)庫(kù)中對(duì)應(yīng)的表名, 如tb_test_2017
 :return: Model class
 eg:
 '''
 class TemplateModel(db.Model):
  __abstract__ = True
  id = db.Column(db.Integer(), autoincrement=True, primary_key=True)
  name = db.Column(db.VARCHAR(32), nullable=False)

 Test_2017 = NewDynamicModel(TemplateModel, 'tb_test_2017')
 print Test_2017.query.all()
 '''
 """
 _instance = dict()

 def __new__(cls, base_cls, tb_name):
  new_cls_name = "%s_To_%s" % (
   base_cls.__name__, '_'.join(map(lambda x:x.capitalize(),tb_name.split('_'))))

  if new_cls_name not in cls._instance:
   model_cls = type(new_cls_name, (base_cls,),
        {'__tablename__': tb_name})
   cls._instance[new_cls_name] = model_cls

  return cls._instance[new_cls_name]

Bug:由于新的數(shù)據(jù)模型是通過type動(dòng)態(tài)創(chuàng)建的,實(shí)際module 下的py文件并不存在該類的代碼,因而在通過pickle等方式序列化的時(shí)候,會(huì)報(bào)找不到類的錯(cuò)誤。

Fixbug: 通過inspect庫(kù),拷貝基類的代碼作為副本,并替換tablename 屬性,寫入臨時(shí)類定義文件,并引入module。

新的方式實(shí)現(xiàn)如下:

class NewDynamicModel(object):
 """
 動(dòng)態(tài)產(chǎn)生模型和表的對(duì)應(yīng)關(guān)系模型
 :param base_cls: 基類模型,虛類,如TemplateModel
 :param tb_name: 數(shù)據(jù)庫(kù)中對(duì)應(yīng)的表名, 如tb_test_2017
 :return: Model class
 eg:
 '''
 class TemplateModel(db.Model):
  __abstract__ = True
  id = db.Column(db.Integer(), autoincrement=True, primary_key=True)
  name = db.Column(db.VARCHAR(32), nullable=False)



 Test_2017 = NewDynamicModel(TemplateModel, 'tb_test_2017')
 print Test_2017.query.all()
 '''
 """

 @staticmethod
 def get_import_codes(Model):
  """
  獲取基類的import依賴
  :param Model:
  :return:
  """
  module = inspect.getmodule(Model)
  all_codelines = inspect.getsourcelines(module)
  import_codes = []
  import_codes.append('# -*-coding:utf-8\n')
  for i in all_codelines[0]:
   match = re.search(r'[from]*[\w|\s]*import [\w|\s]*', i)
   if match:
    import_codes.append(i)
  import_codes.extend(['\n', '\n'])

  return import_codes

 @staticmethod
 def get_codes(Model, new_model_name, tb_name):
  """
  獲取基類的實(shí)現(xiàn)代碼
  :param Model:
  :param new_model_name:
  :param tb_name:
  :return:
  """
  codes = inspect.getsourcelines(Model)[0]
  result = []
  has_alias_tb_name = False
  result.append(codes[0].replace(Model.__name__, new_model_name))
  for line in codes[1:]:
   match = re.search(r'\s+__tablename__\s+=\s+\'(?P<name>\w+)\'', line)
   abstract = re.search(r'(?P<indent>\s+)__abstract__\s+=\s+', line)
   if abstract:
    del line
    continue

   if match:
    name = match.groupdict()['name']
    line = line.replace(name, tb_name)
    has_alias_tb_name = True

   result.append(line)

  if not has_alias_tb_name:
   result.append("%s__tablename__ = '%s'\n" % (' ', tb_name))

  return result

 @staticmethod
 def create_new_module(module_name, codes):
  """
  創(chuàng)建新表映射類的module文件
  :param module_name:
  :param codes:
  :return:
  """
  f_path = os.path.join(CURRENT_PATH, '_tmp/%s.py' % module_name)
  fp = open(f_path, 'w')
  for i in codes:
   fp.write(i)
  fp.close()

  return import_module('sync_session.models._tmp.%s' % module_name)

 _instance = dict()

 def __new__(cls, base_cls, tb_name):
  new_cls_name = "%s_To_%s" % (
   base_cls.__name__, ''.join(map(lambda x: x.capitalize(), tb_name.split('_'))))

  if tb_name not in engine.table_names():
   raise TableNotExist

  if new_cls_name not in cls._instance:
   import_codes = cls.get_import_codes(base_cls)
   class_codes = cls.get_codes(base_cls, new_cls_name, tb_name)
   import_codes.extend(class_codes)
   new_module_name = new_cls_name.lower()
   new_module = cls.create_new_module(new_module_name, import_codes)
   model_cls = getattr(new_module, new_cls_name)

   cls._instance[new_cls_name] = model_cls

  return cls._instance[new_cls_name]

2.2 django

# -*-coding:utf-8
from django.db import models


class NewDynamicModel(object):
 """
 動(dòng)態(tài)產(chǎn)生模型和表的對(duì)應(yīng)關(guān)系模型
 :param base_cls: 基類模型,虛類,如TemplateModel
 :param tb_name: 數(shù)據(jù)庫(kù)中對(duì)應(yīng)的表名, 如tb_test_2017
 :return: Model class
 eg:
 '''
 class TemplateModel(models.Model):
  id = models.AutoField(primary_key=True)
  name = models.CharField(max_length=50)

  class Meta:
   abstract = True

 Test_2017 = NewDynamicModel(TemplateModel, 'tb_test_2017')
 print Test_2017.objects.all()
 '''
 """
 _instance = dict()

 def __new__(cls, base_cls, tb_name):
  new_cls_name = "%s_To_%s" % (
   base_cls.__name__, '_'.join(map(lambda x:x.capitalize(),tb_name.split('_'))))

  if new_cls_name not in cls._instance:
   new_meta_cls = base_cls.Meta
   new_meta_cls.db_table = tb_name
   model_cls = type(new_cls_name, (base_cls,),
        {'__tablename__': tb_name, 'Meta': new_meta_cls, '__module__': cls.__module__})
   cls._instance[new_cls_name] = model_cls

  return cls._instance[new_cls_name]

以上這篇flask/django 動(dòng)態(tài)查詢表結(jié)構(gòu)相同表名不同數(shù)據(jù)的Model實(shí)現(xiàn)方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Django權(quán)限機(jī)制實(shí)現(xiàn)代碼詳解

    Django權(quán)限機(jī)制實(shí)現(xiàn)代碼詳解

    這篇文章主要介紹了Django權(quán)限機(jī)制實(shí)現(xiàn)代碼詳解,分享了相關(guān)代碼示例,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下
    2018-02-02
  • 關(guān)于python寫入文件自動(dòng)換行的問題

    關(guān)于python寫入文件自動(dòng)換行的問題

    今天小編就為大家分享一篇關(guān)于python寫入文件自動(dòng)換行的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-06-06
  • python多進(jìn)程共享變量

    python多進(jìn)程共享變量

    這篇文章主要為大家詳細(xì)介紹了python多進(jìn)程共享變量的相關(guān)資料,感興趣的小伙伴們可以參考一下
    2016-04-04
  • python格式化輸出實(shí)例(居中、靠右及靠左對(duì)齊)

    python格式化輸出實(shí)例(居中、靠右及靠左對(duì)齊)

    所謂格式化輸出就是數(shù)據(jù)按照某種特殊的格式和要求進(jìn)行輸出,下面這篇文章主要給大家介紹了關(guān)于python格式化輸出(居中、靠右及靠左對(duì)齊)的相關(guān)資料,文中介紹了format方式、其他擴(kuò)展寫法以及'%'方式,需要的朋友可以參考下
    2022-04-04
  • tsv、csv、xls等文件類型區(qū)別及如何用python處理詳解

    tsv、csv、xls等文件類型區(qū)別及如何用python處理詳解

    近日在處理數(shù)據(jù)的時(shí)候發(fā)現(xiàn)有的文件為csv文件,有的為tsv文件,這篇文章主要給大家介紹了關(guān)于tsv、csv、xls等文件類型區(qū)別及如何用python處理的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-04-04
  • ROS1?rosbag的詳細(xì)使用并且使用python合并bag包的方法

    ROS1?rosbag的詳細(xì)使用并且使用python合并bag包的方法

    這篇文章主要介紹了ROS1?rosbag的詳細(xì)使用,并且使用python來合并bag包,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-05-05
  • Pyspider進(jìn)行API接口抓取和數(shù)據(jù)采集的實(shí)現(xiàn)

    Pyspider進(jìn)行API接口抓取和數(shù)據(jù)采集的實(shí)現(xiàn)

    Pyspider是一個(gè)基于Python的強(qiáng)大的網(wǎng)絡(luò)爬蟲框架,它提供了豐富的功能和靈活的擴(kuò)展性,使我們可以輕松地進(jìn)行數(shù)據(jù)的抓取和處理,本文主要介紹了Pyspider進(jìn)行API接口抓取和數(shù)據(jù)采集的實(shí)現(xiàn),感興趣的可以了解一下
    2023-09-09
  • Python?PyJWT庫(kù)簡(jiǎn)化JSON?Web?Token的生成與驗(yàn)證

    Python?PyJWT庫(kù)簡(jiǎn)化JSON?Web?Token的生成與驗(yàn)證

    PyJWT庫(kù)為Python開發(fā)者提供了簡(jiǎn)便的生成和驗(yàn)證JWT的工具,本文將深入介紹PyJWT庫(kù)的核心概念、功能以及實(shí)際應(yīng)用,通過豐富的示例代碼,幫助大家更全面地了解和應(yīng)用這一強(qiáng)大的JWT庫(kù)
    2023-12-12
  • PIP和conda 更換國(guó)內(nèi)安裝源的方法步驟

    PIP和conda 更換國(guó)內(nèi)安裝源的方法步驟

    這篇文章主要介紹了PIP和conda 更換國(guó)內(nèi)安裝源的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-09-09
  • PyTorch中關(guān)于tensor.repeat()的使用

    PyTorch中關(guān)于tensor.repeat()的使用

    這篇文章主要介紹了PyTorch中關(guān)于tensor.repeat()的使用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-11-11

最新評(píng)論