django mysql json数据库_python+django读取json数据,同步数据库

该博客介绍了如何在Django环境中,通过Python读取JSON数据并同步到MySQL数据库中。首先,它设置了Django管理环境,然后定义了处理数据的函数,包括读取文件、解析JSON、比较数据库记录并更新或插入新数据。最后,通过读取日志文件并调用相应函数来执行同步操作。
摘要由CSDN通过智能技术生成

[["account_detail", 1],

["account", 1], ["account_recharge", 3]]

########################################################

#!/usr/bin/python

#coding=utf-8

from django.core.management import setup_environ

#import sys

#sys.path.append('..')

from payment import settings

setup_environ(settings)

#------------------------------------

from datetime import datetime,date,timedelta

from payment.models import *

from django.db.models import Q,Avg,Sum,Count

from django.db import connection

from django.db import transaction

from django.contrib.sessions.models import Session

import json

import time

from decimal import *

from payhandler import mytest,plans

from payment.app import log

import os

import sys

import re

logger=log.get_logger('syncdb',__name__)

data=[]

def writetxt(jdata):

f=open('syncdb.txt','w')

f.write(jdata)

f.close()

def test4(data1):

#把所有表对象放到一个元组中

tab=(account,account_detail,account_recharge,account_recharge_log,user_login_log,credit_class,credit_rule,

festival_datelist,excute_datelist,schedule_list,credit_exec,partner_credit,

partner_credit_detail,latefee_detail,account_status_log,messages,ignore_date_list,amount_level,

account_daily_summary,account_daily_summary_detail)#需要同步的对象

for i in data1:

tabstr=i[0]

if(i[1]==""):

id=1

print(i[1])

id=int(i[1])

for j in tab:

strcut= str(j)[23:-2]

if cmp(strcut,tabstr)==0:

print strcut

r =j.objects.using('aa').order_by('id').filter(pk__gt=id)[:2]

if len(r)>0:

for rvalue in r:

rvalue.save()

value1=rvalue

print (u'数据库:%s,同步到id为:%s'%(tabstr,value1.id))

data2=[]

data2.append(tabstr)

data2.append(value1.id)

data.append(data2)

else:

print(u"未发现没有同步的数据")

#读取txt中需要同步的json数据

def readjson():

f =open("log.txt",'r')

line = f.readline()

fdata=line

while line:

line=f.readline()

fdata=fdata+line

f.close()

print (u"***********************同步数据库开始***************************")

starttime=time.time()

print fdata

data1 = json.loads(fdata)

test4(data1)

print data1[0]

jsondata=json.dumps(data)

print jsondata

writetxt(jsondata)

endtime=time.time()

print("同步数据所需的时间:"+str(endtime-starttime)+"秒")

print (u"***********************同步数据库结束***************************")

if __name__=='__main__':

readjson()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值