Skip to content

Commit f3d05bb

Browse files
committed
Python: Fix enabling of UTF-8 in some situations.
There was a couple of reports of Python applications failing due to the following type of error File "/opt/netbox/netbox/netbox/configuration.py", line 25, in _import print(f"\U0001f9ec loaded config '{path}'") UnicodeEncodeError: 'ascii' codec can't encode character '\U0001f9ec' in position 0: ordinal not in range(128) due to the use of Unicode text in the print() statement. This only happened for python 3.8+ when using the "home" configuration option as this meant we were going through the new PyConfig configuration. When using this new configuration method with the 'isolated' specific API (for embedded Python) UTF-8 is disabled by default, PyPreConfig->utf8_mode = 0. To fix this we need to setup the Python pre config and enable utf-8 mode. However rather than enable utf-8 unconditionally we can set to it to -1 so that it will use the LC_CTYPE environment variable to determine whether to enable utf-8 mode or not. utf-8 mode will be enabled if LC_CTYPE is either: C, POSIX or some specific UTF-8 locale. This is the default utf8_mode setting when using the non-isolated PyPreConfig API. Reported-by: Tobias Genannt <tobias.genannt@kappa-velorum.net> Tested-by: Tobias Genannt <tobias.genannt@kappa-velorum.net> Link: <https://peps.python.org/pep-0587/> Link: <https://docs.python.org/3/c-api/init_config.html#c.PyPreConfig.utf8_mode> Fixes: 491d0f7 ("Python: Added support for Python 3.11.") Closes: <#817> Reviewed-by: Alejandro Colomar <alx@nginx.com> Signed-off-by: Andrew Clayton <a.clayton@nginx.com>
1 parent a560cbf commit f3d05bb

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

src/python/nxt_python.c

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,9 +78,23 @@ nxt_python3_init_config(nxt_int_t pep405)
7878
PyConfig config;
7979
PyStatus status;
8080
nxt_int_t ret;
81+
PyPreConfig preconfig;
8182

8283
ret = NXT_ERROR;
8384

85+
PyPreConfig_InitIsolatedConfig(&preconfig);
86+
/*
87+
* Determine whether to use UTF-8 mode or not, UTF-8
88+
* will be enabled if LC_CTYPE is C, POSIX or some
89+
* specific UTF-8 locale.
90+
*/
91+
preconfig.utf8_mode = -1;
92+
93+
status = Py_PreInitialize(&preconfig);
94+
if (PyStatus_Exception(status)) {
95+
return ret;
96+
}
97+
8498
PyConfig_InitIsolatedConfig(&config);
8599

86100
if (pep405) {

0 commit comments

Comments
 (0)