SoFunction
Updated on 2024-11-16

Solving uWSGI encoding problems in detail

Problems found

I recently ran into an issue at work where I was deploying a Flask-written application to a full-fledged server via Supervisor+uWSGI and got this error:

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 is no such error when running directly in a Python environment. It also works fine using uwsgi.

This error often occurs in Python2 due to the lack of unicode support, but all of my programs are written in Python3, and I shouldn't get this error again. Moreover, all python files have the encoding set 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 contents of the configuration file are as follows:

[uwsgi]
master = true

wsgi-file = 
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/

Since neither Python nor uwsgi will give you this error directly, you can assume that the problem is due to the environment encoding settings.

View the server's code 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

It was found that the LANG and LANGUAGE environment variables were not set.

You can set the values of these two environment variables in the After testing, it turns out that LANGUAGE is the one that actually works.

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

summarize

Above is the entire content of this article, I hope that the content of this article on everyone's learning or use of python can bring some help, if there is any doubt you can leave a message to exchange, thank you for my support.