Monday, June 21, 2021

Working on Basic Python C Extensions on Fedora Linux 34 (2)

 Relatively complicated sample based on

with  minor refactoring just to make things clear 


(.env) [boris@sever33fedora enhancePython]$ cat demo.h
unsigned long cfactorial_sum(char num_chars[]);
unsigned long ifactorial_sum(long nums[], int size);
unsigned long factorial(long n);

(.env) [boris@sever33fedora enhancePython]$ cat demolib.c
#include <stdio.h>
#include "demo.h"


unsigned long cfactorial_sum(char num_chars[]) {
    unsigned long fact_num;
    unsigned long sum = 0;

    for (int i = 0; num_chars[i]; i++) {
        int ith_num = num_chars[i] - '0';
        fact_num = factorial(ith_num);
        sum = sum + fact_num;
    }
    return sum;
}

unsigned long ifactorial_sum(long nums[], int size) {
    unsigned long fact_num;
    unsigned long sum = 0;
    for (int i = 0; i < size; i++) {
        fact_num = factorial(nums[i]);
        sum += fact_num;
    }
    return sum;
}

unsigned long factorial(long n) {
    if (n == 0)
        return 1;
    return (unsigned)n * factorial(n-1);
}

(.env) [boris@sever33fedora enhancePython]$ cat demo.c   
#include <Python.h>
#include <stdio.h>
#include "demo.h"
/*
Just to suppress warnings, which don't affect runtime phase
*/
#pragma GCC diagnostic ignored   "-Wincompatible-pointer-types"


// wrapper function for cfactorial_sum
static PyObject *DemoLib_cFactorialSum(PyObject *self, PyObject *args) {
    char *char_nums;
    if (!PyArg_ParseTuple(args, "s", &char_nums)) {
        return NULL;
    }

    unsigned long fact_sum;
    fact_sum = cfactorial_sum(char_nums);

    return Py_BuildValue("i", fact_sum);
}

// wrapper function for ifactorial_sum
static PyObject *DemoLib_iFactorialSum(PyObject *self, PyObject *args) {

/* 
  I believe this declaration is a cause of several
   "-Wincompatible-pointer-types" warnings,
   which are easy to see commenting #pragma GCC
   directive out
*/
    
    PyObject *lst; 

    if (!PyArg_ParseTuple(args, "O", &lst)) {
        return NULL;
    }

    int n = PyObject_Length(lst);
    if (n < 0) {
        return NULL;
    }

    long nums[n];
    for (int i = 0; i < n; i++) {
        PyLongObject *item = PyList_GetItem(lst, i);
        /* long num = PyLong_AsLong(item); */

        nums[i] = PyLong_AsLong(item);
    }

    unsigned long fact_sum;
    fact_sum = ifactorial_sum(nums, n);

    return Py_BuildValue("i", fact_sum);
}

// module's function table
static PyMethodDef DemoLib_FunctionsTable[] = {
    {
        "sfactorial_sum", // name exposed to Python
        DemoLib_cFactorialSum, // C wrapper function
        METH_VARARGS, // received variable args (but really just 1)
        "Calculates factorial sum from digits in string of numbers" // documentation
    }, {
        "ifactorial_sum", // name exposed to Python
        DemoLib_iFactorialSum, // C wrapper function
        METH_VARARGS, // received variable args (but really just 1)
        "Calculates factorial sum from list of ints" // documentation
    }, {
        NULL, NULL, 0, NULL
    }
};

// modules definition
static struct PyModuleDef DemoLib_Module = {
    PyModuleDef_HEAD_INIT,
    "demo",     // name of module exposed to Python
    "Demo Python wrapper for custom C extension library.", // module documentation
    -1,
    DemoLib_FunctionsTable
};

PyMODINIT_FUNC PyInit_demo(void) {
    return PyModule_Create(&DemoLib_Module);
}

(.env) [boris@sever33fedora enhancePython]$ cat setup.py
from setuptools import Extension, setup

