Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在打开某个具有功能的路线后,烧瓶卡在装载位置_Python_Matplotlib_Flask_Web Applications_Mpld3 - Fatal编程技术网

Python 在打开某个具有功能的路线后,烧瓶卡在装载位置

Python 在打开某个具有功能的路线后,烧瓶卡在装载位置,python,matplotlib,flask,web-applications,mpld3,Python,Matplotlib,Flask,Web Applications,Mpld3,我对Python和Flask比较陌生。我一直在尝试创建一个web应用程序,从.txt文件中读取数据读数,并将其打印到matplotlib绘图上。在这个web应用程序中,我有一个带有3个按钮的首页。这些按钮通过读取数据并将其打印到matplotlib绘图的函数重定向到不同的管线。这个web应用程序只有在我第一次使用这两条路线时才能完美运行。在那之后,再也没有东西装载了。我想我有一个某种无限循环,但我想不出来。此外,在网站陷入困境后,Python进程开始消耗更多资源 仅当我在web应用程序上打开此路

我对Python和Flask比较陌生。我一直在尝试创建一个web应用程序,从.txt文件中读取数据读数,并将其打印到matplotlib绘图上。在这个web应用程序中,我有一个带有3个按钮的首页。这些按钮通过读取数据并将其打印到matplotlib绘图的函数重定向到不同的管线。这个web应用程序只有在我第一次使用这两条路线时才能完美运行。在那之后,再也没有东西装载了。我想我有一个某种无限循环,但我想不出来。此外,在网站陷入困境后,Python进程开始消耗更多资源

仅当我在web应用程序上打开此路由时,问题才会持续:

@app.route("/temperature/")
这在网页上加载没有问题,但只有一次,整个web应用程序被卡住,我也无法访问任何其他路径

提前谢谢

编辑1-下面的完整代码 cloudapp.py(运行Flask和函数的Python源代码)

frontpage.html(文件夹..\templates\html中的html模板)

编辑2 我花了很长时间试图解决这个问题,但找不到解决办法。对我来说,这与Flask/mpld3的兼容性有关。我制作了同样的web应用程序,但这次使用了一个简单的金字塔WSGI。我现在可以多次刷新绘图,并将自己重定向到任何视图,而无需挂起服务器。我仍然会留下这个帖子,因为我仍然想用烧瓶。我也会继续我的研究。以下是适合我的金字塔版本:

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()
从wsgiref.simple\u服务器导入make\u服务器
从pyramid.config导入配置程序
从pyramid.response导入响应
将numpy作为np导入
将matplotlib.pyplot作为plt、mpld3导入
从日期时间导入日期时间
def hello_world(请求):
返回响应('测试金字塔版本!')
def第二视图(请求):
将open('C:/Email/file.txt')作为f:
cpt=0#行金额值
所有_行=[]#具有每n个值的列表
对于f中的行:
cpt+=1#遍历每一行并向计数器添加1
#打印值的频率(每N个值)
如果cpt%100==0:
所有_行。追加(行)#计算第30行时,将该行添加到所有_行[]列表中
如果cpt==500:#绘制多少个值(从第一个开始计数)
打破
日期=[str(line.split(“;”)[0]),用于所有_行中的行]
date=[datetime.strTime(x,%Y.%m.%d_U8;%H:%m'),用于x个输入日期]
y=[float(line.split(“;”)[1]),用于所有_行中的行]
z=[float(line.split()[2]),用于所有_行中的行]
plt.图(figsize=(10,5))
打印标题(“湿度”,字体大小=15)
plt.ylabel('相对湿度',字体大小=15)
图=plt.图()
plot=plt.plot_日期(日期,z,'b-'))
myfig=mpld3.fig_to_html(fig,template_type='simple')
返回响应(myfig)
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
config=Configurator()
config.add_route('hello_world','/hello_world'))
config.add_route('second_view','/second_view'))
config.add_视图(hello_world,route_name='hello_world')
config.add_视图(第二个_视图,route_name='second_view')
app=config.make_wsgi_app()
服务器=制作服务器(“”,8888,应用程序)
服务器。永远为您服务()

以下是我的尝试。刷新或打开链接的新选项卡后,我没有发现服务器挂起的任何问题。但是,在我关闭服务器(
Ctrl+C
)后,控制台抛出了一些异常,表明mpld3或matplotlib打开了一些新线程。具体来说,异常是
运行时错误:主线程不在主循环中

