'Replacement in python package in Docker

GraphQL is still not supported in Django 4, so to use it I need to change the line:

"from django.utils.encoding import force_text"

to

"from django.utils.encoding import force_str as force_text"

in package

"VENV/lib/PYTHON_VERSION/site-packages/graphene_django/utils/utils.py"

The problem occurs when using Docker, how could I replace this line when building the container?



Solution 1:[1]

Instead of manually changing the python module in site-packages, and assuming there's no other way to fix this (i.e. if all you need is force_text to be defined at django.utils.encoding), you could also write a "monkey patch", i.e. a runtime patch of the django.utils.encoding module. Adding something like this in our own code (untested):

from django.utils import encoding

encoding.force_text = encoding.force_str 

Later, once not needed, this patch should be removed.

Solution 2:[2]

Simply combine RUN with a sed-replace in your dockerfile.

RUN pyver="python$(python --version | grep -Eo '[0-9]\.[0-9]')" && \
    sed -i "s/import force\_text/import force\_str as force\_text/g" \
    ./lib/$pyver/site-packages/graphene_django/utils/utils.py

Replace <PATH_TO_utils.py> with the path to utils.py

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ricardo Alves
Solution 2