Hear is my code:
from flask import Flask
from flask import Markup
from flask import Flask
from flask import render_template
app = Flask(__name__)
#app.route("/")
def chart():
labels = ["2009-Q1","2009-Q2","2009-Q3","2009-Q4","2009-Q1","2009-Q2","2009-Q3","2009-Q4","2009-Q1","2009-Q2","2009-Q3","2009-Q4"]
values = [9,6,6,10,9,7,5,4,10,6,10,8]
return render_template('chart.html', values=values, labels=labels)
#app.route("/chart")
def chart():
labels = ["2009-Q1","2009-Q2","2009-Q3","2009-Q4","2009-Q1","2009-Q2","2009-Q3","2009-Q4","2009-Q1","2009-Q2","2009-Q3","2009-Q4"]
values = [9,6,6,10,9,7,5,4,10,6,10,8]
return render_template('chart.html', values=values, labels=labels)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5001)
The first #app.route("/") works correctly the second does not disappear any Chart like the first one. it disappears just some text of HTML. Any one can help?
First, you don't need to import Flask twice so you can delete one line of
from flask import Flask
The reason it's not working is because you defined two of the same functions 'chart()'. There also seems to be something wrong with the name 'chart' as a route, if you change that, it should be working.
Related
I am working on a Flask application that uses multiple Dash dashboards. I've been able to set up a multi-page Dash application in Flask. This required a lot of extra steps to do so. I am using a Blueprint, as well as some other atypical steps for a Dash application.
The problem I am trying to replicate in this dummy example (see below) is how to properly log errors in a callback when dash is being used within Flask. If I were to strip out some of the Flask parts to this application, the debug environment in Dash will catch the callback error (test_me). Currently, I have not found a solution to correctly trigger errors when I am embedding a Dash application within Flask.
I have tried doing try...Except around parts of the code, as well as tinkering with the .enable_dev_tools() to no avail. It seems like putting the callbacks within a function is the crux of why errors are not being propagated as one would expect. I can explain why the code has to be structured this way.
I am using dash = 2.0.0 and flask = 2.0.2. This is being run in a Conda environment that is using Python 3.9.7.
I looked around googling and some other questions on SO but could not find something helpful enough. Please let me know if my example is not reproducible or if I need more information.
import dash
from dash import html, dcc
import pandas as pd
from werkzeug.serving import run_simple
from flask import (Flask, Blueprint)
server_bp = Blueprint('main', __name__)
bottom_thing = html.Div(
[dcc.Dropdown(id='filter',options = [{'label':'temp','value':'temp'},
{'label':'not_temp','value':'not_temp'}],
value = 'temp'),
html.H6(id = 'made-up-text',children = [])]
)
main_page = html.Div(children = [
html.H1(children = 'Dash Example'),
bottom_thing
])
def dumb_function(x = 1):
return x
##NOTE: This should fail as I am passing an extra argument to it.
def generate_callbacks(app):
#app.callback(dash.dependencies.Output('made-up-text','children'),
dash.dependencies.Input('filter','value'))
def test_me(filter_val):
dumb_function(x=100, y = 100)
if filter_val == 'temp':
return 'This is a temp string'
return 'This is not a temp string'
return app
def create_layout(app:dash.Dash, main_dash_path = '/'):
'''
Returns the view for a specific url. Note that the pathnames must match
the navbar defined elsewhere.
Parameters: pathname (str). Pathname is passed through via a callback.
not explicitly passed
Returns: A view which is a html.Div object
'''
# Update app layout
app.layout = html.Div([
dcc.Location(id='url', refresh=False),
html.Div(id='page-content')
])
#Add path names for the particular view.
#app.callback(dash.dependencies.Output('page-content', 'children'),
[dash.dependencies.Input('url','pathname')])
def display_page(pathname):
'''Returns the view for a specific url.'''
if pathname == main_dash_path:
return main_page
callbacks = generate_callbacks(app)
return app.layout
##Configure the various layouts here
def register_dashapps(app: Flask, title:str, url_pathname = '/'):
dashapp = dash.Dash(__name__,
server=app,
url_base_pathname=url_pathname)
with app.app_context():
dashapp.title = title
dashapp.layout = create_layout(dashapp)
##NOTE: This is only for development
dashapp.enable_dev_tools(debug=True)
def register_blueprints(server):
server.register_blueprint(server_bp)
def create_app():
server = Flask(__name__)
register_dashapps(server, title = 'wee')
register_blueprints(server)
return server
if __name__ == '__main__':
server = create_app()
run_simple('127.1.1.1', 1111, server, use_reloader=True, use_debugger=True)
import flask
import sentimentanalyzer
app: object = flask
#app.route("/")
def default() :
return "Hello world>>!!"``
#app.route("/predictsentiment/<query>",method=['GET'])
def predict(query):
sentiment = sentimentanalyzer.returnSentiment(query)
return flask.jsonify(sentiment)
if __name__ == "__main__":
app.run()
You need to import Flask class from flask module.
from flask import Flask
import sentimentanalyzer
app = Flask(__name__)
#app.route("/")
def default() :
return "Hello world>>!!"
#app.route("/predictsentiment/<query>",methods=['GET'])
def predict(query):
sentiment = sentimentanalyzer.returnSentiment(query)
return flask.jsonify(sentiment)
if __name__ == '__main__':
app.run()
I see you have not found a solution yet.
from flask import Flask
import sentimentanalyzer
app = Flask(__name__)
#app.route("/")
def default() :
return "Hello world>>!!"
#app.route("/predictsentiment/<query>",methods=['GET'])
def predict(query):
sentiment = sentimentanalyzer.returnSentiment(query)
return flask.jsonify(sentiment)
if __name__ == '__main__':
app.run()
Though the above code is correct, your error may be the initialization or the structure of the app. Please post the structure.
init.py needs to be put in a directory and the directory is called.
Try renaming your init.py to app.py, should solve the error.
As a reference the Quickstart docs here: https://flask.palletsprojects.com/en/1.1.x/quickstart/
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello, World!'
You need to create an object from the Flask class to get started.
And methods needs to be plural. (ref: https://flask.palletsprojects.com/en/1.1.x/quickstart/#http-methods)
Not relevant tot the question the default route has invalid syntax with the double backticks resulting in:
File "/home/tom/tmp/test.py", line 8
return "Hello world>>!!"``
^
SyntaxError: invalid syntax
Regards,
Tom
You need to import the flask class from the flask module. Check how to make minimal application here
import flask
import sentimentanalyzer
app: flask.Flask = flask.Flask(__name__)
#app.route("/")
def default() :
return "Hello world>>!!"
#app.route("/predictsentiment/<query>")
def predict(query):
sentiment = sentimentanalyzer.returnSentiment(query)
return flask.jsonify(sentiment)
if _name_== " main ":
app.run()
A brief introduction to the directory structure is as follows:
__init__.py contain the application factory.
page.py
from app import app
# a simple page that says hello
#app.route('/hello')
def hello():
return 'Hello, World!'
app.py
from flaskr import create_app
app = create_app()
if __name__ == '__main__':
app.run()
When I start the server and go to the '/hello', it says 404.
What's the problem?
Here is a short solution which should run.
page.py
from flaskr import app
#app.route('/hello')
def hello():
return 'Hello'
__index__.py
from flask import Flask
app = Flask(__name__)
from flaskr import page
app.py
from flaskr import app
To run this you just need to define a Environment Variable on the Commandline like this:
export FLASK_APP=microblog.py
And then run it with
flask run
The way you have structured your code is not right. That's the reason you are not able to access your "/hello" API.
Let's assume that you run the app.py file. In this case, you haven't imported page.py right? So, how will the app.py know that there is a route defined in page.py?
Alternatively, let's assume you run page.py. In this case, when you do an "from app import app" , the main definition does not get executed. Here too, the route will now be present, but the app will not be run, thereby you will be unable to access your API.
The simplest solution would be to combine the contents of app.py and page.py into a single file.
I have two Python scripts:
tnk_flask.py: This creates a flask webserver and two pages.
pitoka.py: this creates a random number.
My goal is the following:
When I run pitonka.py, I always generate a random number which I'd like to pass to tnb_flask.py, but, after refreshing those pages nothing changes.
What can be the mistake?
tnb_flask.py:
from flask import Flask # ezzel importáljuk ki
from pitonka import *
app = Flask(__name__)
#app.route('/')
def index():
denis = alma()
return str(denis)
#app.route('/tuna')
def index__():
return str(numbi)
if __name__ == "__main__":
app.run(debug=True)
pitonka.py:
from flask import Flask
# import tnb_flask
import random
numbi = random.randint(10, 100)
print(numbi)
def alma():
return numbi + 17
In pitonka.py you are assigning the random number to a variable. So it will only get the random variable once. Instead return the random number in the function.
def alma():
return random.randint(10, 100) + 17
You could serve static pages via flask and re-render them from templates in pitonka.py
I did everything according to the flask documentation, but I always get the error 404. I really don't get what I am doing wrong. Perhaps, someone can look at my code and give me a push in the direction of my mistake? It would be too generous, I am really stuck here for hours now and I am almost at the point to give up again. It is so frustrating.
my app:
import flask
app = flask.Flask(__name__)
def main():
register_blueprints()
app.run(debug=True)
def register_blueprints():
from pypi_org.views import home_views
from pypi_org.views import package_views
app.register_blueprint(package_views.blueprint)
app.register_blueprint(home_views.blueprint)
if __name__ == '__main__':
main()
my home_views.py file
import flask
import pypi_org.services.package_service as package_service
blueprint = flask.Blueprint('home', __name__, template_folder='templates')
#blueprint.route('/')
def index():
test_packages = package_service.get_latest_packages()
return flask.render_template('home/index.html', packages=test_packages)
#blueprint.route('/about')
def about():
return flask.render_template('home/about.html')
I found the answer to this in the 'final' github files provided for the course (see the link provided by OP), there's an addition of a couple lines in app.py:
if __name__ == '__main__':
main()
else:
register_blueprints()
Perhaps simplify app.py:
import flask
from pypi_org.views import home_views
from pypi_org.views import package_views
app = flask.Flask(__name__)
app.register_blueprint(package_views.blueprint)
app.register_blueprint(home_views.blueprint)
if __name__ == '__main__':
print (app.url_map)
app.run(debug=True)
Note the addition of the second last line prints all the URL routes to the terminal when you run the application, which helps for debugging.