-1

I am creating a Flask APP that use GoogleChart. I was able to make it work when the application was simple. Now, as the application is getting bigger, I am organizing the project using Blueprints. Mu problem is the following. In the simple application I create the app

from flask import Flask
from flask_googlecharts import GoogleCharts

app = Flask(__name__)
charts = GoogleCharts(app)

...

@app.route("/test_chart")
def test_chart():
    chart1 = ColumnChart("chart1",
                        ...)

    charts.register(chart1)

    return render_template('chart.html')

So, I create the app, initialize a instance of GoogleChart (chart). In the route function I create a ColumnChart and register in on the chart.

What I don't know to do is how to make this work using Blueprints as the app is created in a application factory like this.

from flask import Flask
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_googlecharts import GoogleCharts

bootstrap = Bootstrap()
moment = Moment()
charts = GoogleCharts()

def create_app():

    app = Flask(__name__)
    app.config['SECRET_KEY'] = '#$%4890+HjPç'

    bootstrap.init_app(app)
    moment.init_app(app)
    charts.init_app(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)
 
    return app

I don't know if the charts object should be created here. I am guessing this as the bootstrap and moment object are created (I am following example from other tutorials).

The question is. Is it correct create the charts object here. If so, how can use it inside a route function?

Dariva
  • 330
  • 2
  • 13

1 Answers1

0

I figured out how to do that.

In the application factory I should do like this

from flask import Flask from flask_bootstrap import Bootstrap from flask_moment import Moment from flask_googlecharts import GoogleCharts

bootstrap = Bootstrap() moment = Moment()

def create_app():

app = Flask(__name__)
app.config['SECRET_KEY'] = '#$%4890+HjPç'
with app.app_context():
    bootstrap.init_app(app)
    moment.init_app(app)
    app.charts = GoogleCharts()
    app.charts.init_app(app)

from .main import main as main_blueprint
app.register_blueprint(main_blueprint)

return app

and in the route function

from flask import Flask
from flask_googlecharts import GoogleCharts

app = Flask(__name__)
charts = GoogleCharts(app)

...

@app.route("/test_chart")
def test_chart():
    chart1 = ColumnChart("chart1",
                        ...)

    app.charts.register(chart1)

    return render_template('chart.html')

Sometimes we just need to ask the question to figured out the answer by ourselves.

Dariva
  • 330
  • 2
  • 13