module = Extension("demo",
                  sources=[
                    'demo.c',
                    'demolib.c'
                  ])
setup(name='demo',
     version='1.0',
     description='Python wrapper for custom C extension',
     ext_modules=[module])

(.env) [boris@sever33fedora enhancePython]$ cat MyProg.py    
import demo
print("Calling sfactorial_sum(\"1234567\") gives \n",demo.sfactorial_sum("1234567"))
print("Calling ifactorial_sum([1,2,3,4,5,6,7]) gives \n",\
       demo.ifactorial_sum([1,2,3,4,5,6,7]))

     
(.env) [boris@sever33fedora enhancePython]$ python setup.py
 install

running install
running bdist_egg
running egg_info
creating demo.egg-info
writing demo.egg-info/PKG-INFO
writing dependency_links to demo.egg-info/dependency_links.txt
writing top-level names to demo.egg-info/top_level.txt
writing manifest file 'demo.egg-info/SOURCES.txt'
reading manifest file 'demo.egg-info/SOURCES.txt'
writing manifest file 'demo.egg-info/SOURCES.txt'
installing library code to build/bdist.linux-x86_64/egg
running install_lib
running build_ext
building 'demo' extension
creating build
creating build/temp.linux-x86_64-3.9
gcc -pthread -Wno-unused-result -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/home/boris/enhancePython/.env/include -I/usr/include/python3.9 -c demo.c -o build/temp.linux-x86_64-3.9/demo.o
gcc -pthread -Wno-unused-result -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/home/boris/enhancePython/.env/include -I/usr/include/python3.9 -c demolib.c -o build/temp.linux-x86_64-3.9/demolib.o
creating build/lib.linux-x86_64-3.9
gcc -pthread -shared -Wl,-z,relro -Wl,--as-needed -Wl,-z,now -g -Wl,-z,relro -Wl,--as-needed -Wl,-z,now -g build/temp.linux-x86_64-3.9/demo.o build/temp.linux-x86_64-3.9/demolib.o -L/usr/lib64 -o build/lib.linux-x86_64-3.9/demo.cpython-39-x86_64-linux-gnu.so
creating build/bdist.linux-x86_64
creating build/bdist.linux-x86_64/egg
copying build/lib.linux-x86_64-3.9/demo.cpython-39-x86_64-linux-gnu.so -> build/bdist.linux-x86_64/egg
creating stub loader for demo.cpython-39-x86_64-linux-gnu.so
byte-compiling build/bdist.linux-x86_64/egg/demo.py to demo.cpython-39.pyc
creating build/bdist.linux-x86_64/egg/EGG-INFO
copying demo.egg-info/PKG-INFO -> build/bdist.linux-x86_64/egg/EGG-INFO
copying demo.egg-info/SOURCES.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying demo.egg-info/dependency_links.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying demo.egg-info/top_level.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
writing build/bdist.linux-x86_64/egg/EGG-INFO/native_libs.txt
zip_safe flag not set; analyzing archive contents...
__pycache__.demo.cpython-39: module references __file__
creating dist
creating 'dist/demo-1.0-py3.9-linux-x86_64.egg' and adding 'build/bdist.linux-x86_64/egg' to it
removing 'build/bdist.linux-x86_64/egg' (and everything under it)
Processing demo-1.0-py3.9-linux-x86_64.egg
removing '/home/boris/enhancePython/.env/lib/python3.9/site-packages/demo-1.0-py3.9-linux-x86_64.egg' (and everything under it)
creating /home/boris/enhancePython/.env/lib/python3.9/site-packages/demo-1.0-py3.9-linux-x86_64.egg
Extracting demo-1.0-py3.9-linux-x86_64.egg to /home/boris/enhancePython/.env/lib/python3.9/site-packages
demo 1.0 is already the active version in easy-install.pth

