英文:
Read a CSV file and make HTTP POST to API URL from each line in python?
问题
I have a csv file and I want to POST it to a Django REST API URL.
I can post but it's only the last row from the csv file.
This is my code:
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()
That's the code that I used. Tried to insert all, but it inserts only the last data from the .csv file.
英文:
I have a csv file and I want to POST it to an Django REST API URL.
I can post but It's only the last row from the csv file
This is my code
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()
That's the code that i used. tried to insert all but it insert only the last data from .csv file.
答案1
得分: 0
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)
英文:
read csv to dict sample from
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'])
this is the rough outline in your case:
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)
</details>
# 答案2
**得分**: 0
你实际上想创建一个字典,并将其放入你的工作函数中。
(你也可以使用 `pandas` 模块来完成这个任务)。
创建字典的方法如下:
```python
import csv
with open('data.csv', 'r') as f:
    reader = csv.DictReader(f)
    data = {}
    for row in reader:
        data[row['region']] = row
```
现在,你可以将这个字典解析到你的函数 `insert_data_to_api()` 中,尽管你需要修改它以接受一个字典作为参数。
<details>
<summary>英文:</summary>
You actually want to create a dict and put this into your working function.
(You could also do this with the `pandas` module).
creating a dict is done like this:
```python
import csv
with open('data.csv', 'r') as f:
    reader = csv.DictReader(f)
    data = {}
    for row in reader:
        data[row['region']] = row
```
Now you are able to read parse the dict into your function `insert_data_to_api()` although you will need to modify it to take a dict as an argument.
</details>
				通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论