I'm relatively new to Python and Flask. I've been trying to create a web application that reads data readings from a .txt file and plots them onto a matplotlib plot. In this web-app, I have a front page with 3 buttons. These buttons redirect to different routes with functions that read data and plot them onto a matplotlib plot. The web-app works perfectly only for the first time I go to either of these routes. After that nothing loads anymore. I guess I have an infinite loop of some sort but I can't figure it out. Also, after the website gets stuck the Python process starts consuming more resources.
The problem persists only when I open this route on the web-app:
@app.route("/temperature/")
This loads without problems on the web-page, but only for one time and the whole web-app gets stuck and I cannot access any of the other routes either.
Thanks in advance!
EDIT 1 - Whole code below
cloudapp.py (Python sourcecode that runs Flask and the functions)
from flask import Flask
from flask import render_template
from flask import request
import numpy as np
import matplotlib.pyplot as plt, mpld3
from datetime import datetime
app = Flask(__name__, template_folder='C:\Users\Valtteri\Desktop\cloudapp\Templates\HTML')
global all_lines
@app.route("/")
def frontpage():
return render_template('frontpage.html')
@app.route("/temperature/")
def temperature():
f = open('C:/Email/file.txt', 'r')
cpt = 0 # Line amount value
all_lines = [] # List that has every Nth value
for line in f:
cpt += 1 # Goes through every line and adds 1 to the counter
# How often values are plotted (every Nth value)
if cpt%100 == 0:
all_lines.append(line) # When 30th line is counted, add that line to all_lines[] list
if cpt == 500: # How many values are plotted (counts from first)
break
dates = [str(line.split(';')[0]) for line in all_lines]
date = [datetime.strptime(x,'%Y.%m.%d_%H:%M') for x in dates]
y = [float(line.split(';')[1]) for line in all_lines]
z = [float(line.split()[2]) for line in all_lines]
fig, ax = plt.subplots()
ax.plot_date(date, y, 'r-')
f.close()
return mpld3.fig_to_html(fig)
if __name__ == "__main__":
app.run()
frontpage.html (HTML template in folder ..\templates\html)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Envic Oy Cloud</title>
</head>
<body>
<div class="headers">
<h1>Web-Application</h1>
<h2> Version 0.0.1 </h2>
</div>
<div class="buttons">
<h3 class="buttonheader">Logger 1</h3>
<a class="templink" href="http://127.0.0.1:5000/temperature/" target="_blank"> Check temperature </a>
</body>
</html>
I use Bash on windows to run the code with
export FLASK_APP=myCloud.py
flask run
EDIT 2
I tried to solve the issue for a long time, but couldn't find a solution. It has something to do with Flask/mpld3 compatibility for me. I made the very same web app, but this time using a simple pyramid WSGI. I can now refresh the plot as many times and redirect myself into any view without the server hanging. I'll still leave the post unsolved, because I would still like to use Flask. I will continue my research too. Here is the pyramid version that works for me:
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
import numpy as np
import matplotlib.pyplot as plt, mpld3
from datetime import datetime
def hello_world(request):
return Response('<h1>Testing the Pyramid version!</h1><a href="http://localhost:8888/second_view">Check temperature</a>')
def second_view(request):
with open('C:/Email/file.txt') as f:
cpt = 0 # Line amount value
all_lines = [] # List that has every Nth value
for line in f:
cpt += 1 # Goes through every line and adds 1 to the counter
# How often values are plotted (every Nth value)
if cpt%100 == 0:
all_lines.append(line) # When 30th line is counted, add that line to all_lines[] list
if cpt == 500: # How many values are plotted (counts from first)
break
dates = [str(line.split(';')[0]) for line in all_lines]
date = [datetime.strptime(x,'%Y.%m.%d_%H:%M') for x in dates]
y = [float(line.split(';')[1]) for line in all_lines]
z = [float(line.split()[2]) for line in all_lines]
plt.figure(figsize=(10,5))
plt.title('Humidity', fontsize=15)
plt.ylabel('Humidity RH', fontsize=15)
fig = plt.figure()
plot = plt.plot_date(date, z, 'b-')
myfig = mpld3.fig_to_html(fig, template_type='simple')
return Response(myfig)
if __name__ == '__main__':
config = Configurator()
config.add_route('hello_world', '/hello_world')
config.add_route('second_view', '/second_view')
config.add_view(hello_world, route_name='hello_world')
config.add_view(second_view, route_name='second_view')
app = config.make_wsgi_app()
server = make_server('', 8888, app)
server.serve_forever()