Installed /home/boris/enhancePython/.env/lib/python3.9/site-packages/demo-1.0-py3.9-linux-x86_64.egg
Processing dependencies for demo==1.0
Finished processing dependencies for demo==1.0

(.env) [boris@sever33fedora enhancePython]$ python MyProg.py
Calling sfactorial_sum("1234567") gives 
 5913
Calling ifactorial_sum([1,2,3,4,5,6,7]) gives 
 5913









































Sunday, June 20, 2021

Exercising to Create Basic Python C Extensions on Fedora Linux 34

According https://realpython.com/build-python-c-extension-module/

To write Python modules in C, you’ll need to use the Python API, which defines the various functions, macros, and variables that allow the Python interpreter to call your C code. All of these tools and more are collectively bundled in the <Python.h> header file.

This post follows up Creating Basic Python C Extensions - Tutorial  and does just one update required in static PyMethodDef myMethods[]  still having "METH_NOARGS" instead of "METH_VARARGS", 
what, actually, confuses  inexperienced learners, due to Python module runtime  failure with error "fib( ) expecting no arguments , but get (1)". As of now the only version available to follow :-
static PyMethodDef myMethods[] = {
    { "fib",fib, METH_NOARGS, "Prints Hello World" },
    { NULL, NULL, 0, NULL }
};
Should be
static PyMethodDef myMethods[] = {
    { "fib",fib,METH_VARARGS, "Fibonacci" },
    { NULL, NULL, 0, NULL }
};

Following below is working code follows up the link above, but  making  "code sample" easy to reproduce. Notice also that outside VENV you would have problems to run `python setup install`

(.env) [boris@fedora33server FIBONACHI]$ cat test.c

#include <Python.h>

int Cfib(int n)
{
    if (n < 2)
        return n;
    else
        return Cfib(n-1)+Cfib(n-2);
}

// Our Python binding to our C function
// This will take one and only one non-keyword argument
static PyObject *fib(PyObject* self, PyObject* args)
{
    // instantiate our `n` value
    int n;
    // if our `n` value
    if(!PyArg_ParseTuple(args, "i", &n))
        return NULL;
    // return our computed fib number
    

    int result = Cfib(n);
    return Py_BuildValue("i",result);
}

// Our Module's Function Definition struct
// We require this `NULL` to signal the end of our method
// definition
static PyMethodDef myMethods[] = {
    { "fib", fib, METH_VARARGS, "Calculate fibonacii value" },
    { NULL, NULL, 0, NULL }
};

// Our Module Definition struct
static struct PyModuleDef myModule = {
    PyModuleDef_HEAD_INIT,
    "myModule",
    "Test Module",
    -1,
    myMethods
};

// Initializes our module using our above struct
PyMODINIT_FUNC PyInit_myModule(void)
{
    return PyModule_Create(&myModule);
}

(.env) [boris@fedora33server FIBONACHI]$ cat setup.py
from distutils.core import setup, Extension
setup(name = 'myModule', version = '1.0',  \
   ext_modules = [Extension('myModule', ['test.c'])])

(.env) [boris@fedora33server FIBONACHI]$ python3 setup.py install

(.env) [boris@fedora33server FIBONACHI]$ cat MyProg.py
import myModule
a = int(input("Input number:"))
print(myModule.fib(a))

(.env) [boris@fedora33server FIBONACHI]$ python MyProg.py
Input number:11
89










PyCharm Project setup

Another Sample Factorial Recursion

(.env) [boris@fedora33server FACTORIAL]$ cat test.c
#include <Python.h>

    long factorial(int n)  
    {  
       if (n == 0)  
           return 1;  
       else  
          return(n * factorial(n-1));  
     }  

static PyObject *Factors(PyObject* self, PyObject* args)
{
    int n;
    if(!PyArg_ParseTuple(args, "i", &n))
        return NULL;
    int result = factorial(n);
    return Py_BuildValue("i",result);
}