我在谷歌上搜索了一下,发现了这个。那家伙建议用
fig\u来记录
json
。我尝试了他的解决方案,但还是有例外

现在,我将写下这两种方法,让您决定使用哪种方法。我不知道他们两个是否会为你工作。对于我的设置,尽管关闭服务器后出现异常,但应用程序运行正常

我还将使用您没有读取txt文件的示例。我已将debug设置为
True
,因此我可以确保在刷新图表或打开链接的新实例时正在处理GET请求

方法1(图到html)

app.py

方法2(图到图)

app.py

这是模板文件。我注意到你在
frontpage.html
中使用了一个静态链接,所以我用一个占位符替换了它,它允许Flask自动填充URL。您还有一个未关闭的
div
标记

frontpage.html


环境云
Web应用程序
版本0.0.1
记录器1
temperature.html(仅适用于第二次进近)


样本页
var figureId=“{{single_chart.id}}”;
var json01={{single_chart.json | safe}};
mpld3.绘制图(图ID,json01);

顺便说一句,我使用的是Python 3.5.4、Flask==0.12.2、matplotlib==2.1.2和mpld3==0.3。我使用Chrome版本67.0.3396.87进行了测试。

尝试取消识别您的
返回语句。我的直觉是,文件处理程序从不关闭文件,因此在后续读取中,您可能会在文件上有一个文件锁。感谢您的响应。尝试过,但不幸的是没有解决问题。我还尝试在return语句之前执行f.close(),但它仍然保持不变。我和你的猜测一样,是文件处理程序没有关闭,代码无法处理任何其他内容。问题似乎在于绘图本身(matplotlib或mpld3),请参阅我的原始文章中的编辑。Hmmm。。。我似乎无法复制你的问题。然而,在使用代码时,我注意到您有2
plt。
<!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>
export FLASK_APP=myCloud.py

flask run
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()
from flask import Flask
from flask import render_template
import matplotlib.pyplot as plt
import mpld3


app = Flask(__name__, template_folder='/path/to/templates')


@app.route("/")
@app.route("/index")
def index():
    return render_template('frontpage.html')


@app.route('/temperature')
def temperature():
    date = ([1, 2, 3, 4])
    y = ([1, 2, 3, 4])

    fig = plt.figure(figsize=(10, 5))
    plt.title('Temperature', fontsize=15)
    plt.ylabel('Temperature' + u'\u2103', fontsize=15)

    plt.plot(date, y, 'b-')
    plt.ylim([0, 40])

    myfig = mpld3.fig_to_html(fig, template_type='simple')

    plt.clf()  # clear figure
    plt.cla()  # clear axes
    plt.close('all')  # close all figures

    # Print as HTML
    return myfig


if __name__ == "__main__":
    app.run(debug=True)  # run on debug mode
from flask import Flask
from flask import render_template
import matplotlib.pyplot as plt
import mpld3
import json


app = Flask(__name__, template_folder='/path/to/templates')


@app.route("/")
@app.route("/index")
def index():
    return render_template('frontpage.html')


@app.route('/temperature')
def temperature():
    date = ([1, 2, 3, 4])
    y = ([1, 2, 3, 4])

    fig = plt.figure(figsize=(10, 5))
    plt.title('Temperature', fontsize=15)
    plt.ylabel('Temperature' + u'\u2103', fontsize=15)

    plt.plot(date, y, 'b-')
    plt.ylim([0, 40])

    single_chart = dict()
    single_chart['id'] = "temp_figure"
    single_chart['json'] = json.dumps(mpld3.fig_to_dict(fig))

    plt.clf()  # clear figure
    plt.cla()  # clear axes
    plt.close('all')  # close figure

    # Print as HTML
    return render_template('temperature.html', single_chart=single_chart)


if __name__ == "__main__":
    app.run(debug=True)  # run on debug mode
<!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"></div>
    <h3 class="buttonheader">Logger 1</h3>
    <a class="templink" href="{{ url_for('temperature') }}" target="_blank"> Check temperature </a>
  </body>
</html>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Sample Page</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
    <script type="text/javascript" src="http://mpld3.github.io/js/mpld3.v0.2.js"></script>
  </head>
  <body>
    <div id="{{single_chart.id}}">
  </div>
  <script type="text/javascript">
    var figureId = "{{single_chart.id}}";
    var json01 = {{single_chart.json|safe}};
    mpld3.draw_figure(figureId, json01);
  </script>
  </body>
</html>