我正在 Flask 中编写这个 POST 请求端点:
app.route('/transactions', methods=['POST'])
def upload_transactions():
file = request.files['data']
if 'data' not in request.files:
return 'No file part', 400
if file.filename == '':
return 'No selected file', 400
if file:
#define headers
headers = ['Date', 'Type', 'Amount($)', 'Memo']
# read csv data
csv_data = StringIO(file.stream.read().decode("UTF8"), newline=None)
# add headers to the beginning of the input csv file
csv_content = ','.join(headers) + '\n' + csv_data.getvalue()
#reset file position to the beginning
csv_data.seek(0)
#Read csv file with headers now
transactions = csv.reader(csv_data)
for row in transactions:
if len(row) != 4:
return 'Invalid CSV format', 400
try:
date = datetime.datetime.strptime(row[0], "%m/%d/%Y").date()
type = row[1]
amount = float(row[2])
memo = row[3]
transaction = Transaction(date=date, type=type, amount=amount, memo=memo)
db.session.add(transaction)
except ValueError:
db.session.rollback()
return 'Invalid amount format', 400
db.session.commit()
return 'Transactions uploaded successfully', 201
问题是当我运行应用程序时,有另一个 GET 请求来获取应作为此 POST 请求的一部分保存在数据库中的记录,而实际上,我没有看到任何记录保存在数据库中。有人可以帮助我知道我在这里可能缺少什么吗?
以下示例根据您的代码向您展示如何成功地将 CSV 文件的行添加到数据库中。
io.TextIOWrapper
来转换二进制数据。
请记住,在查询值之前,首先检查该文件是否包含在字典中。此外,仅当
db.session.rollback()
失败时才需要调用 db.session.commit()
。
import io
# ...
@app.post('/transactions')
def upload_transactions():
if 'data' not in request.files:
return 'No file part', 400
file = request.files['data']
if file.filename == '':
return 'No selected file', 400
with io.TextIOWrapper(file) as fd:
reader = csv.reader(fd)
for row in reader:
if len(row) != 4:
return 'Invalid CSV format', 400
date, type_, amount, memo = row
try:
date = datetime.datetime.strptime(date, '%m/%d/%Y').date()
amount = float(amount)
except ValueError:
return 'Invalid format', 400
transaction = Transaction(date=date, type=type_, amount=amount, memo=memo)
db.session.add(transaction)
try:
db.session.commit()
except:
db.session.rollback()
return 'Transactions uploaded successfully', 201