Cara menggunakan python datagrid

I am writing an application using python.net. My objective is to fill a DataGrid programmatically with data. The code I am working in is below:

import clr
import System.Threading
System.Threading.Thread.CurrentThread.SetApartmentState(System.Threading.ApartmentState.STA)

clr.AddReference(r"wpf\PresentationFramework")
clr.AddReference(r"wpf\PresentationCore")
clr.AddReference("System.Xml")

from System.IO import StringReader
from System.Xml import XmlReader
from System.Windows.Markup import XamlReader, XamlWriter
from System.Windows import Window, Application, LogicalTreeHelper, MessageBox
from model import Model
from System.Windows.Media import Brushes
from random import random
from System.Windows.Controls import DataGridTextColumn, TextBox
from System.Windows.Data import Binding

xaml = """
<Window
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="panel1"
       Title="harpia.ml" Height="600" Width="800" Background="#FFFBFBFB">
    <Grid Margin="0,0,0,58">
        <DataGrid x:Name="dataGrid" IsReadOnly="True" Background="#FFAC5C5C" AutoGenerateColumns="False" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="206" Width="449">
            <DataGrid.Columns>

            </DataGrid.Columns>
          </DataGrid>
        <Button x:Name="refreshBtn" Content="Button" HorizontalAlignment="Left" Margin="10,221,0,0" VerticalAlignment="Top" Width="75"/>
        <Button x:Name="button1" Content="Button" HorizontalAlignment="Left" Margin="384,221,0,0" VerticalAlignment="Top" Width="75" RenderTransformOrigin="-0.033,-0.086"/>
        <Button x:Name="button2" Content="Button" HorizontalAlignment="Left" Height="21" Margin="10,266,0,-36" VerticalAlignment="Top" Width="75"/>
        <Button x:Name="button3" Content="Button" HorizontalAlignment="Left" Height="21" Margin="384,266,0,-36" VerticalAlignment="Top" Width="75"/>
        <TextBox x:Name="textBox1" HorizontalAlignment="Left" Height="21" Margin="117,266,0,-36" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="236"/>
    </Grid>
</Window>
"""

class Student(object):

    def __init__(self, name, branch, year):
            self.name = name
            self.branch = branch
            self.year = year
            print("A student object is created.")

    def print_details(self):
        """
        Prints the details of the student.
        """
        print("Name:", self.name)
        print("Branch:", self.branch)
        print("Year:", self.year)

def _button2_Click(s, e):
    textBox1 = LogicalTreeHelper.FindLogicalNode(win, 'textBox1')
    grid = LogicalTreeHelper.FindLogicalNode(win, 'dataGrid')

    col1 = DataGridTextColumn()
    col2 = DataGridTextColumn()
    col3 = DataGridTextColumn()

    grid.Columns.Add(col1)
    grid.Columns.Add(col2)
    grid.Columns.Add(col3)

    col1.Binding = Binding("name")
    col2.Binding = Binding("branch")
    col3.Binding = Binding("year")


    col1.Header = "name"
    col2.Header = "branch"
    col3.Header = "year"

    item = []

    item.append(Student("Andre", "Piratas", "1973"))
    item.append(Student("Andres", "Piratass", "1973s"))
    item.append(Student("Andre3", "Piratas3", "19733"))
    item.append(Student("Andre4", "Piratas4", "19734"))
    grid.ItemsSource = item
    textBox1.Text = str(grid.Items[0])

if __name__ == "__main__":
    xr = XmlReader.Create(StringReader(xaml))
    win = XamlReader.Load(xr)
    _button2 = LogicalTreeHelper.FindLogicalNode(win, 'button2')
    _button2.Click += _button2_Click
    Application().Run(win)

I was able to add the columns. However, the code is failing to add items(rows) to the DataGrid. Does anyone know how can I do this?

Published May 22, 2020Last updated Jun 16, 2020

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.

Cara menggunakan python datagrid

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:

  • Download the latest release
  • Clone the repo (recommended):
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

Cara menggunakan python 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.


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.

  • Datagrid Caption

grid.set_caption('Orders Table')
  • Column Title

grid.set_col_title('orderNumber', 'Order #')
  • Hide Columns

grid.set_col_hidden(['customerNumber, logTime, shippedDate, requiredDate'])
  • Set Page Size (# of rows to display per page)

grid.set_pagesize(20)
  • Set Datagrid Dimension (e.g. Width 800px, Height 400px)

grid.set_dimension(800, 400)

grid.enable_search(True)
  • Display Row Number

grid.enable_rownumbers(True)
  • Display Page Count on Toolbar

grid.enable_pagecount(True)
  • Column Text Align (e.g. Left, Center, or Right)

grid.set_col_align('status', 'center')
  • Set Column Width (e.g. 600px)

grid.set_col_width('comments', 600)
  • Enable CSV export

grid.enable_export()

See the list of complete pythonGrid documentation.

  • Demo
  • Project Homepage

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

Cara menggunakan python datagrid

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