python+django自动化平台(一键执行sql) 前端vue-element展示

一、开发环境搭建和配置

复制代码
pip install mysql-connector-python

pip install PyMySQL

二、django模块目录

复制代码
dbOperations
├── __init__.py
├── __pycache__
│   ├── __init__.cpython-313.pyc
│   ├── admin.cpython-313.pyc
│   ├── apps.cpython-313.pyc
│   ├── models.cpython-313.pyc
│   └── views.cpython-313.pyc
├── admin.py
├── apps.py
├── migrations
│   ├── __init__.py
│   └── __pycache__
│       └── __init__.cpython-313.pyc
├── models.py
├── tests.py
└── views.py

三、django模块相关代码

复制代码
***************************settings.py*********************************************

#数据库 连接配置 mysql
DATABASES = {
    'default': {
        # 数据库引擎
        'ENGINE': 'django.db.backends.mysql',
        # 'ENGINE': 'sqlalchemy.create_engine',
        # 数据库名字
        'NAME': 'xx',
        # 数据库用户名
        'USER': 'xx',
        # 数据库密码
        'PASSWORD': 'xx',
        # 数据库主机地址
        'HOST': 'xx',
        # 数据库端口号
        'PORT': 'xx'
    }
}

************************************urls************************************


urlpatterns = [
  path('dbOperations/executeSQLView', db_views.executeSQLView,name='execute_sql_view'),
]

**************************************viwes.py************************************

import json
import logging

from django.db import connection
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from rest_framework import status

from operation.common.enum.ResponeCodeEnum import ResponseCodeEnum
from operation.common.exception.BusinessException import BusinessException
from operation.common.utils.CommonResult import CommonResult
from operation.common.utils.Serializers import SQLExecutionSerializer


# Create your views here.


from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.db import connection
import logging
from rest_framework import status
import json

@csrf_exempt
def executeSQLView(request):
    try:
        if request.method == 'POST':
            json_data = request.body
            print(json_data)
            data = json.loads(json_data)
            sql = data.get('sql', None)
            # 序列化器的正确使用:在 serializer = SQLExecutionSerializer(data={'sql': sql}) 中,
            # 我们传递了一个包含 sql 键的字典,而不是直接传递 SQL 查询字符串。
            serializer = SQLExecutionSerializer(data={'sql': sql})
            if serializer.is_valid():
                sql = serializer.validated_data['sql']
                logging.info("sql:%s" % (sql))
                """
                    使用 with 语句管理游标
                """
                with connection.cursor() as cursor:
                    try:
                        # 执行 SQL 查询:
                        cursor.execute(sql)
                        results = cursor.fetchall()
                        # 处理查询结果:
                        columns = [col[0] for col in cursor.description]
                        # 将查询结果转换为字典列表,每个字典表示一行数据。
                        data = [dict(zip(columns, row)) for row in results]
                        return JsonResponse(CommonResult.success_data(data), json_dumps_params={'ensure_ascii': False})
                    except Exception as e:
                        # return JsonResponse(CommonResult.error(e.code, e.message),
                        #                     json_dumps_params={'ensure_ascii': False})
                        raise BusinessException(e.message, e.code)
            return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        else:
            raise BusinessException(ResponseCodeEnum.METHOD_ERROR.message, ResponseCodeEnum.METHOD_ERROR.code)
    except BusinessException as e:
        return JsonResponse(CommonResult.error(e.code, e.message), json_dumps_params={'ensure_ascii': False})

四、前端代码

复制代码
<template>
  <div class="app-container">
    <el-card shadow="always">
      <el-row :gutter="24">
        <el-input v-model="sqlParam.sql" type="textarea" :rows="10" placeholder="请输入SQL查询" />
        <el-button type="primary" @click="executeSQL">执行</el-button>
      </el-row>
    </el-card>

    <el-card shadow="always">

      <el-table v-if="data.length > 0" :data="data" style="width: 100%">
        <el-table-column v-for="key in Object.keys(data[0])" :key="key" :prop="key" :label="key" />
      </el-table>

    </el-card>
  </div>
</template>

<script>
import {
  executeSQLView
} from '@/api/dataBase/database-request'

export default {
  data() {
    return {
      sqlParam: { // 输入框给出默认值
        sql: ''
      },
      data: [],
      error: ''
    }
  },
  methods: {
    executeSQL() {
      this.dataLoading = true
      console.log('请求参数:' + this.sqlParam)
      executeSQLView(this.sqlParam).then((res) => {
        // alert(JSON.stringify(res.data.data))
        this.data = res.data.data
        setTimeout(() => { // 超过指定超时时间  关闭查询的转圈的loading加载动画
          this.listLoading = false
        }, 1.5 * 1000)
      })
    }
  }
}
</script>

<style>
</style>

五、运行效果

相关推荐
hef2885 小时前
如何生成特定SQL的AWR报告_@awrsqrpt.sql深度剖析单条语句性能
jvm·数据库·python
Jinkxs5 小时前
从语法纠错到项目重构:Python+Copilot 的全流程开发效率提升指南
python·重构·copilot
技术专家5 小时前
Stable Diffusion系列的详细讨论 / Detailed Discussion of the Stable Diffusion Series
人工智能·python·算法·推荐算法·1024程序员节
段一凡-华北理工大学5 小时前
【大模型+知识图谱+工业智能体技术架构】~系列文章01:快速了解与初学入门!!!
人工智能·python·架构·知识图谱·工业智能体
IT小Qi6 小时前
iperf3网络测试工具
网络·python·测试工具·信息与通信·ip
以神为界6 小时前
Python入门实操:基础语法+爬虫入门+模块使用全指南
开发语言·网络·爬虫·python·安全·web
xcjbqd06 小时前
Python API怎么加Token认证_JWT生成与验证拦截器实现
jvm·数据库·python
io_T_T6 小时前
如何调用google api 进行开发(使用免费版本)
python
广师大-Wzx7 小时前
一篇文章看懂MySQL数据库(下)
java·开发语言·数据结构·数据库·windows·python·mysql
hef2888 小时前
golang如何使用range over func_golang range over func迭代器使用方法
jvm·数据库·python