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文件的更多相关文章

  1. 孤荷凌寒自学python第五十九天尝试使用python来读访问远端MongoDb数据服务

    孤荷凌寒自学python第五十九天尝试使用python来读访问远端MongoDb数据服务 (完整学习过程屏幕记录视频地址在文末) 今天是学习mongoDB数据库的第五天.今天的感觉是,mongoDB数 ...

  2. python读取数据库并把数据写入本地文件

    一,介绍 上周用jmeter做性能测试时,接口B传入的参数需要依赖接口A生成的借贷申请ID,接口A运行完需要把生成的借贷申请ID导出来到一个文件,作为参数传给接口B,刚开始的时候,手动去数据库倒, 倒 ...

  3. Python学习笔记之将数据写入到文件中

    10-3 访客:编写一个程序,提示用户输入其名字:用户作出响应后,将其名字写入到文件guest.txt 中. 编写Python代码: username = input("Please ent ...

  4. http 异步 接收 回传 数据文字和文件流

    public void HttpListenerStar() { try { HttpListener httpListener = new HttpListener(); httpListener. ...

  5. Python中,添加写入数据到已经存在的Excel的xls文件,即打开excel文件,写入新数据

    背景 Python中,想要打开已经存在的excel的xls文件,然后在最后新的一行的数据. 折腾过程 1.找到了参考资料: writing to existing workbook using xlw ...

  6. R_Studio读取xls文件

    百度经验 传送门 需要包xlsx 依赖包rjava 需要安装java编译环境 在R Console中执行命令install.packages("rjava"),install.pa ...

  7. Python黑魔法 --- 异步IO( asyncio) 协程

    python asyncio 网络模型有很多中,为了实现高并发也有很多方案,多线程,多进程.无论多线程和多进程,IO的调度更多取决于系统,而协程的方式,调度来自用户,用户可以在函数中yield一个状态 ...

  8. (转)Python黑魔法 --- 异步IO( asyncio) 协程

    转自:http://www.jianshu.com/p/b5e347b3a17c?from=timeline Python黑魔法 --- 异步IO( asyncio) 协程 作者 人世间 关注 201 ...

  9. 消息/事件, 同步/异步/协程, 并发/并行 协程与状态机 ——从python asyncio引发的集中学习

    我比较笨,只看用await asyncio.sleep(x)实现的例子,看再多,也还是不会. 已经在unity3d里用过coroutine了,也知道是“你执行一下,主动让出权限:我执行一下,主动让出权 ...

随机推荐

  1. oracle的序列号(sequence)

    oracle的自增列,要采用序列号(sequence). 初始化阶段要手动建立一个sequence,然后插入的时候,还要手动自己去读这个sequence的nextval赋给相关字段,如ID,麻烦的很. ...

  2. Kotlin For Gank.io (干货集中营Kotlin实现)

    介绍 Kotlin,现在如火如荼,所以花了一点时间把之前的项目用Kotlin重构一下 原项目地址:https://github.com/onlyloveyd/GankIOClient 对应Kotlin ...

  3. 通用线程:POSIX 线程详解,第 3 部分

    通用线程:POSIX 线程详解,第 3 部分 使用条件变量提高效率 Daniel Robbins, 总裁兼 CEO, Gentoo Technologies, Inc. 简介: 本文是 POSIX 线 ...

  4. HTML里 iframe跳转后关闭iframe

    if(window != top){      top.location.href = location.href;    }

  5. DNS域名解析负载均衡

  6. wlan经常掉线怎么办?

    有没有这样的情款,好好的网络总是突然断掉然,之后就需要重新连接,连接以后没多久有需要重新连接.本次经验就来和大家一起分享一下几种情况的解决方法,非常的简单实用. 工具/原料 电脑 电源设置问题 1.本 ...

  7. IOS socket编程--Asyncsocket

    iPhone的标准推荐是CFNetwork 库编程,其封装好的开源库是 cocoa AsyncSocket库,用它来简化CFNetwork的调用,它提供了异步操作 主要特性有: 队列的非阻塞的读和写, ...

  8. UVA136 Ugly Numbers

    题意 PDF 分析 用堆和集合维护即可. 时间复杂度\(O(1500 \log n)\) 代码 #include<iostream> #include<cstdio> #inc ...

  9. jquery移除、绑定、触发元素事件

    unbind(type [,data]) //data是要移除的函数 $('#btn').unbind("click"); //移除click $('#btn').unbind() ...

  10. fn project 试用之后的几个问题

    今天试用fnproject  之后自己有些思考,后面继续解决   1. 目前测试是强依赖 dockerhub 的,实际可能不是很方便 2. 如何与k8s .mesos.docker swarm  集成 ...