我目前正在使用python 3.4并在运行代码时收到错误10055。代码如下。
我尝试过设置“time.sleep(10)”并允许我的数据库收集更多条目,但最终我的程序总是出错。
据我所知,当我“sock.close()”我的套接字时,套接字实际上并没有关闭,它在关闭之前会暂停一段时间,这就是造成我的错误的原因。
我无法找到强制连接关闭的方法,以释放套接字并运行程序完成。
我的代码中有很多方法,但是这些方法与我的错误有关,如果你想要整个代码,请告诉我。
from urllib.request import urlopen
import xml.etree.ElementTree as ET
import time
# Connect to MongoDB
def database_connection():
from pymongo import MongoClient
MONGODB_HOST = 'localhost'
MONGODB_PORT = 27017
DBS_NAME = 'SEC'
COLLECTION_NAME = 'Form15F'
connection = MongoClient(MONGODB_HOST, MONGODB_PORT)
collection = connection[DBS_NAME][COLLECTION_NAME]
return collection, connection
# Connection to the .XML online link
def connection(xml_link):
import socket
# Make xml_link readable so it can be manipulated
sock = urlopen(xml_link)
xml_readable = sock.read()
sock.close()
root = ET.fromstring(xml_readable)
return root
# Populate database
def database_addition(Holdings_FundName, Holdings_Name, Holdings_Shares, Holdings_Value, Holdings_Date):
for i in range(len(Holdings_Name)):
dictionary = {'Date':Holdings_Date[i] ,'Fund Name':Holdings_FundName[i],'Holding Company':Holdings_Name[i], 'Number of Shares':Holdings_Shares[i], 'Value of Shares':Holdings_Value[i]}
db, dbc = database_connection()
db.insert(dictionary)
dbc.close()
def main(link):
all_xml_docs = fund_listings(link)
for i in all_xml_docs:
Fund_Name, date, xml_link = fund_details(i)
print(Fund_Name)
print(xml_link)
Holdings_FundName, Holdings_Name, Holdings_Shares, Holdings_Value, Holdings_Date = holdings_attributes(xml_link, Fund_Name, date)
database = database_addition(Holdings_FundName, Holdings_Name, Holdings_Shares, Holdings_Value, Holdings_Date)
time.sleep(10)
答案 0 :(得分:0)
问题出在我连接和断开MongoDB的次数内。我更改了database_addition函数并删除了问题。 我已经发布了两种方法可以更改功能,以消除此问题。第一个是改变for循环之前和之外连接数据库的位置。第二种是使用bulk_insert来填充数据库。
# Populate database
def database_addition(Holdings_FundName, Holdings_Name, Holdings_Shares, Holdings_Value, Holdings_Date):
db, dbc = database_connection()
for i in range(len(Holdings_Name)):
dictionary = {'Date':Holdings_Date[i] ,'Fund Name':Holdings_FundName[i],'Holding Company':Holdings_Name[i], 'Number of Shares':Holdings_Shares[i], 'Value of Shares':Holdings_Value[i]}
db, dbc = database_connection()
db.insert(dictionary)
dbc.close()
insert_bulk:
# Bulk insert
def database_addition_bulk(attribute_list):
db,dbc = database_connection()
db.insert_many([{'Date':attribute_list[0][i], 'Fund Id':attribute_list[1][i], 'Fund Name':attribute_list[2][i],'Holding CUSIP':attribute_list[3][i], 'Holding Name':attribute_list[4][i], 'Number of Shares':attribute_list[5][i], 'Value of Shares':attribute_list[6][i]} for i in range(len(attribute_list[0]))])
dbc.close()