使用for循环时的JSONDecodeError与firestore数据迭代API请求

问题描述 投票:1回答:1

我迷失了为什么这个错误不断发生以及如何解决它。

我正在尝试从我的一个firestore集合中获取数据,使用ID(这是一个股票代码),并通过for循环将该ID迭代到返回JSON数组的API。

每次我运行它,大约三分之一的时间我将得到以下错误,首先显示为错误:404,然后显示以下内容:

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

该脚本适用于前三分之一的数据,但如果我删除了错误所在的集合中的项目,则无法解决问题,因此我认为它不会与文档中的项目有关。登陆了。

我错过了什么吗?

我尝试为404错误添加一个异常,但是我实现得很糟糕,或者它没有解决问题。

import requests
import json
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
import datetime

cred = credentials.Certificate("./serviceAccountKey.json")
firebase_admin.initialize_app(cred)

db = firestore.client()
doc_ref1 = db.collection(u'Quiver').stream()

for doc in doc_ref1:
    symbol = doc.id
    api_url = "https://api.iextrading.com/1.0/stock/{}/company".format(symbol)
    query_url = api_url
    r = requests.get(query_url)

    if r.status_code != 200: 
        print("Error:", r.status_code)

    if r.status_code == 404: 
        print("Error:", r.status_code)

    json_stock = r.json()

    symbol = json_stock['symbol']
    companyName = json_stock['companyName']
    exchange = json_stock['exchange']
    industry = json_stock['industry']
    website = json_stock['website']
    description = json_stock['description']
    CEO = json_stock['CEO']
    issueType = json_stock['issueType']
    sector = json_stock['sector']
    tags = json_stock['tags']

    updateTime = datetime.datetime.now()

    doc_ref = db.collection(u'Quiver').document(u'{}'.format(symbol))
    doc_ref.set({
        u'symbol':u'{}'.format(symbol),
        u'Company Name':u'{}'.format(companyName),
        u'Exchange':u'{}'.format(exchange),
        u'Industry':u'{}'.format(industry),
        u'Website':u'{}'.format(website),
        u'Description':u'{}'.format(description),
        u'Issue Type':u'{}'.format(issueType),
        u'Sector':u'{}'.format(sector),
        u'Tags':u'{}'.format(tags),
        u'Last Update Time':u'{}'.format(updateTime)
    })

    #docs = doc_ref.get({u'summary'})
    print(symbol)
python json python-requests google-cloud-firestore
1个回答
0
投票

对服务记录中不存在的公司的股票请求返回404

当发生这种情况时,print-to stdout不足以处理这个问题,因为非200状态代码的响应主体不是有效的JSON文本。

根据您的业务,您必须跳过非200回复,从其他服务获取股票信息或将其记录为关键问题,以便您可以为服务不再提供股票信息的公司应用策略。

跳过非200响应的第一个选项可以在以下子句中完成。

if r.status_code != 200: 
    print("Error:", r.status_code)
    continue
© www.soinside.com 2019 - 2024. All rights reserved.