python - 为 Normal Flask python 程序选择年份范围的 Drop 按钮有问题
问题描述
我已经编写了一个基于flask应用程序的程序,该程序主要用于将数据相乘,它将获取用户数据随机打印用户想要的数据5k .. 10k ..等等之后我想通过网页所以我在那里使用了 Flask 我已经添加了文件选择(以浏览 CSV 文件)和记录计数,用户指定他们想要生成多少数据以及我被卡住的非常重要的部分是“从一年开始”和“到年”,这是我通过 HTML 文件中的 JavaScript 执行的,这是一个具有指定年份的下拉按钮
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> upload </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link href="https://bootswatch.com/4/slate/bootstrap.min.css" rel="stylesheet" type="text/css">
</head>
<script>
$( document ).ready(function() {
for(var i=1970; i<=2018; i++){
var fromYearSelect = document.getElementById("fromYear");
var toYearSelect = document.getElementById("toYear");
var option = document.createElement("OPTION");
fromYearSelect.options.add(option);
option.text = i;
option.value = i;
var option2 = document.createElement("OPTION");
toYearSelect.options.add(option2);
option2.text = i;
option2.value = i;
}
});
</script>
<body>
<div class="container">
<div class="jumbotron">
<div class = "mx-auto" style="width:500px;">
<h1>Large Data Generation</h1>
</div>
</div>
<form id = "upload-form" action="{{ url_for('upload') }}" method="POST" enctype="multipart/form-data">
<div id="file-selector">
<strong>Input File: </strong>
<input id="source_fileName" type="file" name="source_fileName" accept="csv/*" multiple style="
margin-left: 30px;">
</div>
<br></br>
<div id="div_records">
<strong>Record Count: </strong>
<input id="records" type="text" name="records" value="1000" >
<br> <br> <br>
<strong>From Year: </strong>
<select id="fromYear" name="fromYear" style="margin-left: 25px;"></select>
<!-- <input type="month" id="fromDate" name="fromDate" multiple style="margin-left: 20px;" > -->
<strong style="margin-left:20px">To Year: </strong>
<select id="toYear" name="toYear" style="margin-left: 5px;"></select>
<!-- <input type="month" id="toDate" name="toDate" multiple style="margin-left: 40px;"> -->
</div>
<br></br><br></br>
<input type="submit" value="Manufacture Data" id="upload-button" >
</form>
</div>
</body>
当我选择年份范围小于 5 时,该程序运行良好,如果我选择超过 5 则它不起作用。
from io import StringIO
import pandas as pd
import numpy as np
import random
import os
import csv
from random import randint
from flask import Flask, render_template, request,Response, redirect, make_response
import boto3
from botocore.client import Config
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
tempFile =""
#defined the flask route
@app.route("/")
def index():
print("Loading the root file")
return render_template("uploadDataManf.html")
@app.route("/uploadDataManf", methods=['POST'])
def upload():
target = os.path.join(APP_ROOT, 'metadata/')
print("target-",target)
if not os.path.isdir(target):
os.mkdir(target)
global recordCount
recordCount = int(request.values.get("records"))
print("recordCount-",recordCount)
global fromYear
fromYear = int(request.values.get("fromYear"))
print("From Year - " + request.values.get("fromYear"));
global toYear
toYear = int(request.values.get("toYear"))
print("To Year - " + request.values.get("toYear"));
for file in request.files.getlist("source_fileName"):
print("file-",file)
filename = file.filename
print("filename-",filename)
destination = "/".join([target, filename])
print("destination-",destination)
file.save(destination)
print("file>",file)
global tempFile
tempFile = destination
print("tempFile - " + tempFile)
#define global scope and reference it
global destination_fileName
destination_fileName = request.form.get('target_fileName')
print("destination_fileName",destination_fileName)
return redirect("/compute", )
def segment():
number= recordCount
a = number
n = 12
assert a >= n >= 1
seg = []
for idx in range(n-1):
# Number between 1 and a
# minus the current total so we don't overshoot
# minus 1 for each number that hasn't been picked
# so they can all be nonzero
seg.append(randint(1,a-sum(seg)-n+idx))
seg.append(a-sum(seg))
random.shuffle(seg)
print("NumberOfseg-",seg)
return seg
@app.route("/compute")
def compute():
Year_Array=[]
for val in range(fromYear, toYear+1):
Year_Array.append(val)
print("Year Array - ",Year_Array)
Month_Array=['Jan','Feb','Mar','April','May','June','July','Aug','Sep','Oct','Nov','Dec']
final_Array=[]
p=0
global recordCount
recordCount = recordCount / len(Year_Array)
df = pd.read_csv(tempFile)
temp = df.iloc[1]
print(temp)
#print(temp.loc)
#print(temp['Asset_Id'])
for p in range(0, len(Year_Array), 1):
c = 0
# Regenerate segments
seg = segment()
for i in range(0,len(seg), 1):
h=seg[i]
for j in range(0, int(h) , 1):
num=randint(0, len(df)-1)
row=df.iloc[num]
final_Array.append(((Year_Array[p], Month_Array[c],row.get("Asset_Id"),row.get("Asset Family"),row.get("Asset Name"),row.get("Location"),row.get("Asset Component"),row.get("Keywords"),row.get("Conditions"),row.get("Parts"))))
c += 1
data = pd.DataFrame(final_Array)
data['SR_ID'] = 'SR_' + pd.Series(np.arange(1, len(data.index) + 1)).astype(str).str.zfill(4)
data.columns = ['Year', 'Month', 'Asset_Id ', 'Asset Family', 'Asset Name', 'Location', 'Asset Component', 'Keywords', 'Conditions', 'Parts','SR_ID']
result = data[['SR_ID','Year', 'Month', 'Asset_Id ', 'Asset Family', 'Asset Name', 'Location', 'Asset Component', 'Keywords', 'Conditions', 'Parts']]
print("result-",result)
resp = make_response(result.to_csv(index=False,))
resp.headers["Content-Disposition"] = "attachment; filename=OutputData.csv"
resp.headers["Content-Type"] = "text/csv"
return resp
if __name__ == '__main__':
app.run(debug=True)
实际上,我知道问题出在compute
哪里:
global recordCount
recordCount = recordCount / len(Year_Array)
如果我删除它,它将解决我的问题,但之后它不会根据用户生成数据,它会将数据与我不想要的年份范围相乘,如果我在记录计数中选择 1k 意味着它应该只打印1k不超过那个。
csv文件的示例输入:
Asset_Id Asset Family Asset Name Location Asset Component Keywords Conditions Parts
1 Haptic Analyser HAL1 Zenoa Tetris Measuring Unit Measurement Inaccuracy, Mirror Angle Skewed Alignment - Lower Axis - positive angle Tetris Controller, Measurement Unit, Processor, Signal Emitter, TDU
1 Haptic Analyser HAL1 Zenoa Micro Pressure Platform Low air pressure, Pressure - Fluctuating Measuring Faces, Cycle Timer, Pressure Simulator, Platform Unit, Sensometer, Pressure Release,
1 Haptic Analyser HAL1 Technopolis Rotation Chamber Rotation Chamber Intermittent Slowdown Current - Fluctuating Anti-Rotation Pin, Springs, Gyroscope, Joiner, Separator, Sealant, Chamber Enclosure, Mount Unit
1 Haptic Analyser HAL1 Technopolis Mirror Lens Combinator Mirror Angle Skewed, Alignment - Mid Axis - negative angle "Mirror Unit, Lens Unit,
2 Hyperdome Inspector HISP1 Technopolis Turbo Quantifier Quantifier output Drops Intermittently Pressure - Low Gas Generator, Quantifier Processing Unit, Turbo Generator, Backup Unit, Turbo Drive
2 Hyperdome Inspector HISP1 Technopolis Generator Generator Power Failure, Vibration - 135% above threshold Generator Armature, Generator Unit, Measurement Gauge, Pressure Gauge, Temperature Gauge,
2 Hyperdome Inspector HISP1 Technopolis High Frequency Emulator Emulator Frequency Drop Speed at entrance - Fluctuating Amplifier, Oscillator, Frequency Emulator, Display Unit, High Frequency Simululator, Drum,
2 Hyperdome Inspector HISP1 Zenoa Center Stage Stage not Balanced Vibration - 110% above threshold Stage Support, Stage Enclosure, Stage Balancer, Alignment Unit, Line Control,
解决方案
推荐阅读
- kubernetes - 无法删除 Kubernetes 中的 apache solr operator CRD
- python - Scrapy 在更好的设备上的执行速度比在更差的设备上慢,我不明白为什么
- python - Xpath Python 从两个标题之间的表中提取数据
- python - 如何加入目录内的所有txt文件?(尊重所有行都在另一行之下)
- visual-studio-code - 如何使 cmd 成为打开 VS Code 时在 VSCode 中打开的默认终端。?
- vb.net - 使用 sendkey 命令 VBA 查看 Excel 公式
- node.js - 如何创建插件以在其他网站上销售我的产品?
- arrays - 为什么即使矩阵中存在元素,我也找不到输出元素?
- c - malloc_chunk 的布局到底是什么样的?
- javascript - 这个终端是什么意思?(使用 Next.js 下一个/路由器)