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

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

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:

  1. import requests
  2. import os
  3. import csv
  4. def insert_data_to_api():
  5. # CSV file path
  6. csv_folder = "csv"
  7. csv_file_name = "my_data.csv"
  8. csv_file_path = os.path.join(csv_folder, csv_file_name)
  9. url = "http://127.0.0.1:8000/api/url/"
  10. with open(csv_file_path, newline='') as file:
  11. # create a CSV reader object using DictReader
  12. reader = csv.DictReader(file)
  13. print("")
  14. print("==== FOR LOOP =====")
  15. print("")
  16. # iterate over each row in the CSV file
  17. for row in reader:
  18. # access the values in the row using the column headers
  19. print(row)
  20. print("")
  21. print("==== From data =====")
  22. print("")
  23. response = requests.post(url, json=row)
  24. if response.status_code == 200 or 201:
  25. print("Data inserted successfully")
  26. else:
  27. print(f"Failed to insert data: {response.status_code}")
  28. 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

  1. import requests
  2. import os
  3. import csv
  4. def insert_data_to_api():
  5. # CSV file path
  6. csv_folder = "csv"
  7. csv_file_name = "my_data.csv"
  8. csv_file_path = os.path.join(csv_folder, csv_file_name)
  9. url = "http://127.0.0.1:8000/api/url/"
  10. with open(csv_file_path, newline='') as file:
  11. # create a CSV reader object using DictReader
  12. reader = csv.DictReader(file)
  13. print("")
  14. print("==== FOR LOOP =====")
  15. print("")
  16. # iterate over each row in the CSV file
  17. for row in reader:
  18. # access the values in the row using the column headers
  19. print(row)
  20. print("")
  21. print("==== From data =====")
  22. print("")
  23. response = requests.post(url, json=row)
  24. if response.status_code == 200 or 201:
  25. print("Data inserted successfully")
  26. else:
  27. print(f"Failed to insert data: {response.status_code}")
  28. 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

  1. import csv
  2. with open('names.csv', newline='') as csvfile:
  3. reader = csv.DictReader(csvfile)
  4. for row in reader:
  5. print(row['first_name'], row['last_name'])
  1. rows = []
  2. with open(read, 'r') as file:
  3. csvreader = csv.DictReader(file)
  4. for row in csvreader:
  5. rows.append(row)
  6. print(rows)
  7. print("")
  8. print("==== Sending POST to an API URL ===")
  9. print("")
  10. for row in rows:
  11. response = requests.post(url, json=json.dumps(row))
  12. print(response)
英文:

read csv to dict sample from
https://docs.python.org/3/library/csv.html?highlight=dictreader#csv.DictReader

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

this is the rough outline in your case:

  1. rows = []
  2. with open(read, 'r') as file:
  3. csvreader = csv.DictReader(file)
  4. for row in csvreader:
  5. rows.append(row)
  6. print(rows)
  7. print("")
  8. print("==== Sending POST to an API URL ===")
  9. print("")
  10. for row in rows:
  11. response = requests.post(url, json=json.dumps(row))
  12. print(response)
  13. </details>
  14. # 答案2
  15. **得分**: 0
  16. 你实际上想创建一个字典,并将其放入你的工作函数中。
  17. (你也可以使用 `pandas` 模块来完成这个任务)。
  18. 创建字典的方法如下:
  19. ```python
  20. import csv
  21. with open('data.csv', 'r') as f:
  22. reader = csv.DictReader(f)
  23. data = {}
  24. for row in reader:
  25. data[row['region']] = row
  26. ```
  27. 现在,你可以将这个字典解析到你的函数 `insert_data_to_api()` 中,尽管你需要修改它以接受一个字典作为参数。
  28. <details>
  29. <summary>英文:</summary>
  30. You actually want to create a dict and put this into your working function.
  31. (You could also do this with the `pandas` module).
  32. creating a dict is done like this:
  33. ```python
  34. import csv
  35. with open(&#39;data.csv&#39;, &#39;r&#39;) as f:
  36. reader = csv.DictReader(f)
  37. data = {}
  38. for row in reader:
  39. data[row[&#39;region&#39;]] = row
  40. ```
  41. 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.
  42. </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:

确定