编辑3:
我正在尝试从pythonanywhere上的csv文件显示信息,从用户输入提示到表单。
我已将client_db.csv加载到pythonanywhere上的文件中:' /home/myusername/mydirectory/client_db.csv'。
基本上,用户可以输入地址:(表单)'以及' name',' shack',' status& #39;和'付款'会显示。
这是我到目前为止的尝试(第3节),但我没有让它发挥作用。我怀疑html输入有问题吗?
from flask import Flask
import os
import sys
import csv
import numpy as np
app = Flask(__name__)
app.config["DEBUG"] = True
path = '/home/myusername/ishack'
if path not in sys.path:
sys.path.append(path)
client_db = np.genfromtxt('/home/myusername/ishack/client_db.csv', delimiter=',',dtype=None, names=True)
@app.route('/')
def form()
return """
<html>
<body>
<h1>Enter a Shack Number</h1>
<form action="/address" method="POST">
<textarea class="form-control" name="address" placeholder="Enter a Shack Number"></textarea>
<input type="submit" />
</form>
</body>
</html>
"""
@app.route('/address', methods=["POST"])
def display_info(address):
ind = np.where(client_db['Shack']==address)[0]
return {'Name': client_db['Name'][ind],
'Shack': client_db['Shack'][ind],
'Status': client_db['Status'][ind],
'Payments': client_db['Payments'][ind]}
display_info(address)
答案 0 :(得分:0)
您刚发布的代码中存在小问题:
另外,请注意,您正在错误地索引矩阵,首先是列,然后是行,后面恰好相反。正确的句子是(注意例如在姓名之前):
return {'Name':client_db [ind] ['Name'] [0], 'Shack':client_db [ind] ['Shack'] [0], '状态':client_db [ind] ['状态'] [0], '付款':client_db [ind] ['付款'] [0]}
最后一个问题与表单的POST有关。要获取必须使用的地址数据:address = request.form [“address”]
为了完成代码,此示例返回一个JSON数据,其中包含CSV文件中的字段:
from flask import Flask, request, Response
from flask import request
import json
import os
import sys
import csv
import numpy as np
app = Flask(__name__)
app.config["DEBUG"] = True
path = '/home/myusername/ishack'
if path not in sys.path:
sys.path.append(path)
client_db = np.genfromtxt('/home/myusername/ishack/client_db.csv', delimiter=',', dtype=None, names=True)
@app.route('/')
def form():
return """
<html>
<body>
<h1>Enter a Shack Number</h1>
<form action="/address" method="POST">
<textarea class="form-control" name="address" placeholder="Enter a Shack Number"></textarea>
<input type="submit" />
</form>
</body>
</html>
"""
@app.route('/address', methods=["POST"])
def display_info():
address = request.form["address"]
ind = np.where(client_db['Shack'] == address)[0]
res = {'Name': client_db[ind]['Name'][0],
'Shack': client_db[ind]['Shack'][0],
'Status': client_db[ind]['Status'][0],
'Payments': client_db[ind]['Payments'][0]}
return Response(json.dumps(res), mimetype='application/json')
app.run(host="0.0.0.0", port=5000)