3

I try to html escape a string

from html import escape
project_name_unescaped = Project.get('name').encode('utf-8')
project_name = escape(project_name_unescaped)

I get the following error

Traceback (most recent call last):
  File "hosts.py", line 70, in <module>
     project_name = escape(bytes(project_name_unescaped))
  File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/html/__init__.py", line 19, in escape
    s = s.replace("&", "&amp;") # Must be done first!
 TypeError: a bytes-like object is required, not 'str'

I also tried it with the following, but still have the same error

project_name = escape(bytes(project_name_unescaped))

The strange thing is, I'm pretty sure this had worked before. Any ideas whats wrong or what I need to change to make it work again? Also I tried it before with

from cgi import escape

1 Answer 1

1

The error message is a little confusing. html.escape expects s to be str, not bytes as you would expect from the message.

Remove all encoding-related stuff and it will work

from html import escape
project_name_unescaped = Project.get('name')
project_name = escape(project_name_unescaped)
Sign up to request clarification or add additional context in comments.

3 Comments

thanks that helped. I just wondered, because before I had to add the encoding as else it would fail without it. Maybe that was for python2 the case.
Well, yes, Python 3 changed string representations. But hard to tell, there wasn't even html module in standard library of Python 2.
I used cgi module before, just switched to html recently after I had the issue with python 3.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.