【问题标题】:AttributeError: object has no attribute 'get'AttributeError:对象没有属性“get”
【发布时间】:2022-02-26 06:36:31
【问题描述】:

我尝试使用 python 将 json API 中的数据添加到 MySql 数据库中,但出现错误: xx=validate_string(i.get(x, None))AttributeError: 'str' object has no attribute 'get'

我的代码:

import requests
import json
import pymysql

headers = {
  'Accept': 'application/json',
  'api-key': 'xxxxx'
}

r = requests.get('https://api.example.com', params={
  'Id': '432',
  'Id2': '6'
}, headers = headers)
package_json=r.json()

con = pymysql.connect(host='domain.net', user='user', passwd='pass', db='test')
cursor = con.cursor()

def validate_string(val):
    if val != None:
        if type(val) is int:
            return str(val).encode('utf-8')
        else:
            return val


for i in package_json:
    # start off your query string
    query = 'Insert into xxxx ('
    t1=[]
    first_item = True
    for x in i:
        xx=validate_string(i.get(x, None))
        # append the value to the value list
        t1.append(xx)
        if not first_item:
            # add a comma and space to the query if it's not the first item
            query += ', '
        # add the field name to the query
        query += x
        # mark that it's no longer the first item
        first_item = False

    # finish off the query string
    query += ') VALUES {}'
    # and send the query
    cursor.execute(query.format(tuple(t1)))

con.commit()
con.close()

有什么想法可以解决吗?

【问题讨论】:

  • for i in package_json 为您提供package_json 的键列表。您是否想使用for key, i in package_json.items()?或for i in package_json.values()?
  • 我只是想从API中抓取东西并将它们放入Mysql数据库

标签: python mysql-python


【解决方案1】:

这里的主要问题是,当您迭代字典时,您没有得到“项目”,而是得到了键。如果给你:

for x in {"a": 1, "b": 2}:
    print(x)

你会得到:

a
b

或更明确地list({"a": 1, "b": 2}) == ['a', 'b']

所以在您的代码中,for i in package_json 并没有返回您所期望的。它为您提供字典 package_json 中的刺痛键 (i)。由于i 是一个字符串,它没有get() 方法并且你的代码会抛出错误:

xx = validate_string(i.get(x, None))
>>> AttributeError: 'str' object has no attribute 'get'

注意:您在此处遇到的问题与之前的行中相同:

for x in i:

此时x 是字符串i 中的单个字符。

如果不知道您的 package_json 通常是什么样子,就无法确定您应该如何构建代码。如果您使用示例更新您的帖子,我们可能会提供更多帮助。 Maye 从做开始:

for key, i in package_json.items():

看看有没有帮助。

再次提供更多帮助,我们需要查看您的 package_json 的示例。

附录:

鉴于您的 package_json 带有更正看起来有点像:

package_json = {
    "data": [
        {
            "id": 0,
            "name": "Example",
            "links": {"websiteUrl": "https://example.com",},
            "summary": "This is a summary",
            "status": 1,
            "classId": 0,
            "screenshots": [
                {
                    "id": 0,
                    "title": "This is a screenshot",
                    "description": "a screenshot",
                    "thumbnailUrl": "https://example.com",
                    "url": "https://example.com"
                }
            ],
            "mainFileId": 0,
            "latestFiles": [
                {
                    "id": 0,
                    "isAvailable": True,
                    "displayName": "example file",
                    "fileName": "example",
                    "releaseType": 1,
                    "fileStatus": 1,
                    "hashes": [
                        {
                            "value": "string",
                            "algo": 1
                        }
                    ],
                    "fileDate": "2019-08-24T14:15:22Z",
                    "fileLength": 0,
                    "downloadUrl": "https://example.com",
                    "Versions": [
                        "string"
                    ],
                    "latestFilesIndexes": [
                        {
                            "Version": "1",
                            "fileId": 0,
                            "filename": "example file",
                            "releaseType": 1,
                            "VersionTypeId": 0,
                            "Loader": 0
                        }
                    ],
                }
            ],
        }
    ]
}

然后您可能会构建一个插入语句,例如:

SQL_STATEMENT = """
    INSERT INTO xxxx (
        name,
        website,
        summary,
        screenshot,
        file,
        filename,
        version
    ) VALUES (%s, %s, %s, %s, %s, %s, %s);
"""

for data_item in package_json["data"]:
    name = data_item["name"]
    website = data_item["links"]["websiteUrl"]
    summary = data_item["summary"]
    screenshot = data_item["screenshots"][0]["thumbnailUrl"]
    file = data_item["latestFiles"][0]["downloadUrl"]
    filename = data_item["latestFiles"][0]["fileName"]
    version = data_item["latestFiles"][0]["latestFilesIndexes"][0]["Version"]
    cursor.execute (SQL_STATEMENT, (name, website, summary, screenshot, file, filename, version))

【讨论】:

  • 我从 API 得到的答案如下所示:pastebin.com/976JYS9E(因为太长,不能在这里写)我想添加名称、网站、摘要、屏幕截图、文件、文件名、版本等内容在我的数据库中
  • 其中一些数据点是列表。这些项目将如何添加到您的 sql 数据库中?如果数据点是列表,您是否只想添加列表中的第一项?
  • 没有例如:我想在项目中添加“屏幕截图”,所以我只想将指向 thumbnailurl 的链接添加到我的数据库中
  • "screenshots" 和许多其他元素一样是一个列表。如果有两个屏幕截图和两个最新文件,您要添加多少行? 1、2、4?
  • 哦,抱歉,只有 1 行
猜你喜欢
  • 2014-09-08
  • 2021-02-24
  • 2018-05-09
  • 2020-11-27
  • 2018-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多