如何使用Python来存储在MySQL数据库API响应?

问题描述 投票:3回答:2

我真的很新的到Python,MySQL和API开发。所以,我有一个从创建日历调度使用邮差(后在线研究小时)一个简单的请求。我能够创建本地主机上的MySQL数据库。我可以插入使用Python的数据,但我想没有手动存储API响应。请看看我的代码,我真的很感激,如果任何机构可以帮助我在此。

使用Python请求调用

    import requests

    url = "https://shedul.com/api/v1/appointments"
    querystring = {"minDate":"02/01/2019","maxDate":"02/08/2019"}

    payload = ""
    headers = {
        'Authorization': "Basic ************************"}

    response = requests.request("GET", url, data=payload, headers=headers, params=querystring)
    print(response.json())

我会得到回应这样的事情(我将这么多的要求和更多的领域,但我需要那几个字段),

[
    {
        "id": 2649,
        "firstName": "Walikada",
        "lastName": "Sumana",
        "phone": "7894561452",
        "email": "[email protected]",
        "date": "February 8, 2019",
        "time": "2:00pm",
        "endTime": "3:00pm",
        "dateCreated": "February 5, 2019",
        "datetimeCreated": "2019-02-05T15:57:13-0600",
        "datetime": "2019-02-08T14:00:00-0700",
    },
    {
        "id": 264693950,
        "firstName": "Wade",
        "lastName": "Gulikapupusa",
        "phone": "789691985",
        "email": "[email protected]",
        "date": "February 8, 2019",
        "time": "2:00pm",
        "endTime": "2:20pm",
        "dateCreated": "February 4, 2019",
        "datetimeCreated": "2019-02-04T15:05:07-0600",
        "datetime": "2019-02-08T14:00:00-0600",
     }
]

代码,我发现连接MySQL数据库,

import mysql.connector

connection = mysql.connector.connect(
              host="localhost",
              user="root",
              passwd="admin",
              database="techbrandtest"
            )
mycursor = connection.cursor()

sqlcode = """INSERT INTO techbrandtest.acuity 
                (
                    id, 
                    firstName, 
                    lastName,
                    phone,
                    email,
                    date,
                    time,
                    endTime,
                    dateCreated,
                    datetimeCreated,
                    datetime                     

                ) 
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""

insertvalues = ('546606', 'Suneth', 'Tharinda', '8016381256', '[email protected]', '2019-02-02', '', '','2019-02-02','2019-02-02 23:59:59', '2019-02-05 23:59:59')

mycursor.execute(sqlcode, insertvalues)
connection.commit()
print(mycursor.rowcount, "was inserted.")

我想让它一个代码,并存储在MySQL数据库的每个响应。我不知道这是过分的要求,但任何帮助将不胜感激。

非常感谢您的参与

python mysql python-3.x api mysql-python
2个回答
1
投票

如果我正确理解你的问题,那么你应该能够通过简单地使用一个for循环来实现这一目标。

EG,

    for i in response:
        mycursor.execute(sqlcode, (i['id'],i['firstName']))           

1
投票

在Python中你有处理数据库非常有用的工具。其所谓的SQLAlchemy的。有了它的帮助,你不需要写原始SQL,您可以使用数据库表作为Python对象。虽然你需要了解它的API。

反应可以存储为JSON场数据库,也可以让更多的表,它(如果响应看起来都一样的时间)。您可以发送回应之前保存它,它就会“自动”保存。

如果您还有其他问题或我的答案不包含你所需要的,不只是发表评论这个答案。祝你有美好的一天。

© www.soinside.com 2019 - 2024. All rights reserved.