In Flask, it uses view functions to handle 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 two view functions that require initialization.
routes.py contains our
def index() view functions associate with root URL
/. This means that when a web browser requests the URL, Flask is going to invoke this function and pass 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 the sample database sampledb.
grid = PythonGrid('SELECT * FROM orders', 'orderNumber', 'orders')
PythonGrid initializer shown above requires 3 parameters, in the order from left to right:
- A simple SQL SELECT statement. Always include the primary key as one of the columns if not using the wildcard start(*).
- The name of the database table primary key.
- Name of the database table used in the SQL statement.
Do NOT include WHERE clause in 1st SQL SELECT statement. Instead use set_query_filter() method.
The view function passes the grid object into the rendered template from
return render_template('grid.html', title='GRID', grid=grid)
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.
It has required only 1 parameter, which should be the SAME sql select statement used for PythonGrid.
data = PythonGridDbData('SELECT * FROM orders')
At this point, we can run our program with the command below
It should give you a beautiful datagrid with data come from the table
Congrats! You just made your first grid.