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

前端之家收集整理的这篇文章主要介绍了如何使用Python将API响应存储在MySQL数据库中? 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我真的是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": "wsumanar@gmail.com","date": "February 8,2019","time": "2:00pm","endTime": "3:00pm","dateCreated": "February 5,"datetimeCreated": "2019-02-05T15:57:13-0600","datetime": "2019-02-08T14:00:00-0700",},{
        "id": 264693950,"firstName": "Wade","lastName": "Gulikapupusa","phone": "789691985","email": "W.Gulika77@yhaoo.com","endTime": "2:20pm","dateCreated": "February 4,"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)"""

insertvalues = ('546606','Suneth','Tharinda','8016381256','wimalasena@gmail.com','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数据库上.我不确定这是太多要问的问题,但是任何帮助将不胜感激.

非常感谢您的参与

最佳答案
如果我正确理解了您的问题,那么您只需使用for循环就可以实现此目的.

例如.,

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

猜你在找的MySQL相关文章