We demonstrate how to convert Python modules into Cythonized ones in this sense.

Typically, when using Cython, only a few selected modules of the program are Cythonized.

Examining a very basic Python module that we could put in `wsgi.py`.

import os
import sys

if os.name != 'nt':
    path = '/home/usr/public_html'
    python_path = '/home/user/env/lib/python3.9/site-packages'
os.environ['DJANGO_SETTINGS_MODULE'] = 'conf.settings'

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

from django.conf import settings
setattr(settings, 'Key', False)

We are aware that the Django application can call this module right away when the project is launched. and a location that we can refer to as below.

from conf.wsgi import application

Using the Python API, Cython can convert Python code into similar C code as follows:

$ cython3 wsgi.py

The outcome is a file called `wsgi.c` that may be built into a Python C-extension. The C-file can be examined, although it is nearly 3000 lines long and not really intended for human reading.

The modules typically employ Cython language extensions to render them invalid Python. To signify this, one typically adds the .pyx suffix to the file names of Cython modules, thus `wsgi.py` would become `wsgi.pyx`.

In order to make constructing C-extensions from Cython easier, one typically uses Python's `distutilssetup.py` build file rather than Cython straight from the command line:

from distutils.core import setup
from Cython.Build import cythonize


This setup file might include multiple modules in more extensive real-world applications.

The C-extension module can then be produced using:

$ python3 setup.py build_ext --inplace

Wait a moment and keep an eye on the console. Depending on your platform, you will receive files ending .c, .pyd, or .so.

`wsgi.py` can now be swapped out for *.pyd or *.so. Additionally, you can utilize this file in your Python program just like `wsgi.py` file. and may use any function contained in that file.

from conf.wsgi import application

The conversion of a pure Python module into a C-extension typically only results in very small speedups because the C-extension just implements the completely dynamic Python code using the Python C-API. However, as we will see in the steps that follow, it is feasible to gain far more significant performance benefits by incorporating extensions written in the Cython language into the code (making it no longer legitimate Python code).

Share Sense To:

Similar Senses

It is a Django's performance tuning guide using select_related and prefetch_related for Faster Queries Django is a popular web framework …