Python Forum
Thread Rating:
  • 1 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
safe text to html
#9
(Jul-06-2017, 02:48 AM)Skaperen Wrote: here is a snippet of what i ended up coding:
The problem is that is not correct Wink
I you want to challenge yourself to write this,no problem.
Can use tool i show here to test code,
all that's need for code under is pip install Flask.
>>> from flask import Markup                               
                                                            
>>> s = '<html><body>hello world</body></html>'              
>>> s = s.replace('&','&amp;')                               
... s = s.replace('"','&quot;')                              
... s = s.replace('<','&lt;')                                
... s = s.replace('>','&gt')                                 
... for n in list(range(32))+[39,92]:                        
...     s = s.replace(chr(n),'&#'+hex(n)[1:]+';')            
                                                            
>>> s                                                        
'&lt;html&gt&lt;body&gthello world&lt;/body&gt&lt;/html&gt'  
>>> test = Markup(s) 
>>> test
Markup('&lt;html&gt&lt;body&gthello world&lt;/body&gt&lt;/html&gt')                                 
>>> test.unescape()                                          
'<html&gt<body&gthello world</body&gt</html&gt' 
test.unescape() should be '<html><body>hello world</body></html>'
With Jinja2 is battle proved  and tested,
company like Mozilla use it and of course all that use Flask.
>>> import jinja2

>>> s = '<html><body>hello world</body></html>'
>>> test = jinja2.escape(s)
>>> test
Markup('&lt;html&gt;&lt;body&gt;hello world&lt;/body&gt;&lt;/html&gt;')
>>> test.unescape()
'<html><body>hello world</body></html>'
Reply


Messages In This Thread
safe text to html - by Skaperen - Jul-05-2017, 06:02 AM
RE: safe text to html - by nilamo - Jul-05-2017, 02:32 PM
RE: safe text to html - by nilamo - Jul-05-2017, 02:35 PM
RE: safe text to html - by snippsat - Jul-05-2017, 04:50 PM
RE: safe text to html - by wavic - Jul-05-2017, 04:50 PM
RE: safe text to html - by nilamo - Jul-05-2017, 05:08 PM
RE: safe text to html - by Skaperen - Jul-06-2017, 01:12 AM
RE: safe text to html - by Skaperen - Jul-06-2017, 02:48 AM
RE: safe text to html - by snippsat - Jul-06-2017, 06:53 AM
RE: safe text to html - by nilamo - Jul-06-2017, 04:29 PM
RE: safe text to html - by Skaperen - Jul-07-2017, 04:23 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  make eval() safe Skaperen 5 5,400 Mar-24-2022, 05:47 PM
Last Post: Skaperen
  is this string shell quote safe? Skaperen 2 3,034 Feb-18-2020, 12:56 AM
Last Post: Skaperen
  after py2 EOL, is it safe to repoint python? Skaperen 6 4,849 Sep-14-2019, 10:37 AM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020