What I am doing
Now I am building flask-based web application with Python and Plotly but I face a problem. Please send me some advice. I show you what I did. Though there are many endpoints (@app.route) in the script and also import other libraries, I intentionally omitted to focus the issue.
Environment
- Windows10 64bit
- Python v3.8.6
- Flask v2.1.2
- Plotly v5.7.0
- “set FLASK_APP=app.py” was configured.
- “set FLASK_ENV=development” was configured.
1st code
import plotly.express as px
from flask import Flask,render_template,url_for.redirect
app = Flask(__name__)
basedir = os.path.dirname(__file__)
@app.route("/")
def index():
BASE_HTML="""<!DOCTYPE html>
<html lang='ja'>
<head>
<meta charset='utf-8'>
<title>test</title>
</head>
<body>
"""
x_data = [list of numbers]
y_data = [list of numbers]
fig = px.scatter(x_data,y_data)
os.chdir(basedir+"static")
fig.write_image("test.png")
os.chdir("..")
BASE_HTML+="""
<div>
<img src='static\\test.png'>
</div>
</body>
</html>
"""
os.chdir(basedir+"templates")
fw = open("test.html",mode="w",encoding="utf-8")
fw.write(BASE_HTML)
fw.close()
os.chdir("..")
return render_template("test.html")
if __name__ == "__main__":
app.run(debug=True)
What happened when I execute the 1st code…
From the command line, start the script.
flask run
and then when I access the address (localhost:5000) on the Chome browser, following error message was shown.
RuntimeError: There is no current event loop in thread ‘Thread-1’.
2nd code
I changed the style to import plotly library.
import plotly <-- Intentionally changed to import library
from flask import Flask,render_template,url_for.redirect
app = Flask(__name__)
basedir = os.path.dirname(__file__)
@app.route("/")
def index():
BASE_HTML="""<!DOCTYPE html>
<html lang='ja'>
<head>
<meta charset='utf-8'>
<title>test</title>
</head>
<body>
"""
x_data = [list of numbers]
y_data = [list of numbers]
fig = plotly.express.scatter(x_data,y_data)
os.chdir(basedir+"static")
fig.write_image("test.png")
os.chdir("..")
BASE_HTML+="""
<div>
<img src='static\\test.png'>
</div>
</body>
</html>
"""
os.chdir(basedir+"templates")
fw = open("test.html",mode="w",encoding="utf-8")
fw.write(BASE_HTML)
fw.close()
os.chdir("..")
return render_template("test.html")
if __name__ == "__main__":
app.run(debug=True)
What happened when I execute the 2nd code…
As same way described above, when I started the script, following error message was shown.
AttributeError: module ‘plotly’ has no attribute ‘express’
How should I describe the script to avoid such errors ?