// Our Module's Function Definition struct
// We require this `NULL` to signal the end of our method
// definition
static PyMethodDef myMethods[] = {
    { "Factors", Factors, METH_VARARGS, "Tracking factorial" },
    { NULL, NULL, 0, NULL }
};

// Our Module Definition struct
static struct PyModuleDef myModule = {
    PyModuleDef_HEAD_INIT,
    "myModule",
    "Test Module",
    -1,
    myMethods
};

// Initializes our module using our above struct
PyMODINIT_FUNC PyInit_myModule(void)
{
    return PyModule_Create(&myModule);
}

(.env) [boris@fedora33server FACTORIAL]$ cat setup.py 
from distutils.core import setup, Extension
setup(name = 'myModule', version = '1.0',  \
   ext_modules = [Extension('myModule', ['test.c'])])
   
(.env) [boris@fedora33server FACTORIAL]$ python setup.py install
running install
running build
running build_ext
building 'myModule' extension
creating build
creating build/temp.linux-x86_64-3.9
gcc -pthread -Wno-unused-result -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/home/boris/FACTORIAL/.env/include -I/usr/include/python3.9 -c test.c -o build/temp.linux-x86_64-3.9/test.o
creating build/lib.linux-x86_64-3.9
gcc -pthread -shared -Wl,-z,relro -Wl,--as-needed -Wl,-z,now -g -Wl,-z,relro -Wl,--as-needed -Wl,-z,now -g build/temp.linux-x86_64-3.9/test.o -L/usr/lib64 -o build/lib.linux-x86_64-3.9/myModule.cpython-39-x86_64-linux-gnu.so
running install_lib
copying build/lib.linux-x86_64-3.9/myModule.cpython-39-x86_64-linux-gnu.so -> /home/boris/FACTORIAL/.env/lib64/python3.9/site-packages
running install_egg_info
Removing /home/boris/FACTORIAL/.env/lib64/python3.9/site-packages/myModule-1.0-py3.9.egg-info
Writing /home/boris/FACTORIAL/.env/lib64/python3.9/site-packages/myModule-1.0-py3.9.egg-info

(.env) [boris@fedora33server FACTORIAL]$ cat MyModule.py
import myModule
a = int(input("Input number:"))
print(myModule.Factors(a))

(.env) [boris@fedora33server FACTORIAL]$ python MyModule.py
Input number:7
5040
(.env) [boris@fedora33server FACTORIAL]$ python MyModule.py
Input number:6
720
(.env) [boris@fedora33server FACTORIAL]$ python MyModule.py
Input number:5
120

**************************************************************
You might want to take a look at following more complicated sample then considered earlier
**************************************************************

Saturday, June 12, 2021

Setting up PyQT5 && "Mariadb 10.5 or MySQL 8.0.25" CRUD Application on Debian Bullseye/sid

Tuning remote connection of PyQT5 to Mariadb-Server as well as to MySQL seemed to me the most time consuming part of this small project. Obviously, the options for Mariadb and MySQL are mutually exclusive. Mariadb-Server seems to be native to Debian Bullseye due to setup MySQL 8.0.25 appears to be possible after purge preinstalled by default mariadb packages.

Tuning network configs on bare metal described in details utilizing `netstat -ant | grep 3306` output required to verify that  connection is established.

The very first time setup root account privileges to access the database server.

# mysql -u root -p

MariaDB [(none)]> GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.%' IDENTIFIED BY '*******' WITH GRANT OPTION;

Query OK, 0 rows affected (0.001 sec)

MariaDB [(none)]> FLUSH PRIVILEGES ;

MariaDB [(none)]> CREATE DATABASE db3 CHARACTER SET = 'utf8' COLLATE = 'utf8_bin';

MariaDB [db3]> CREATE TABLE persons ( id INT NOT NULL AUTO_INCREMENT,  name VARCHAR(30) CHARSET utf8,    spec VARCHAR(30) CHARSET utf8, ocenka INT,PRIMARY KEY (id) );

