2

I'd like the answers to accumulate a checklist of general reasons why unicode_literals may not work as expected

from __future__ import unicode_literals

This feature has both good and bad consequences. It has no effect in Python 3. For Python 2 it makes all string literals unicode by default, without the u'' prefixes.


This feature is not working in my specific case in a flask file, which begins:

# encoding: utf-8
from __future__ import unicode_literals
from __future__ import print_function
assert isinstance('123', unicode)

This assert passes when I run from the command line. But fails when run by apache. (That is, this assert failure message appears in my error_log.) My goal is to have unicode strings everywhere.

Here are a few aspects unique to my particular case that could conceivably contribute:

  • Python 2.7.11, Flask 0.11, Apache 2.2.15
  • the above .py file is named directly in my WSGIScriptAlias directive, instead of an intermediate .wsgi file as in the examples.

  • I'm executing activate_this.py for a virtualenv before I import flask. I don't think that matters, as it comes later in the file but here are those lines

    ACTIVATE_THIS_PY = '/somewhere/somewhere/activate_this.py'
    execfile(ACTIVATE_THIS_PY, dict(__file__=ACTIVATE_THIS_PY))
    import flask

Related:

Community
  • 1
  • 1
Bob Stein
  • 16,271
  • 10
  • 88
  • 101
  • What version of Python is being used by Apache? – Mark Ransom Jul 01 '16 at 16:11
  • Are those four lines the exact beginning of your file? Nothing else above or between them? Future statements can only be preceded by blank lines, comments, other future statements, and the module docstring. – user2357112 Jul 01 '16 at 16:13
  • @user2357112 good first thing to check. Yes those are the first four lines of the .py file. – Bob Stein Jul 01 '16 at 16:23
  • @MarkRansom Python 2.7.11, and added other info in edit. – Bob Stein Jul 01 '16 at 16:27
  • 2
    If the script is compiled with `flags = 0`, the `__future__` statements will be useless. Try using `import` to actually get your module. – o11c Jul 01 '16 at 16:49
  • Have you verified that the same version of Python is being run from the command line and from Apache? – Mark Ransom Jul 01 '16 at 16:56
  • @MarkRansom good idea, yes, in both cases sys.version is `2.7.11 (default, Dec 7 2015, 11:22:37)` – Bob Stein Jul 01 '16 at 17:00
  • Good point @o11c. I was avoiding an `ImportError` when file.wsgi tries to import file.py. Will work that out... – Bob Stein Jul 01 '16 at 17:02
  • You nailed it @o11c! when file.wsgi imports file.py unicode_literals work in file.py. (For import to work I [learned](http://blog.dscpl.com.au/2014/09/python-module-search-path-and-modwsgi.html) I needed `WSGIDaemonProcess example python-path=/path/to/myfiles`.) If you answer with that `import` trick I'll accept it. – Bob Stein Jul 01 '16 at 17:27

0 Answers0