Chart.js在flask蓝图上不显示图表。

问题描述 投票:0回答:1

我在尝试使用flask蓝图显示chart.js中的图表时遇到了麻烦。当我的代码直接放在主应用程序文件中时,它工作得很好,我试着在我的蓝图中使用它,但它没有显示出来,我找不到代码中需要修改的地方。

app.py:

from flask import Flask, render_template

from views.trainings import training_blueprint
from views.workouts import workout_blueprint
from views.users import users_blueprint

app = Flask(__name__)
app.secret_key = 'jose'

@app.route('/')
def start():
    return 'hello'

@app.route("/simple_chart2")
def chart():
    legend = 'Monthly Data'
    labels = ["January", "February", "March", "April", "May", "June", "July", "August"]
    values = [10, 9, 8, 7, 6, 4, 7, 8]
    return render_template('chart.html', values=values, labels=labels, legend=legend)



app.register_blueprint(workout_blueprint, url_prefix='/workouts')
app.register_blueprint(users_blueprint, url_prefix='/users')
app.register_blueprint(training_blueprint, url_prefix='/trainings')


if __name__ == '__main__':
    app.run(debug=True)

chart.html:

<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Chart.js Example</title>
    <!-- import plugin script -->
    <script src='static/Chart.min.js'></script>
  </head>
  <body>
    <h1>Simple Line Chart</h1>
    <!-- bar chart canvas element -->
    <canvas id="myChart" width="600" height="400"></canvas>
    <p id="caption">The chart is displaying a simple line chart.</p>

    <script>
      // Global parameters:
      // do not resize the chart canvas when its container does (keep at 600x400px)
      Chart.defaults.global.responsive = false;

      // define the chart data
      var chartData = {
        labels : [{% for item in labels %}
                   "{{item}}",
                  {% endfor %}],
        datasets : [{
            label: '{{ legend }}',
            fill: true,
            lineTension: 0.1,
            backgroundColor: "rgba(75,192,192,0.4)",
            borderColor: "rgba(75,192,192,1)",
            borderCapStyle: 'butt',
            borderDash: [],
            borderDashOffset: 0.0,
            borderJoinStyle: 'miter',
            pointBorderColor: "rgba(75,192,192,1)",
            pointBackgroundColor: "#fff",
            pointBorderWidth: 1,
            pointHoverRadius: 5,
            pointHoverBackgroundColor: "rgba(75,192,192,1)",
            pointHoverBorderColor: "rgba(220,220,220,1)",
            pointHoverBorderWidth: 2,
            pointRadius: 1,
            pointHitRadius: 10,
            data : [{% for item in values %}
                      {{item}},
                    {% endfor %}],
            spanGaps: false
        }]
      }

      // get chart canvas
      var ctx = document.getElementById("myChart").getContext("2d");

      // create the chart using the chart canvas
      var myChart = new Chart(ctx, {
        type: 'line',
        data: chartData,
      });
    </script>

  </body>
</html>

trainings.py (最后一个函数):

from flask import Blueprint, render_template, request, session, url_for, Flask
from werkzeug.utils import redirect

from models.exercise import Excercise
from models.user import requires_login
from models.workout import Workout

training_blueprint = Blueprint('trainings', __name__)

@training_blueprint.route('/ex_index')
@requires_login
def ex_index():
    exercises = Excercise.user_exercises(session['email'])
    return render_template('trainings/ex_index.html', exercises=exercises)


@training_blueprint.route('/ex_index/new_exercise', methods = ['GET', 'POST'])
@requires_login
def new_exercise():
    if request.method == 'POST':
        name = request.form['name']
        exercise = Excercise(name, session['email'])
        exercise.save_to_mongo()
        return redirect(url_for('.ex_index'))
    return render_template('trainings/new_exercise.html')


@training_blueprint.route('/delete/<string:exercise_id>')
@requires_login
def delete_exercise(exercise_id):
    exercise = Excercise.get_by_id(exercise_id)
    if exercise.user_email == session['email']:
        exercise.remove_from_mongo()
    return redirect(url_for('.ex_index'))


@training_blueprint.route('/edit/<string:exercise_id>', methods=['GET', 'POST'])
@requires_login
def edit_exercise(exercise_id):

    if request.method == 'POST':
        new_name = request.form['new_name']
        exercise = Excercise.get_by_id(exercise_id)
        exercise.name = new_name
        exercise.save_to_mongo()

        return redirect(url_for('.ex_index'))
    return render_template('trainings/edit_exercise.html', exercise = Excercise.get_by_id(exercise_id))


@training_blueprint.route('/new_training', methods=['GET', 'POST'])
@requires_login
def new_training():
    exercises = Excercise.user_exercises(session['email'])

    if request.method == 'POST':
        new_workout_dict = {}
        for i in range(1,11):
            exercise_name = request.form[f'exercise_multiselect{i}']
            reps = request.form[f'Reps{i}']
            weight = request.form[f'Weight{i}']
            if exercise_name != 'None':
                new_workout_dict[exercise_name] = [reps, weight]
        new_workout = Workout(session['email'], new_workout_dict, request.form['date'])
        new_workout.save_to_mongo()
        return "ello"

    return render_template('trainings/new_training.html', exercises=exercises)


@training_blueprint.route('/chart', methods=['GET', 'POST'])
def chart():
    legend = 'Monthly Data'
    labels = ["January", "February", "March", "April", "May", "June", "July", "August"]
    values = [10, 9, 8, 7, 6, 4, 7, 8]

    return render_template('/chart.html', values=values, labels=labels, legend=legend)

python python-3.x flask chart.js
1个回答
0
投票

浏览器检查器有没有给你任何错误,帮助我们解答?

也许这与你的蓝图静态文件夹结构或HTML文件中的js url有关。

对于每个蓝图,你可以选择指定一个模板文件夹。

training_blueprint = Blueprint('training_blueprint', __name__,
                        template_folder='templates')

更多信息https:/hackersandslackers.comflask-blueprints。

在您的HTML中,您可以将

<script src='static/Chart.min.js'></script>

<script src="{{ url_for('static', filename='Chart.min.js') }}"></script>
© www.soinside.com 2019 - 2024. All rights reserved.