*****************************************************

VENV Setup for Mariadb Python Connection on Debian 11

 *****************************************************

  $ sudo apt install python3-venv

  $ python3 -m venv .env

  $ source .env/bin/activate

  $ sudo apt install libmariadb3 libmariadb-dev

  $ sudo apt install python3-dev

  $ pip3 install mariadb

  $ pip install PyQt5

Remote Connection to Mariadb on Debian Bullseye

Open port 3306

# firewall-cmd --zone=public --permanent --add-port=3306/tcp

1. Update /etc/mysql/mariadb.conf.d/50-server.cnf 

2. Update /etc/mysql/my.cnf

# cd /etc/mysql/mariadb.conf.d

# vi 50-server.cnf 

[server]

[mysqld]

# Comment out binding to localhost

#bind-address           = 127.0.0.1

save

# vi  /etc/mysql/my.cnf

    # add line to section below

    [mysqld]

    bind-address = 0.0.0.0

save

Restart mariadb service     

# systemctl restart mariadb

To get netstat on Debian ready to go 

$ sudo apt install net-tools 

When work on bare metal make sure that netstat reports a kind of :-

(.env) boris@boris-ms7c42:~/MARIADB$ netstat -ant  | grep 3306      

tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      

tcp        0      0 192.168.0.19:3306       192.168.0.14:33312      ESTABLISHED

Code of PyQT5 module

import sys

import mariadb
from PyQt5.QtWidgets import QTableWidget, QApplication, QMainWindow, QTableWidget
from PyQt5.QtWidgets import QTableWidgetItem, QWidget, QPushButton, QLineEdit
from PyQt5 import QtGui

class MyWidget(QWidget):

def __init__(self):

super().__init__()

self.con()

self.setGeometry(125, 125, 550, 650)
self.setWindowTitle('Scores List')
self.tb = Tb(self)
self.btn = QPushButton('Refresh View', self)
self.btn.resize(150, 40)
self.btn.move(350, 20)
self.btn.clicked.connect(self.upd)
self.idp = QLineEdit(self)
self.idp.resize(150, 40)
self.idp.move(350, 70)
self.idp.setReadOnly(True)
self.fio = QLineEdit(self)
self.fio.resize(150, 40)
self.fio.move(350, 120)
self.spec = QLineEdit(self)
self.spec.resize(150, 40)
self.spec.move(350, 180)
self.oce = QLineEdit(self)
self.oce.resize(150, 40)
self.oce.move(350, 230)
self.btn = QPushButton('Add row', self)
self.btn.resize(150, 40)
self.btn.move(350, 280)
self.btn.clicked.connect(self.ins)
self.btn = QPushButton('Update row', self)
self.btn.resize(150, 40)
self.btn.move(350, 330)
self.btn.clicked.connect(self.change)
self.btn = QPushButton('Delete row', self)
self.btn.resize(150, 40)
self.btn.move(350, 390)
self.btn.clicked.connect(self.dels)

# connect to datatabase
def con(self):
self.conn =mariadb.connect(user = "root",
password = "**********",
host = "192.168.0.26",
port = 3306,
database = "db3")

self.cur = self.conn.cursor()

def upd(self):
self.conn.commit()
self.tb.updt()
self.idp.setText('')
self.fio.setText('')
self.spec.setText('')
self.oce.setText('')

# insert row updated by B.D.

def ins(self):
fio,spec,oce = self.fio.text(),self.spec.text(),self.oce.text()
try:
self.cur.execute("insert into persons (name,spec,ocenka) values (%s,%s,%s)",(fio,spec,oce))
except:
pass
self.upd()

# update row added by B.D.

def change(self):
fio,spec,oce = self.fio.text(),self.spec.text(), self.oce.text()
try:
ids = int(self.idp.text())
except:
return
self.cur.execute("update persons set name=%s,spec=%s,ocenka=%s where id=%s",(fio,spec,oce,ids,))
self.upd()

