Can';t在FLASK/Python中上载/下载文件;Can';“我看不到这一页”;
我不熟悉烧瓶,这是我的第一个任务。 我正在尝试使用Python实现一个简单的RESTAPI 框架API应该能够在Linux机器上作为独立服务运行,并且可以通过命令行工具(cURL、wget e.t.c)访问。 任务是创建一个应用程序,该应用程序(A)接收每个地址带有经度/纬度坐标的CSV文件,以及(B)返回一个JSON文件,其中包含所有 每个点之间可能存在的直接链接,包括以米为单位的距离。我已经管理了1和2,但当我必须创建基于烧瓶的应用程序时,问题出现了: 当我通过Anaconda提示符运行我的应用程序时,会发生以下情况:Can';t在FLASK/Python中上载/下载文件;Can';“我看不到这一页”;,python,flask,download,upload,Python,Flask,Download,Upload,我不熟悉烧瓶,这是我的第一个任务。 我正在尝试使用Python实现一个简单的RESTAPI 框架API应该能够在Linux机器上作为独立服务运行,并且可以通过命令行工具(cURL、wget e.t.c)访问。 任务是创建一个应用程序,该应用程序(A)接收每个地址带有经度/纬度坐标的CSV文件,以及(B)返回一个JSON文件,其中包含所有 每个点之间可能存在的直接链接,包括以米为单位的距离。我已经管理了1和2,但当我必须创建基于烧瓶的应用程序时,问题出现了: 当我通过Anaconda提示符运
App/ [app.py, downloads/, uploads/, templates/upload.html]
导入csv
导入操作系统
从数学输入sin、cos、sqrt、atan2、弧度
从werkzeug导入安全文件名
从flask导入flask、jsonify、请求、呈现模板、flash、重定向、url、从目录发送
导入网络浏览器
app=Flask(\uuuuu名称\uuuuuuuuuuuuuuuuuuuuuuuuuu,模板\uuuuuu文件夹='templates')
app.secret\u key=“秘钥”
app.config['UPLOAD_FOLDER']=os.path.dirname(os.path.abspath(_file__))+'/uploads/'
DOWNLOAD_FOLDER=os.path.dirname(os.path.abspath(_file__))+'/downloads/'
app.config['DOWNLOAD_FOLDER']=DOWNLOAD_FOLDER
允许的_扩展={'csv'}
允许的def_文件(文件名):
在文件名和文件名中返回“.”。rsplit(“.”,1)[1]。在允许的扩展名中返回lower()
@应用程序路径(“/”)
def upload_form():
返回渲染模板('file\u upload\u form.html')
@app.route('/',方法=['GET','POST'])
def index():
如果request.method==“POST”:
如果“文件”不在request.files中:
打印('请求中没有附加文件')
返回重定向(request.url)
file=request.files['file']
如果file.filename=='':
打印('未选择文件')
返回重定向(request.url)
如果文件和允许的文件(file.filename):
filename=secure\u文件名(file.filename)
保存(os.path.join(app.config['UPLOAD\u FOLDER'],文件名))
进程文件(os.path.join(app.config['UPLOAD\u FOLDER'],文件名))
返回重定向(url_for('uploaded_file',filename=filename))
返回渲染模板('index.html')
def过程_文件(点):
def upload_文件():
如果request.method==“POST”:
点=请求.files['file']
保存(安全文件名(points.filename))
返回点
def计算_距离(lat1、lon1、lat2、lon2):
#地球的近似半径(mm)
半径=6371.0*1000
dlat=弧度(lat2-lat1)
dlon=弧度(lon2-lon1)
a=sin(dlat/2)*sin(dlat/2)+cos(弧度(lat1))\
*cos(弧度(lat2))*sin(dlon/2)*sin(dlon/2)
c=2*atan2(sqrt(a),sqrt(1-a))
d=半径*c
返回d
打开(点,换行=“”)作为csvfile:
reader=csv.DictReader(csvfile)
点数=[]
链接=[]
对于读取器中的行:
p={“name”:list(row.items())[0][1],“address(La/Lo)”:(list(row.items())[1][1],list(row.items())[2][1])
点。附加(p)
l=[]
对于点到点:
对于点中的v.values():
l、 附加(五)
链接=[]
对于范围(0,len(l)-1,2)内的i:
如果(i>0):
对于范围(i-2,0,-2)内的j:
links.append({'name':l[i]+l[j],'distance':计算_距离(float(l[i+1][0]),float(l[i+1][1]),float(l[j+1][0]),float(l[j+1][1]))
其他:
对于范围内的j(i+2,len(l),2):
links.append({'name':l[i]+l[j],'distance':计算_距离(float(l[i+1][0]),float(l[i+1][1]),float(l[j+1][0]),float(l[j+1][1]))
返回jsonify({points:points,links:links})
@app.route(“/uploads/”)
def上传文件(文件名):
从_目录返回发送_(app.config['DOWNLOAD_FOLDER'],文件名,如_attachment=True)
如果名称=“\uuuuu main\uuuuuuuu”:
webbrowser.open('http://localhost:5000')
port=int(os.environ.get(“port”,5000))
app.run(host='127.0.0.1',port=port)
app.run()
和模板(upload.html):
CSV上传器
经纬度测量仪
上载新文件
提前谢谢 您应该添加
print()
并在控制台中运行,以查看执行了哪个函数以及在变量中得到了什么。在控制台中没有收到任何错误消息吗?您还可以在debug
模式下运行它-app(…,debug=True)
。我可能会显示一些信息。代码适合我-它上载文件。Python3.7,LinuxMint。也许可以检查print(app.config['UPLOAD\u FOLDER'])
查看它试图保存文件的文件夹。您还可以检查哪些用户有权在此文件夹(和父文件夹)中写入文件。谢谢@furas。问题似乎源于我的电脑(我在Wondows上)的系统参数。很高兴它对你有用。
import csv
import os
from math import sin, cos, sqrt, atan2, radians
from werkzeug import secure_filename
from flask import Flask, jsonify, request, render_template, flash, redirect, url_for, send_from_directory
import webbrowser
app = Flask(__name__, template_folder = 'templates')
app.secret_key = "secret key"
app.config['UPLOAD_FOLDER'] = os.path.dirname(os.path.abspath(__file__)) + '/uploads/'
DOWNLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/downloads/'
app.config['DOWNLOAD_FOLDER'] = DOWNLOAD_FOLDER
ALLOWED_EXTENSIONS = {'csv'}
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/')
def upload_form():
return render_template('file_upload_form.html')
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
if 'file' not in request.files:
print('No file attached in request')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
print('No file selected')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
process_file(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('uploaded_file', filename=filename))
return render_template('index.html')
def process_file(points):
def upload_file():
if request.method == 'POST':
points = request.files['file']
points.save(secure_filename(points.filename))
return points
def calculate_distance(lat1, lon1, lat2, lon2):
# approximate radius of earth in mm
radius = 6371.0 * 1000
dlat = radians(lat2-lat1)
dlon = radians(lon2-lon1)
a = sin(dlat/2) * sin(dlat/2) + cos(radians(lat1)) \
* cos(radians(lat2)) * sin(dlon/2) * sin(dlon/2)
c = 2 * atan2(sqrt(a), sqrt(1-a))
d = radius * c
return d
with open(points, newline='') as csvfile:
reader = csv.DictReader(csvfile)
points = []
links = []
for row in reader:
p = {"name": list(row.items())[0][1], "address (La/Lo)": (list(row.items())[1][1], list(row.items())[2][1])}
points.append(p)
l = []
for point in points:
for v in point.values():
l.append(v)
links = []
for i in range(0, len(l) -1 , 2):
if(i>0):
for j in range(i-2, 0, -2):
links.append({'name': l[i] + l[j], 'distance': calculate_distance(float(l[i+1][0]), float(l[i+1][1]), float(l[j+1][0]), float(l[j+1][1]))})
else:
for j in range(i+2, len(l), 2):
links.append({'name': l[i] + l[j], 'distance': calculate_distance(float(l[i+1][0]), float(l[i+1][1]), float(l[j+1][0]), float(l[j+1][1]))})
return jsonify({points : points, links : links})
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename, as_attachment=True)
if __name__ == "__main__":
webbrowser.open('http://localhost:5000')
port = int(os.environ.get("PORT", 5000))
app.run(host='127.0.0.1', port=port)
app.run()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSV UPLOADER</title>
</head>
<body>
<div align="center">
<h1>LONGITUDE/LATITUDE measurer</h1>
<h2>Upload new File</h2>
<form method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
</div>
</body>
</html>