如何在 python 中使用 Bottle 从 csv 文件获取 API 响应
How to get the API response from a csv file Using Bottle in python
下面是我正在使用的 CSV 文件示例 (sample.csv)
ID Name Address Ph.no Category
1 Person 1 Address 1 1234568789 Category1
2 Person 2 Address 2 1234568790 Category2
3 Person 3 Address 3 1234568791 Category3
4 Person 4 Address 4 1234568792 Category4
5 Person 5 Address 5 1234568793 Category1
6 Person 6 Address 6 1234568794 Category2
7 Person 7 Address 7 1234568795 Category3
8 Person 8 Address 8 1234568796 Category2
9 Person 9 Address 9 1234568797 Category1
我想使用 Bottle Framework 构建一个 restful 网络服务来查询此 CSV 文件。请求将是“/getDetails?category=x”。响应应该是 table ID、姓名、地址的记录(元组),Ph.no 属于类别
这是实现方法之一:
from bottle import route, run, template, response
from json import dumps
import csv
output = []
# API Endpoint
@get('/getDetails')
def get_details():
category = request.forms.get('category')
response.content_type = 'application/json'
# read csv file
csv_file = open("file-question", "r")
reader = csv.reader(csv_file)
#Traversing the CSV file
for row in reader:
if row[4] == category:
output.append(row)
# Return Output
return dumps(output)
run(host='localhost', port=8080)
下面是我正在使用的 CSV 文件示例 (sample.csv)
ID Name Address Ph.no Category
1 Person 1 Address 1 1234568789 Category1
2 Person 2 Address 2 1234568790 Category2
3 Person 3 Address 3 1234568791 Category3
4 Person 4 Address 4 1234568792 Category4
5 Person 5 Address 5 1234568793 Category1
6 Person 6 Address 6 1234568794 Category2
7 Person 7 Address 7 1234568795 Category3
8 Person 8 Address 8 1234568796 Category2
9 Person 9 Address 9 1234568797 Category1
我想使用 Bottle Framework 构建一个 restful 网络服务来查询此 CSV 文件。请求将是“/getDetails?category=x”。响应应该是 table ID、姓名、地址的记录(元组),Ph.no 属于类别
这是实现方法之一:
from bottle import route, run, template, response
from json import dumps
import csv
output = []
# API Endpoint
@get('/getDetails')
def get_details():
category = request.forms.get('category')
response.content_type = 'application/json'
# read csv file
csv_file = open("file-question", "r")
reader = csv.reader(csv_file)
#Traversing the CSV file
for row in reader:
if row[4] == category:
output.append(row)
# Return Output
return dumps(output)
run(host='localhost', port=8080)