Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

javascript - Getting Flask Python Information to Chart.JS

I've got a program with a python backend using flask and I'm uploading a CSV file to create a graph with Chart.JS. I'm extremely unfamiliar with this program and I'm kinda stuck at the moment. I have a basic graph being created right now but I'm not sure how to get the values from python to use them on chart.js. When I tried inputting {{dataxarray}} to data on the chart it just breaks the chart and doesn't display anything and I'm not quite sure how to fix this. Any help would be much appreciated.

Views.py

 
@app.route('/', methods=["GET", "POST"])
def index():
    data = []
    if request.method == 'POST':
        if request.files:
            uploaded_file = request.files['filename']
            filepath = os.path.join(app.config['FILE_UPLOADS'], uploaded_file.filename)
            uploaded_file.save(filepath)
            with open(filepath) as file:
                csv_file = csv.reader(file)
                for row in csv_file:
                    data.append(row)
            data = pd.DataFrame(data[1:], columns=data[0])
            if len(data.columns) >=3:
                error_msg = 'Error please select a CSV with two columns'
                return error_msg

            d_list = list(data.columns.values)

            def get_x_label():
                x_label = d_list[0]
                return x_label
            def get_y_label():
                y_label = d_list[1]
                return y_label
            def get_title():
                new_file = uploaded_file.filename.replace(".csv", "")
                return new_file
            def get_x_array():
                d_list = list(data.columns.values)
                x_label = d_list[0]
                data_x_array = np.array(data[x_label])
                return data_x_array
            def get_y_array():
                d_list = list(data.columns.values)
                y_label = d_list[1]
                data_y_array = np.array(data[y_label])
                return data_y_array

            return render_template('index.html', datayarray=get_y_array(), dataxarray=get_x_array(), dataframe=data, x_label=get_x_label(), y_label=get_y_label(), chart_title=get_title(), tables=[data.to_html(classes='data')], titles=str(data.iloc[0]), header=False, index=False, index_names=False)
    return render_template('index.html', data=data)


@app.route('/help')
def help():
    return render_template('help.html')

app.config['FILE_UPLOADS'] = "C:\Users\Zachary\Documents\VSCode_Projects\monday_webapp\app\static\file\uploads"

Index.html

{% extends "base.html" %}
{% block title %}Home{% endblock %}
{% block body %}

<div class="background">
    <h1 style='text-align: center'>Zach's Web Application</h1>
    <br>
    <br>
    <br>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"></script>
    <script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/Chart.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://dl.dropbox.com/s/iyrrn20zt5za9ma/styles.css"/>
    <script>
        $(document).ready(function(){
            $('table').DataTable();
            $("#form_button").on('click', function(e) {
                    e.preventDefault();
                    validateDropDown();
                });
                var ctx = document.getElementById('myChart').getContext('2d');
            var myChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
                    datasets: [{
                        label: '# of Votes',
                        data: "[12, 19, 3, 5, 2, 3]",
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.2)',
                            'rgba(54, 162, 235, 0.2)',
                            'rgba(255, 206, 86, 0.2)',
                            'rgba(75, 192, 192, 0.2)',
                            'rgba(153, 102, 255, 0.2)',
                            'rgba(255, 159, 64, 0.2)'
                        ],
                        borderColor: [
                            'rgba(255, 99, 132, 1)',
                            'rgba(54, 162, 235, 1)',
                            'rgba(255, 206, 86, 1)',
                            'rgba(75, 192, 192, 1)',
                            'rgba(153, 102, 255, 1)',
                            'rgba(255, 159, 64, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero: true
                            }
                        }]
                    }
                }
            });

        } );
        function validateDropDown() {
                var ddl = document.getElementById('ddl');
                if(ddl.selectedIndex == 0 || ddl.options[ddl.selectedIndex].value == -1) {
                    alert('Please select a valid option!');
                    return false;
                }
                if(ddl.selectedIndex == 1){
                    $('#hidden_data').removeClass('hidden');
                }
                if(ddl.selectedIndex == 2){
                    $('#hidden_data').removeClass('hidden');

                }
                if(ddl.selectedIndex == 3){
                    $('#hidden_data').removeClass('hidden');

                }
                if(ddl.selectedIndex == 4){
                    $('#hidden_data').removeClass('hidden');

                }
                return true;
            }

    </script>
</div>
<div>
    <p class="lead">Select Option from dropdown window</p>
</div>
<div>
    <form id='form_id' onsubmit="return validateDropDown('ddl');">
        <select id="ddl">
            <option value="-1">----- Please Select -----</option>
            <option>Single Line Graph</option>
            <option>Multiple Line Graph</option>
            <option>Single Bar Graph</option>
            <option>Stacked Bar Graph</option>
        </select>
        <br>
        <input id='form_button' type="submit" />
    </form>
</div>
<br>
<div>
    <form id='hidden_data' class='hidden' method="POST" enctype="multipart/form-data" action="/">
        <input class='background' type="file" id="myFile" name="filename" accept=".csv">
        <input id='renderButton' type="submit">
    </form>
    </div>
</div>
<br>
<br>
<div id="div_table">
    {% for table in tables %}
            {{ table|safe }}
    {% endfor %}
    {{ error_msg }}
</div>
<div>
    <canvas id="myChart" width="100" height="100"></canvas>
</div>
<div>

{% endblock %}
question from:https://stackoverflow.com/questions/66051187/getting-flask-python-information-to-chart-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...