OrderAndChaos
OrderAndChaos

Reputation: 3860

Odd output when trying to set up Flask secret key

I'm trying to work out how to deploy a Flask app. The docs say I can generate a secret key with a Python command:

python -c 'import os; print(os.urandom(16))'

In their example this outputs b'_5#y2L"F4Q8z\n\xec]/'.

When I run it with python I get odd characters, and with python3 I get character codes. Why are the python and python3 versions different? Which one should I use?

$ python -c 'import os; print(os.urandom(16))' 
��L���vl�6��Z5

$ python3 -c 'import os; print(os.urandom(16))'
b'A\xa4\xf3O\xdd\xf4qr\xfb\x9b\x12\x1f*\x0bm\xdf'

Upvotes: 1

Views: 360

Answers (1)

davidism
davidism

Reputation: 127180

You should be using Python 3 for all new projects, so this is essentially a non-issue. The Python 3 output is correct and can be copy pasted directly. The fact that python runs Python 2 for you means you have not followed the tutorial to set up a Python 3 virtualenv, or your virtualenv is not active.

If you're really using Python 2 for some reason, that output is fine too. Copy and paste it into quotes and it will work. Python 2's str is sort-of-bytes, so it outputs non-ASCII characters, while Python 3 always outputs bytes with escape characters (\xAB). Either output will work in either version.

SECRET_KEY = '��L���vl�6��Z5'
SECRET_KEY = b'A\xa4\xf3O\xdd\xf4qr\xfb\x9b\x12\x1f*\x0bm\xdf'

The example output does contain escape characters (\n and \xec), just not as many as the random string you happened to generate.

Upvotes: 1

Related Questions