django 访问数据库返回 JSON数据格式

本文介绍了一个使用Python和Django框架实现的数据库查询功能,通过连接Oracle数据库获取特定时间段内的数据库使用情况,并返回JSON格式的数据供前端展示。

from django.shortcuts import render

# Create your views here.

from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response

# Create your views here.
import cx_Oracle as oracle
import json
def search_db(sqlcmd):
    conn = oracle.connect('test/test@test:1526/orcl')
    cur  = conn.cursor()
    cur.execute(sqlcmd)
    result = cur.fetchall()
#    print ("Exec sql:%s"%(sqlcmd))
    conn.close()
    return result
def cont_json_format(dbname, USED_SIZE, FREE_SIZE,SM_SIZE,OTIME):
    json_str = {"code":200, "message": "OK", "descriptions": {"DB_NAME":dbname, "USED_SIZE": USED_SIZE, "FREE_SIZE": FREE_SIZE, "SM_SIZE":SM_SIZE, "OTIME":OTIME}}
    return json.dumps(json_str)

def cont(request,dbname):
    starttime = request.GET['starttime']
    endtime = request.GET['endtime']
    sql='''select * 
           from ORADB_SIZE t
           where 
            t.DB_NAME = '%s' and 
            t.OTIME > to_date('%s','YYYY/MM/DD') and 
            t.OTIME < to_date('%s','YYYY/MM/DD')''' % (dbname, starttime, endtime)
    result = search_db(sql)
    USED_SIZE = [round(e[1],2) for e in result]
    FREE_SIZE = [round(e[2],2) for e in result]
    SM_SIZE = [round(e[3],2) for e in result]
    OTIME = [e[4].strftime('%Y-%m-%d') for e in result]
    json_data = cont_json_format(dbname, USED_SIZE, FREE_SIZE, SM_SIZE, OTIME)
    return HttpResponse(json_data)


def echarts_cont(request):
    return render_to_response("content.html")

转载于:https://my.oschina.net/zhiyonghe/blog/920475

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值