读取CSV文件并从每一行进行HTTP POST到API URL的Python代码是什么?

huangapple go评论55阅读模式
英文:

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(&#39;data.csv&#39;, &#39;r&#39;) as f:
    reader = csv.DictReader(f)

    data = {}

    for row in reader:
        data[row[&#39;region&#39;]] = 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>



huangapple
  • 本文由 发表于 2023年5月13日 16:13:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76241734.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定