Solve the encoding problem of uWSGI in detail

  • 2020-05-27 06:14:11
  • OfStack

Found the problem

Recently, I encountered a problem in my work. When I was deploying the application written by Flask to the official server through Supervisor+uWSGI, the following error occurred:


Unable to print the message and arguments  �  possible formatting error.

or


UnicodeEncodeError:  ' ascii' codec can't encode characters in position 24-25: ordinal not in range(128)

Interestingly, there are no such errors when running directly in the Python environment. uwsgi uwsgi. ini also works fine.

Due to the lack of support for unicode, this kind of error is often found in Python2, but all my programs are written in Python3, so this should not happen again. Furthermore, all python files are encoded on the first line:


# -*- coding: utf-8 -*-

My environment is as follows:

Ubuntu 16.04.1 LTS Python 3.5.2 uWSGI 2.0.14 (in python3 pip) Supervisor 3.3.1 (in python2 pip)

The uwsgi.ini configuration file reads as follows:


[uwsgi]
master = true

wsgi-file = manage.py
callable = app

processes = 2
threads = 2
max-requests = 6000
chmod-socket = 664

uid = app
gid = app

buffer-size = 32768

venv = {project_dir}/venv

; http = 127.0.0.1:5001

logto = {project_dir}/logs/uwsgi.log

Since neither Python nor uwsgi can be used directly, it can be determined that the problem is caused by the environment encoding Settings.

The code of the view server is as follows:


% locale
LANG=C
LANGUAGE=C:
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=en_US.UTF-8

Found that the LANG and LANGUAGE environment variables are not set.

You can set the values of these two environment variables in uwsgi.ini. After testing, it was found that LANGUAGE actually worked.


env LANG="en_US.UTF-8"
env LANGUAGE="en_US.UTF-8"

conclusion


Related articles: