这里的工作是将一个从https://xxx.xxx.xxx/xxx/1.jsonhttps://xxx.xxx.xxx/xxx/1417749.json的API从一个站点中删除,并将其准确地写入mongodb.为此,我有以下代码:

client = pymongo.MongoClient("mongodb://127.0.0.1:27017")
db = client["thread1"]
com = db["threadcol"]
start_time = time.time()
write_log = open("logging.log", "a")
min = 1
max = 1417749
for n in range(min, max):
    response = requests.get("https:/xx.xxx.xxx/{}.json".format(str(n)))
    if response.status_code == 200:
        parsed = json.loads(response.text)
        inserted = com.insert_one(parsed)
        write_log.write(str(n) + "\t" + str(inserted) + "\n")
        print(str(n) + "\t" + str(inserted) + "\n")
write_log.close()

但完成这项任务需要很多时间.这里的问题是我如何加快这个过程.

推荐答案

如果不想使用多线程,asyncio也是一个解决方案

import time
import pymongo
import json
import asyncio
from aiohttp import ClientSession


async def get_url(url, session):
    async with session.get(url) as response:
        if response.status == 200:
            return await response.text()


async def create_task(sem, url, session):
    async with sem:
        response = await get_url(url, session)
        if response:
            parsed = json.loads(response)
            n = url.rsplit('/', 1)[1]
            inserted = com.insert_one(parsed)
            write_log.write(str(n) + "\t" + str(inserted) + "\n")
            print(str(n) + "\t" + str(inserted) + "\n")


async def run(minimum, maximum):
    url = 'https:/xx.xxx.xxx/{}.json'
    tasks = []
    sem = asyncio.Semaphore(1000)   # Maximize the concurrent sessions to 1000, stay below the max open sockets allowed
    async with ClientSession() as session:
        for n in range(minimum, maximum):
            task = asyncio.ensure_future(create_task(sem, url.format(n), session))
            tasks.append(task)
        responses = asyncio.gather(*tasks)
        await responses


client = pymongo.MongoClient("mongodb://127.0.0.1:27017")
db = client["thread1"]
com = db["threadcol"]
start_time = time.time()
write_log = open("logging.log", "a")
min_item = 1
max_item = 100

loop = asyncio.get_event_loop()
future = asyncio.ensure_future(run(min_item, max_item))
loop.run_until_complete(future)
write_log.close()

Mongodb相关问答推荐

$mod只支持数字类型,不支持MongoDb中的array和int

获取响应周期中的特定键和值

MongoDB - 将属性添加到数组中的对象(如果不存在)

MongoDB 聚合 - $project 和 $match 阶段未按预期工作

尽管前一阶段输出文档,$group stage 仍返回零文档

在 MongoDB 中加入多个集合

Mongoose 更新不同类型的记录

$group 和 sum + 添加所有大于

替换 MongoDB 中数组中的嵌入文档

使用 mgo 从 golang 中的 Mongodb 中 Select 列

.NET 4 中是否有 mongodb C# 驱动程序支持 System.Dynamic.DynamicObject?

如何在 Ruby on Rails 环境中使用 Mongoid 进行通配符搜索?

MongoDB:单个数据库处理程序的 >5 个打开连接

如何使用 java 驱动程序更新 mongo db 中的文档字段?

在MongoDB中查询一个半​​径内的位置

如何使用 MongoDB C# 驱动程序有条件地组合过滤器?

Mongoose 版本控制:when is it safe to disable it?

从 mongo 结果中删除 _id

使用 mongoengine 将多文档插入到 mongodb

MongoDB:删除唯一约束