Created On: June 08, 2021, Last Updated On: June 08, 2021

Numpy Pandas Flask Datatables

Public

Numpy Pandas Flask Datatables

By Ozzie Ghani3 new


Source Code:  https://github.com/Ozzie6935/pandas_numpy_flask


Steps

# Prepare virtual environment
python3 -m venv venv
cd venv
source bin/activate

# Clone
git clone git@github.com:Ozzie6935/pandas_numpy_flask.git
# Install dependencies pip install --upgrade pip pip install -r requirements.txt # Run App python app.py


requirement.text

Flask==1.0.3
pandas
numpy


app.py

from flask import Flask, render_template, jsonify, url_for, Markup
from flask_wtf.csrf import CsrfProtect
import pandas as pd
import numpy as np
import json

app = Flask(__name__)

app.config['SECRET_KEY'] = 'thisissecret'

CsrfProtect(app)

@app.route('/')
def index():
    return Markup("""<a href="/example1">/example1</a> (with pandas df .to_html())<br>
              <a href="/example2">/example2</a> (with jinja parsing into custom html table)<br>
              <a href="/example3">/example3</a> (with column names)<br>
           """)


@app.route('/example1')
def example1():
    x = pd.DataFrame(np.random.randn(20, 6))
    data = x.to_html(table_id="sample_data")
    return render_template("index_np.html", data=data)


@app.route('/example2')
def example2():
    # https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_json.html
    x = pd.DataFrame(np.random.randn(20, 6))
    results = x.to_json(orient="index")  # other orients to try ['split', 'records', 'index', 'columns', 'values', 'table']

    parsed = json.loads(results)
    # return jsonify(parsed)
    return render_template("index_np2.html", data=parsed)

@app.route('/example3')
def example3():
    # https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_json.html
    """
    with Column Names
    """
    x = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
    data = x.to_html(table_id="sample_data")
    # return jsonify(data)
    return render_template("index_np.html", data=data)


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


index_np.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="{% block meta_description %}{% endblock %}">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <meta name="author" content="Osman Ghani">


  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.25/css/dataTables.bootstrap4.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
  <script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.25/js/dataTables.bootstrap4.min.js"></script>
  <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/bootstrap-editable.css')}}">
  <script src="{{ url_for('static', filename='js/bootstrap-editable.js')}}"></script>

  <script type="text/javascript">
    var csrftoken = $('meta[name=csrf-token]').attr('content');

    $.ajaxSetup({
      beforeSend: function(xhr, settings) {
        if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type)) {
          xhr.setRequestHeader("X-CSRFToken", csrftoken)
        }
      }
    });
  </script>
</head>

<body>

  <div class="container">
    <div class="panel panel-default">
      <div class="panel-heading">DataTable</div>
      <div class="panel-body">
        <div class="table-responsive">
          <div class="header">
          </div>
          {% block content %}
          <div>
            {{data | safe}}
          </div>
          {% endblock %}
        </div>
      </div>
    </div>
  </div>
  </div>

  <br />
  <br />


</body>



<script type="text/javascript" language="javascript">
  $(document).ready(function() {
    var dataTable = $('#sample_data').DataTable();

  });
</script>

</html>


index_np2.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="{% block meta_description %}{% endblock %}">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <meta name="author" content="Osman Ghani">


  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.25/css/dataTables.bootstrap4.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
  <script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.25/js/dataTables.bootstrap4.min.js"></script>
  <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/bootstrap-editable.css')}}">
  <script src="{{ url_for('static', filename='js/bootstrap-editable.js')}}"></script>

  <script type="text/javascript">
    var csrftoken = $('meta[name=csrf-token]').attr('content');

    $.ajaxSetup({
      beforeSend: function(xhr, settings) {
        if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type)) {
          xhr.setRequestHeader("X-CSRFToken", csrftoken)
        }
      }
    });
  </script>
</head>

<body>

  <div class="container">
    <div class="panel panel-default">
      <div class="panel-heading">DataTable</div>
      <div class="panel-body">
        <div class="table-responsive">

          <!-- {% for rowNum, row in data.items() %}
          <pre>{{ row }}</pre>
          {% endfor %} -->

          <table id="sample_data" class="table table-striped table-bordered" style="width:100%">
            <thead>
              <tr>
                <th>Index</th>
                <th>Col1</th>
                <th>Col2</th>
                <th>Col3</th>
                <th>Col4</th>
                <th>Col5</th>
                <th>Col6</th>
              </tr>
            </thead>
            <tbody>
              {% for rowNum, row in data.items() %}
              <tr>
                <td data-pk="{{rowNum}}">{{rowNum}}</td>
                {% for k, v in row.items() %}
                <td data-name="{{k}}" class="name" data-type="text" data-pk="{{rowNum}}">{{v}}</td>
                {% endfor %}

              </tr>
              {% endfor %}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>


  <br />
  <br />


</body>



<script type="text/javascript" language="javascript">
  $(document).ready(function() {
    var dataTable = $('#sample_data').DataTable();

  });
</script>

</html>