# delete record from table

def dels(self):
try:
ids = int(self.idp.text()) # rowid obtained
except:
return
self.cur.execute("delete from persons where id=%s",(ids,))
self.upd()

class Tb(QTableWidget):

def __init__(self, wg):

self.wg = wg # remember window to show table
super().__init__(wg)
self.setGeometry(20, 20, 320, 500)
self.setColumnCount(4)
self.verticalHeader().hide();
self.updt() # обновить таблицу
self.setEditTriggers(QTableWidget.NoEditTriggers)
self.cellClicked.connect(self.cellClick) # catch mouse click on table

def updt(self):

self.clear()
self.setRowCount(0);
self.setHorizontalHeaderLabels(['id', 'Name','Speciality','Score'])
self.wg.cur.execute("select * from persons order by id")
rows = self.wg.cur.fetchall()

i = 0

for elem in rows:
self.setRowCount(self.rowCount() + 1)
j = 0
for t in elem:
self.setItem(i, j, QTableWidgetItem(str(t).strip()))
j += 1
i += 1
self.resizeColumnsToContents()

# Reaction on mouse click inside table

def cellClick(self, row, col): # row - row number, col - column number

self.wg.idp.setText(self.item(row, 0).text())
self.wg.fio.setText(self.item(row, 1).text().strip())
self.wg.spec.setText(self.item(row, 2).text().strip())
self.wg.oce.setText(self.item(row, 3).text().strip())

app = QApplication(sys.argv)
ex = MyWidget()
ex.show()
sys.exit(app.exec_())
Runtime snapshots































































*******************************************************
Setting up MySQL 8.0.25 via purge preinstalled mariadb packages
*******************************************************
$ sudo apt update
$ sudo apt upgrade
$ wget https://dev.mysql.com/get/mysql-apt-config_0.8.17-1_all.deb
$ sudo apt install ./mysql-apt-config_0.8.17-1_all.deb







$ sudo apt update
***********************************
Upgrade mysql-common up to 8.0.25
***********************************
$ sudo apt upgrade  
$ sudo apt install mysql-server
************************************************
Failure due to preinstalled conflicting mariadb packages
************************************************
Cleaning up conflicting packages 
$ sudo apt purge mariadb-client-core-10.5 mariadb-server-core-10.5
*************************
Reinstall MySQL 8.0.25
*************************
$ sudo apt install mysql-server 
$ sudo systemctl start mysql.service
$ sudo systemctl enable mysql.service









************************************************
DATABASE SETUP for "root" on MySQL 8.0.25 
Community Edition
************************************************
mysql> CREATE USER 'root'@'%' IDENTIFIED BY 'PASSWORD';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;

******************************
NETWORK CONFIG SETUP
******************************
# vi /etc/mysql/mysql.conf.d/mysqld.cnf
d-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
datadir         = /var/lib/mysql
log-error       = /var/log/mysql/error.log
bind-address    = 0.0.0.0
:wq
# systemctl restart mysql
 
VENV SETUP

$ python3 -m venv .env
$ source .env/bin/activate
$ pip install mysql-connector-python==8.0.25
$ pip install PyQt5
 
Code for MySQL 8.0.25 connectivity
import sys

import mysql.connector
from PyQt5.QtWidgets import QTableWidget, QApplication, QMainWindow, QTableWidget
from PyQt5.QtWidgets import QTableWidgetItem, QWidget, QPushButton, QLineEdit
from PyQt5 import QtGui

class MyWidget(QWidget):

def __init__(self):

super().__init__()

self.con()

