将for循环与Firestore数据迭代API请求结合使用时发生JSONDecodeError

时间:2019-04-30 20:33:18

标签: python json python-requests google-cloud-firestore

我一直不知道为什么该错误持续发生以及如何解决。

我试图使用ID(是股票行情自动收录器)从我的一个Firestore集合中取出数据,并通过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)

1 个答案:

答案 0 :(得分:0)

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

print-在发生这种情况时转到stdout不足以处理此问题,因为非200状态代码的响应正文不是有效的JSON文本。

根据您的业务,您必须跳过非200响应,从其他服务获取股票信息或将其记录为严重问题,以便可以对不再使用其股票信息的公司应用政策由服务提供。

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

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