Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove auto escaping from environment variable?

Tags:

python-3.3

In settings.py, I get var from environment like this:

ROBOTS_STR = os.environ.get('DJANGO_ROBOTS_STR')

My env var is set in a file and looks like:

DJANGO_ROBOTS_STR=User-agent: *\nDisallow: /admin\nDisallow: /api

The problem is that in the view, when I get settings.ROBOTS_STR, the value of the string has been auto escaped. It is: User-agent: *\\nDisallow: /admin\\nDisallow: /api

How can I change this behaviour? Note that I'm using Python 3.3

like image 994
David D. Avatar asked Oct 24 '25 06:10

David D.


1 Answers

Decode it with string-escape:

>>> os.environ.get('DJANGO_ROBOTS_STR')
'User-agent: *\\nDisallow: /admin\\nDisallow: /api'
>>> os.environ.get('DJANGO_ROBOTS_STR').decode('string-escape')
'User-agent: *\nDisallow: /admin\nDisallow: /api'
>>> print(os.environ.get('DJANGO_ROBOTS_STR'))
User-agent: *\nDisallow: /admin\nDisallow: /api
>>> print(os.environ.get('DJANGO_ROBOTS_STR').decode('string-escape'))
User-agent: *
Disallow: /admin
Disallow: /api

For Python 3, encode it first, then decode it:

>>> os.environ.get('DJANGO_ROBOTS_STR').encode('latin1').decode('unicode_escape')
'User-agent: *\nDisallow: /admin\nDisallow: /api'
like image 122
Burhan Khalid Avatar answered Oct 28 '25 05:10

Burhan Khalid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!