self.setGeometry(125, 125, 550, 650)
self.setWindowTitle('Scores List')
self.tb = Tb(self)
self.btn = QPushButton('Refresh View', self)
self.btn.resize(150, 40)
self.btn.move(350, 20)
self.btn.clicked.connect(self.upd)
self.idp = QLineEdit(self)
self.idp.resize(150, 40)
self.idp.move(350, 70)
self.idp.setReadOnly(True)
self.fio = QLineEdit(self)
self.fio.resize(150, 40)
self.fio.move(350, 120)
self.spec = QLineEdit(self)
self.spec.resize(150, 40)
self.spec.move(350, 180)
self.oce = QLineEdit(self)
self.oce.resize(150, 40)
self.oce.move(350, 230)
self.btn = QPushButton('Add row', self)
self.btn.resize(150, 40)
self.btn.move(350, 280)
self.btn.clicked.connect(self.ins)
self.btn = QPushButton('Update row', self)
self.btn.resize(150, 40)
self.btn.move(350, 330)
self.btn.clicked.connect(self.change)
self.btn = QPushButton('Delete row', self)
self.btn.resize(150, 40)
self.btn.move(350, 390)
self.btn.clicked.connect(self.dels)

# connect to datatabase
def con(self):
self.conn =mysql.connector.connect(user = "root",
password = "*******",
host = "192.168.0.27",
port = 3306,
database = "db3")

self.cur = self.conn.cursor()

def upd(self):
self.conn.commit()
self.tb.updt()
self.idp.setText('')
self.fio.setText('')
self.spec.setText('')
self.oce.setText('')

# insert row updated by B.D.

def ins(self):
fio,spec,oce = self.fio.text(),self.spec.text(),self.oce.text()
try:
self.cur.execute("insert into persons (name,spec,ocenka) values (%s,%s,%s)",(fio,spec,oce))
except:
pass
self.upd()

# update row added by B.D.

def change(self):
fio,spec,oce = self.fio.text(),self.spec.text(), self.oce.text()
try:
ids = int(self.idp.text())
except:
return
self.cur.execute("update persons set name=%s,spec=%s,ocenka=%s where id=%s",(fio,spec,oce,ids,))
self.upd()

# delete record from table

def dels(self):
try:
ids = int(self.idp.text()) # rowid obtained
except:
return
self.cur.execute("delete from persons where id=%s",(ids,))
self.upd()

class Tb(QTableWidget):

def __init__(self, wg):

self.wg = wg # remember window to show table
super().__init__(wg)
self.setGeometry(20, 20, 320, 500)
self.setColumnCount(4)
self.verticalHeader().hide();
self.updt() # обновить таблицу
self.setEditTriggers(QTableWidget.NoEditTriggers)
self.cellClicked.connect(self.cellClick) # catch mouse click on table

def updt(self):

self.clear()
self.setRowCount(0);
self.setHorizontalHeaderLabels(['id', 'Name','Speciality','Score'])
self.wg.cur.execute("select * from persons order by id")
rows = self.wg.cur.fetchall()

i = 0

for elem in rows:
self.setRowCount(self.rowCount() + 1)
j = 0
for t in elem:
self.setItem(i, j, QTableWidgetItem(str(t).strip()))
j += 1
i += 1
self.resizeColumnsToContents()

# Reaction on mouse click inside table

def cellClick(self, row, col): # row - row number, col - column number

self.wg.idp.setText(self.item(row, 0).text())
self.wg.fio.setText(self.item(row, 1).text().strip())
self.wg.spec.setText(self.item(row, 2).text().strip())
self.wg.oce.setText(self.item(row, 3).text().strip())

app = QApplication(sys.argv)
ex = MyWidget()
ex.show()
sys.exit(app.exec_())
 Runtime snapshots




Runtime on bare metal Server side (Mariadb-Server)


Client Side


Two PyQT5 sessions opened from Virthost (Server F34) with each one of Debian 11 VBOX Guests attached to Virthost via the same Linux bridge,i.e. both Guests are on the same subnet with
Virthost 192.168.0.0/24.


 Needless to say that KVM Guests of Debian 11  would be much better and faster for testing the same configuration via common
Linux Bridge to Fedora 34 Server running KVM-Hypervisor.