import os
import hfpy_utils
FOLDER="swimdata/"
CHARTS="charts/"
def read_swim_data(filename):
#unpacks the filename into different variales and removes the .txt suffix
swimmer, age, distance, stroke = filename.removesuffix(".txt").split("-")
#gets the path, opens the file, reads the lines, and splits the first line into a list of times
with open(FOLDER + filename) as file:
lines = file.readlines()
times=lines[0].strip().split(",")
#print(times)
time_in_hun=[]
for f in times:
if ":" in f:
minutes, rest= f.split(":")
seconds, hundredths= rest.split(".")
else:
minutes=0
seconds, hundredths= f.split(".")
total_time=(int(minutes)*60*100 + int(seconds)*100+ int(hundredths))
time_in_hun.append(total_time)
import statistics
average=statistics.mean(time_in_hun)
# average/100
# round(average/100, 2)
str(round(average/100, 2)).split(".")
min_secs, hund=f"{(average/100):.2f}".split(".")
min_secs=int(min_secs)
min=min_secs//60
min_secs=min_secs-min*60
min,min_secs,hund
#ex_time=str(min)+":"+str(min_secs)+ "."+ hund
ex_time=f"{min}:{min_secs:0>2}.{hund}"
return swimmer, age, distance, stroke, times, ex_time, time_in_hun
#this function will create a web page with a bar chart representing the swim times, i.e. we do page=header+body+footer and then save it to charts folder
def produce_bar_chart(fn, location=CHARTS):
"""Given the name of a swimmer's file, produce a HTML/SVG-based bar chart.
Save the chart to the CHARTS folder. Return the path to the bar chart file.
"""
swimmer, age, distance, stroke, times, average, converts = read_swim_data(fn)
from_max = max(converts)
times.reverse()
converts.reverse()
title = f"{swimmer} (Under {age}) {distance} {stroke}"
header = f"""
{title}
{title}"""
body = ""
for n, t in enumerate(times):
bar_width = hfpy_utils.convert2range(converts[n], 0, from_max, 0, 350)
body = body + f"""
{t}
"""
footer = f"""
Average time: {average}
"""
page = header + body + footer
save_to = f"{location}{fn.removesuffix('.txt')}.html"
with open(save_to, "w") as sf:
print(page, file=sf)
return save_to
from flask import Flask, session, render_template, request, send_file
import os
import swimclub
app = Flask(__name__)
app.secret_key = "You will never guess..."
@app.get("/")
def index():
return render_template(
"index.html",
title="Welcome to the Swimclub system",
)
def populate_data():
if "swimmers" not in session:
swim_files = os.listdir(swimclub.FOLDER)
swim_files.remove(".DS_Store")
session["swimmers"] = {}
for file in swim_files:
name, *_ = swimclub.read_swim_data(file)
if name not in session["swimmers"]:
session["swimmers"][name] = []
session["swimmers"][name].append(file)
@app.get("/swimmers")
def display_swimmers():
populate_data()
return render_template(
"select.html",
title="Select a swimmer",
url="/showfiles",
select_id="swimmer",
data=sorted(session["swimmers"]),
)
@app.post("/showfiles")
def display_swimmers_files():
populate_data()
name = request.form["swimmer"]
return render_template(
"select.html",
title="Select an event",
url="/showbarchart",
select_id="file",
data=session["swimmers"][name],
)
@app.post("/showbarchart")
def show_bar_chart():
file_id = request.form["file"]
location = swimclub.produce_bar_chart(file_id, "templates/")
return render_template(location.split("/")[-1])
if __name__ == "__main__":
app.run(debug=True)
я также прикрепил изображение каталога.
введите описание изображения здесь
новичок в этом деле, пожалуйста, помогите!
я прикрепил модуль swimclub и модуль app.py, может кто-нибудь сказать мне, где я ошибаюсь? я даже добавил необязательный параметр в функцию Produce_bar_chart, но безуспешно?
Пытаюсь создать гистограммы, а затем отобразить их на веб-странице, но постоянно сталкиваюсь с вышеуказанной ошибкой.
введите здесь описание изображения
ниже приведены все необходимые функции
swimclub.py [code]import os import hfpy_utils FOLDER="swimdata/" CHARTS="charts/"
def read_swim_data(filename):
#unpacks the filename into different variales and removes the .txt suffix swimmer, age, distance, stroke = filename.removesuffix(".txt").split("-")
#gets the path, opens the file, reads the lines, and splits the first line into a list of times with open(FOLDER + filename) as file: lines = file.readlines() times=lines[0].strip().split(",") #print(times)
time_in_hun=[]
for f in times: if ":" in f: minutes, rest= f.split(":") seconds, hundredths= rest.split(".") else: minutes=0 seconds, hundredths= f.split(".") total_time=(int(minutes)*60*100 + int(seconds)*100+ int(hundredths)) time_in_hun.append(total_time)
#this function will create a web page with a bar chart representing the swim times, i.e. we do page=header+body+footer and then save it to charts folder def produce_bar_chart(fn, location=CHARTS): """Given the name of a swimmer's file, produce a HTML/SVG-based bar chart.
Save the chart to the CHARTS folder. Return the path to the bar chart file. """ swimmer, age, distance, stroke, times, average, converts = read_swim_data(fn) from_max = max(converts) times.reverse() converts.reverse() title = f"{swimmer} (Under {age}) {distance} {stroke}" header = f"""
{title}
{title}""" body = "" for n, t in enumerate(times): bar_width = hfpy_utils.convert2range(converts[n], 0, from_max, 0, 350) body = body + f"""
{t} """ footer = f""" Average time: {average}
""" page = header + body + footer save_to = f"{location}{fn.removesuffix('.txt')}.html" with open(save_to, "w") as sf: print(page, file=sf)
app = Flask(__name__) app.secret_key = "You will never guess..."
@app.get("/") def index(): return render_template( "index.html", title="Welcome to the Swimclub system", )
def populate_data(): if "swimmers" not in session: swim_files = os.listdir(swimclub.FOLDER) swim_files.remove(".DS_Store") session["swimmers"] = {} for file in swim_files: name, *_ = swimclub.read_swim_data(file) if name not in session["swimmers"]: session["swimmers"][name] = [] session["swimmers"][name].append(file)
if __name__ == "__main__": app.run(debug=True) [/code] я также прикрепил изображение каталога.
введите описание изображения здесь
новичок в этом деле, пожалуйста, помогите!🙌 я прикрепил модуль swimclub и модуль app.py, может кто-нибудь сказать мне, где я ошибаюсь? я даже добавил необязательный параметр в функцию Produce_bar_chart, но безуспешно?