python asyncio 异步实现mongodb数据转xls文件
from pymongo import MongoClient
import asyncio
import xlwt
import json class Mongodb_Transfer_Excel():
def __init__(self, db_name, table_name, ip='127.0.0.1', port=27017, excel_format=None, mongodb_type=None):
""" :param db_name: 数据库名
:param table_name: 数据表名
:param ip: IP
:param port: 端口
:param excel_format: 数据需求的字段:{'content': 0, 'field': 1}
"""
self.ip = ip
self.port = port
self.db_name = db_name
self.table_name = table_name
self.excel_format = excel_format # excel_format如:{'content': 0, 'field': 1}
self.wbk = xlwt.Workbook()
self.sheet = self.wbk.add_sheet(self.table_name)
self.mongodb_type = mongodb_type
self.loop = asyncio.get_event_loop() def db_conn(self):
"""
创建数据库连接
:return:
"""
conn = MongoClient(self.ip, self.port)
db = conn[self.db_name] # 连接mydb数据库,没有则自动创建
conn = db[self.table_name] # 使用test_set集合,没有则自动创建
return conn def find_data(self):
"""
获取mongdb数据
:return:
"""
rows = self.db_conn().find()
return rows def create_excel(self):
"""
根据self.excel_format生成execl
:return:
"""
if self.excel_format:
excel_format = self.excel_format
else:
excel_format = {'content': 0, 'content1': 1, 'title': 2, "weixin_code": 3, "weixin_name": 4, "type": 5, 'pubtime': 6}
self.excel_format = excel_format
for key, value in excel_format.items():
self.sheet.write(0, value, key)
self.wbk.save('{}.xls'.format(self.table_name)) async def parse_rows(self, i, row):
dic = dict()
dic['cloumn'] = i
if 'user' in row:
user_info = row.get('user')
if 'description' in user_info:
dic['description'] = user_info['description']
if 'screenName' in user_info:
dic['screenName'] = user_info['screenName']
if 'result' in row:
result = row['result']
if isinstance(result, str):
result = json.loads(result)
content = result.get('content').replace('\n', '')
if len(content) > 2000:
dic['content'] = content[0: 2000]
dic['conten1'] = content[2000: ]
else:
dic['content'] = content
if 'title' in result:
dic['title'] = result.get('title')
if 'event' in result:
event = result.get('event')
if isinstance(event, str):
event = json.loads(event)
if 'weixin_code' in event:
dic['weixin_code'] = event.get('weixin_code')
if 'weixin_name' in event:
dic['weixin_name'] = event.get('weixin_name')
if 'type' in event:
dic['type'] = event.get('type')
if 'url' in event:
dic['url'] = event.get('url')
if 'pubtime' in result:
dic['pubtime'] = result.get('pubtime')
await asyncio.sleep(1)
self.parse_dic(dic) def parse_dic(self, dic):
for key, value in dic.items():
if key in self.excel_format:
# print(key)
self.write_excel(key, value, dic['cloumn']) def write_excel(self, key, value, columns):
"""
写入数据
:param dic: 数据字典
:param columns: 插入excel的行
:return:
"""
self.sheet.write(columns, int(self.excel_format.get(key)), value) def save_excel(self):
self.wbk.save('{}.xls'.format(self.table_name)) def run(self):
self.create_excel()
rows = self.find_data()
tasks = [self.parse_rows(i + 1, row) for i, row in enumerate(rows)]
self.loop.run_until_complete(asyncio.wait(tasks))
self.loop.close()
self.save_excel() if __name__ == '__main__':
excel_format = {} # 指定excel文件格式如:{'content': 0, 'field': 1}
mongodb_type = 'weibo' # 或者man_sheng_huo
obj = Mongodb_Transfer_Excel(db_name='db_name', table_name='table_name', mongodb_type=mongodb_type,
excel_format=excel_format)
obj.run()
python asyncio 异步实现mongodb数据转xls文件的更多相关文章
- 孤荷凌寒自学python第五十九天尝试使用python来读访问远端MongoDb数据服务
孤荷凌寒自学python第五十九天尝试使用python来读访问远端MongoDb数据服务 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第五天.今天的感觉是,mongoDB数 ...
- python读取数据库并把数据写入本地文件
一,介绍 上周用jmeter做性能测试时,接口B传入的参数需要依赖接口A生成的借贷申请ID,接口A运行完需要把生成的借贷申请ID导出来到一个文件,作为参数传给接口B,刚开始的时候,手动去数据库倒, 倒 ...
- Python学习笔记之将数据写入到文件中
10-3 访客:编写一个程序,提示用户输入其名字:用户作出响应后,将其名字写入到文件guest.txt 中. 编写Python代码: username = input("Please ent ...
- http 异步 接收 回传 数据文字和文件流
public void HttpListenerStar() { try { HttpListener httpListener = new HttpListener(); httpListener. ...
- Python中,添加写入数据到已经存在的Excel的xls文件,即打开excel文件,写入新数据
背景 Python中,想要打开已经存在的excel的xls文件,然后在最后新的一行的数据. 折腾过程 1.找到了参考资料: writing to existing workbook using xlw ...
- R_Studio读取xls文件
百度经验 传送门 需要包xlsx 依赖包rjava 需要安装java编译环境 在R Console中执行命令install.packages("rjava"),install.pa ...
- Python黑魔法 --- 异步IO( asyncio) 协程
python asyncio 网络模型有很多中,为了实现高并发也有很多方案,多线程,多进程.无论多线程和多进程,IO的调度更多取决于系统,而协程的方式,调度来自用户,用户可以在函数中yield一个状态 ...
- (转)Python黑魔法 --- 异步IO( asyncio) 协程
转自:http://www.jianshu.com/p/b5e347b3a17c?from=timeline Python黑魔法 --- 异步IO( asyncio) 协程 作者 人世间 关注 201 ...
- 消息/事件, 同步/异步/协程, 并发/并行 协程与状态机 ——从python asyncio引发的集中学习
我比较笨,只看用await asyncio.sleep(x)实现的例子,看再多,也还是不会. 已经在unity3d里用过coroutine了,也知道是“你执行一下,主动让出权限:我执行一下,主动让出权 ...
随机推荐
- Django 之Ajax
必备知识:json 什么是json 定义 JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式. 它基于 ECMAScript (w3c制定的 ...
- 【MFC】VC界面绘制双缓存
VC界面绘制双缓存 转载请注明原文网址: http://www.cnblogs.com/xianyunhe/archive/2011/11/20/2255811.html 1.闪屏的问题在GDI的绘图 ...
- Biology(湖南集训)
题目大意:n个字符串,m个操作,可以插入字符串,也可以询问某T个字符串的最长后缀 题解:Trie+lca Trie树的插入与查询操作.把字符串反转就相当于求公共前缀. lca的深度就是公共前缀的长度. ...
- Spring IOC容器在Web容器中是怎样启动的
前言 我们一般都知道怎样使用spring来开发web应用后,但对spring的内部实现机制通常不是很明白.这里从源码角度分析下Spring是怎样启动的.在讲spring启动之前,我们先来看看一个web ...
- 错过的sql语句
总结: 内链接:适合和自己的条件对比,但并没有给出具体条件,要从数据库表里面找,注意有些条件两个表都需要写(嵌套查询貌似也可以 左连接:适合一个表要全部列出来的情况(使用count的时候,注意coun ...
- Delphi单元文件之-简体繁体互转
Function GBCht2Chs(GBStr: String): AnsiString; {GBK繁体转简体} Var len:integer; pGBCHTChar: PChar; ...
- mysql5.7不支持0000-00-00 00:00:00的默认时间设置
方案一: 数据不多的话把原有的5.53的数据改一下符合要求(数据库时间字段里千万不能出现0000-00-00 00:00:00这样的值),然后导出.sql文件,导出的.sql文件里把 DEFAULT ...
- ByteBuf 类——Netty 的数据容器
1.堆缓冲区 2.直接缓冲区 3.复合缓冲区 —CompositeByteBuf——实现了这个模式,它提供了一 个将多个缓冲区表示为单个合并缓冲区的虚拟表示 适用于 JDK 所使用的一种称为分散/收集 ...
- codeforce 985A Chess Placing(暴力)
Chess Placing time limit per test 1 second memory limit per test 256 megabytes input standard input ...
- 第十五届浙江省赛 F Now Loading!!!
Now Loading!!! Time Limit: 1 Second Memory Limit: 131072 KB DreamGrid has integers . DreamGrid ...