Codementor Events

Building Datagrid for CRUD in Flask with pythonGrid

Published May 22, 2020Last updated Jun 16, 2020
Building Datagrid for CRUD in Flask with pythonGrid

pythonGrid is a new free open source library to create a fully working datagrid for CRUD (Create, Read, Update, & Delete) for Flask that connects to a relation database such as Postgres or MySql/MariaDB database.

It makes everyday datagrid tasks extremely easy. Standard functions like sorting, pagination, search, and CSV export are supported out-of-box without complicated programming.

pythonGrid does not require creating a separate data model for each database table.

It requires only two lines of code for a basic CRUD. 😄

mygrid = PythonGrid('SELECT * FROM TABLE_NAME', 'PRIMARY_KEY', 'TABLE_NAME')
return render_template('template.html', title='a page title', grid=mygrid)

Requirements

  • pythonGrid
  • Python 3.6
  • Flask
  • SQLAlchemy
  • MySQL or Postgres

Quick Start

A couple of quick-start options are available:

git clone https://github.com/pycr/pythongrid.git

Files included

Within the download you will see something like this:

├── LICENSE
├── README.md
├── app
│   ├── __init__.py
│   ├── data.py
│   ├── grid.py
│   ├── export.py
│   ├── routes.py
│   ├── static
│   └── templates
│       ├── 404.html
│       ├── base.html
│       ├── grid.html
│       └── index.html
├── sample
│   ├── sampledb_postgres.sql
│   ├── sampledb_mysql.sql
├── config.py
├── index.py
└── requirements.txt

pythonGrid has three main files in grid.py, data.py, and export.py in app folder.

  • grid.py is the main Python class that is responsible for creating the datagrid table. It's a high-level wrapper to jqGrid, a popular jQuery datagrid plugin, for rendering datagrid in the browser.
  • data.py is a Python class that returns the data via AJAX to populate the grid from a database.
  • export.py is responsible for handling the data export.
  • static contains all of the client side Javascript and CSS files used for rendering.

Creating the Database

Find the sample database in the folder sampledb. Using your favorite MySQL os Postgres client (more database supports are coming).

  1. Create a new database named sampledb
  2. Run the sample SQL script.

Install Python

First of all, if you don't have Python installed on your computer, download and install it from the Python official website now.
To make sure your Python is functional, type python3 in a terminal window, or just python if that does not work. Here is what you should expect to see:

Python 3.6.3 (v3.6.3:2c5fed86e0, Oct  3 2017, 00:32:08)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

Next, install the Flask framework.

Install Flask Framework via Virtual Environment

It is highly recommended to use Python virtual environment. A Python virtual environment is a self-contained separate copy of Python installation. Different applications can then use different virtual environments with a modified Python copy without worrying about system permissions.

The following command will create a virtual environment named venv stored in a directory, also called venv.

python3 -m venv venv

Activate the new virtual environment:

source venv/bin/activate

Now the terminal prompt is modified to include the name of the activated virtual environment

(venv) $ _

With a new virtual environment created and activated, finally, let's install dependents:

Install Dependents

pythonGrid uses SQLAlchemy to support different types of databases.

pip install -r requirements.txt

Configuration

Find file config.py, and set the database connection properties according to your environment. The demo uses MySQL database.

You can also use a socket to connect to your database without specifying a database hostname.

PYTHONGRID_DB_HOSTNAME = 'mysqldatabase.example.com'
PYTHONGRID_DB_NAME = 'sampledb'
PYTHONGRID_DB_USERNAME = 'root'
PYTHONGRID_DB_PASSWORD = 'root'
PYTHONGRID_DB_TYPE = 'mysql+pymysql'

For Postgres set database type to postgres+psycopg2

PYTHONGRID_DB_TYPE = 'postgres+psycopg2'

Initialize Grid

Flask uses view functions to handle the application routes. View functions are mapped to one or more route URLs so that Flask knows what logic to execute when a client requests a given URL such as "https://example.com/grid".

We have three view functions that need initialization.

index()

The file routes.py contains our def index() view functions associate with root URL /. This means that when a web browser requests the URL, Flask invokes this function and passes the return value of it back to the browser as a response.

Inside the function, it creates a new instance of the PythonGrid class and assigns this object to the local variable grid. Note orders is a table from our sample database sampledb.

grid = PythonGrid('SELECT * FROM orders', 'orderNumber', 'orders')

PythonGrid initializer shown above requires 3 parameters:

  1. A simple SQL SELECT statement
  2. The database table primary key
  3. The database table name

The view function pass the grid object into the rendered template from grid.html template.

return render_template('grid.html', title='GRID', grid=grid)

data()

Next, we need the data for the grid (thus the datagrid 😃
In the next view function data(), we create a new instance for PythonGridDbData class that is responsible for retrieve data from the database to populate our datagrid.

PythonGridDbData class requires only 1 parameter, which should be the same SQL SELECT statement used for PythonGrid class.

data = PythonGridDbData('SELECT * FROM orders')
return data.getData()

export()

Export function is almost identical to data function above except we need to use PythonGridDbExport to initiate a new instace for export class.

exp = PythonGridDbExport('SELECT * FROM orders')
return exp.export()

Hello, Grid

At this point, we can run our program with the command below.

flask run

It should give you a beautiful datagrid with data from orders table.
basiccrud.png


A List of Common Datagrid Functions

From the basic grid, we can add new functions such as changing title, adding search, and enabling export, set text align, etc., through simple function calls.

cap.png

grid.set_caption('Orders Table')

title.png

grid.set_col_title('orderNumber', 'Order #')
grid.set_col_hidden(['customerNumber, logTime, shippedDate, requiredDate'])

pagesize.png

grid.set_pagesize(20)
grid.set_dimension(800, 400)

export.png

grid.enable_search(True)

rownum.png

grid.enable_rownumbers(True)

pagecnt.png

grid.enable_pagecount(True)
grid.set_col_align('status', 'center')
grid.set_col_width('comments', 600)

csvexport.png

grid.enable_export()

See the list of complete pythonGrid documentation.

Please stay tuned for the second part of the step-by-step walkthrough for the rest of CRUD operations, including Add, Edit, and Delete! 😄

If you have any questions about this tutorial, feel free to comment below or reach out to me.

Discover and read more posts from pycr
get started
post commentsBe the first to share your opinion
Laxman V
a year ago

Hi, i m new to python & flask. This post is very helpful. Thank you. But, further i want to add a row/cell navigation link to another table. I mean once i click on a navigable cell, it should display more details of respective cell from other foreign table. please share code for it using pythongrids. Advance thanks.

pitS
3 years ago

Hi , I’m new in flask . Your post is very usefull. I need help - how to change your code to connect to sqlServer. In config.py I have connection: xSQLALCHEMY_DATABASE_URI = “mssql+pyodbc:///?odbc_connect=%s” % params
SQLALCHEMY_DATABASE_URI = xSQLALCHEMY_DATABASE_URI

next in init.py I have db=SQLAlchemy(app).

Now how to use it in your grid.py ?

Eber Velasquez
3 years ago

how can I get row values from grid view when a cell changes?

Show more replies