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):
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
]
self
.ruledatas
=
Rule.objects.get(
id
=
rule_id)
self
.check_code
=
self
.ruledatas.check_code
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()
finally
:
cs_ms.close()
conn.close()
return
Response({
'pk'
:pk,
'rule_id'
:rule_id})