django 读取CSV文件并在python中从每一行将HTTP POST发送到API URL?

niwlg2el  于 2023-05-19  发布在  Go
关注(0)|答案(2)|浏览(132)

我有一个csv文件,我想将它发布到Django REST API URL。
我可以发布,但它只是csv文件的最后一行
这是我的代码

import requests
import os
import csv

def insert_data_to_api():
    # CSV file path
    csv_folder = "csv"
    csv_file_name = "my_data.csv"
    csv_file_path = os.path.join(csv_folder, csv_file_name)
    url = "http://127.0.0.1:8000/api/url/"

    with open(csv_file_path, newline='') as file:

        # create a CSV reader object using DictReader
        reader = csv.DictReader(file)

        print("")
        print("==== FOR LOOP =====")
        print("")

        # iterate over each row in the CSV file
        for row in reader:
            # access the values in the row using the column headers
           
            print(row)

        print("")
        print("==== From data =====")
        print("")

        response = requests.post(url, json=row)

        if response.status_code == 200 or 201:
            print("Data inserted successfully")
        else:
            print(f"Failed to insert data: {response.status_code}")

insert_data_to_api()

这就是我使用的代码。试图插入所有但它只插入最后的数据从.csv文件.

jgzswidk

jgzswidk1#

从www.example.com读取csv到dict示例https://docs.python.org/3/library/csv.html?highlight=dictreader#csv.DictReader

import csv
with open('names.csv', newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row['first_name'], row['last_name'])

这是你的大致情况:

rows = []
    with open(read, 'r') as file:
        csvreader = csv.DictReader(file)
        
        for row in csvreader:
            rows.append(row)
    
    print(rows)
    print("")
    print("==== Sending POST to an API URL ===")
    print("")
    
    for row in rows:
        response = requests.post(url, json=json.dumps(row))
        print(response)
huwehgph

huwehgph2#

你实际上想创建一个dict并把它放到你的工作函数中。(您也可以使用pandas模块来完成此操作)。
创建一个dict是这样做的:

import csv

with open('data.csv', 'r') as f:
    reader = csv.DictReader(f)

    data = {}

    for row in reader:
        data[row['region']] = row

现在你可以将dict读/解析到你的函数insert_data_to_api()中,尽管你需要修改它以接受一个dict作为参数。

相关问题