1. 程式人生 > >Django多資料來源接入類

Django多資料來源接入類

from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework import status
from django.db import transaction


from .contants import db_dict

contants.py的內容

import cx_Oracle
import pymysql

# 定義一個數據庫型別&引擎的字典,
db_dict = {'mysql':pymysql,'Oracle':cx_Oracle}


from .models import DataSystem,Rule


class DBconnectView(GenericAPIView):
    __DBtype = db_dict
    def get(self,request,pk,rule_id):

        # 通過傳入的id進行對應的資料庫連結
        self.datas = DataSystem.objects.get(pk=pk)
        self.url = self.datas.url
        self.username = self.datas.username
        self.password = self.datas.password_enc
        self.DBname = self.datas.name
        self.DBtype = self.__DBtype[self.datas.type]

        # 獲取check_code規則
        self.ruledatas = Rule.objects.get(id=rule_id)
        self.check_code = self.ruledatas.check_code
        # db = __import__(self.DBtype)

        try:
            conn = self.DBtype.connect(host=self.url,user=self.username,password=self.password,database=self.DBname)
            # 連結成功後建立一個遊標
            cs_ms = conn.cursor()
        except Exception as e:
            raise e
        else:
            # 明顯的開啟事務
            with transaction.atomic():
                # 在安全的地方,建立儲存點,將來操作資料庫失敗回滾到此
                save_id = transaction.savepoint()

                try:

                    # 獲取一個元組
                    db_ret = cs_ms.execute(self.check_code)
                except Exception as e:
                    transaction.savepoint_rollback(save_id)
                    raise e
                else:
                    db_set = db_ret.fetchone()
                    # transaction.savepoint_commit(save_id)
        finally:
            cs_ms.close()
            conn.close()

        return Response({'pk':pk,'rule_id':rule_id})