DEVHIDE
  • Home (current)
  • About
  • Contact
  • Cookie
  • Home (current)
  • About
  • Contact
  • Cookie
  • Disclaimer
  • Privacy
  • TOS
Login Or Sign up

bleach stripping style that should be allowed

882 Views Asked by dabadaba At 24 January 2021 at 12:22 2025-12-21T15:10:07.721000

I have the following string:

html = '<div id="cover" style="display: block; height: 682px"><div class="cover-desktop hidden-xs" style="background-image: linear-gradient(rgba(0, 0, 0, 0.45), rgba(0, 0, 0, 0.45)), url(\'/site_media/covers/cover.jpg\')"></div></div>'

And these are my options:

ALLOWED_TAGS = bleach.sanitizer.ALLOWED_TAGS + [
    'p',
    'div',
    'table',
    'br',
    'style'
]
ALLOWED_STYLES = ['display', 'height', 'background-image']
ALLOWED_ATTRIBUTES = {
    '*': ['id', 'class', 'style']
}

However when running bleach.clean, the background-image style is getting stripped:

cleaned_html = bleach.clean(html, tags=ALLOWED_TAGS, styles=ALLOWED_STYLES, attributes=ALLOWED_ATTRIBUTES)

Output:

u'<div id="cover" style="display: block; height: 682px;"><div class="cover-desktop hidden-xs" style=""></div></div>'

Why? And how can I fix that?

In fact, how can I allow any style? '*' doesn't do the trick.

edit: it turns out it's because of the background image url(). If a rule containts url it just gets stripped. Here's their code in BleachSanitizerFilter.sanitize_css:

# Drop any url values before we do anything else
style = re.compile(r"url\s*\(\s*[^\s)]+?\s*\)\s*").sub(" ", style)

So how am I supposed to allow background-image property then?

python python-2.7 sanitization bleach
Original Q&A
1

There are 1 best solutions below

0
zeyad moustafa zeyad moustafa On 26 March 2023 at 23:32

I am using the bleach 6.0 and I am adding css styles like this

import bleach
from bleach.css_sanitizer import CSSSanitizer

ALLOWED_TAGS = ['p', 'strong', 'em', 'ul', 'ol', 'li', "a", "abbr", 
                "acronym", "b", "blockquote", "code", "i",'span']
ALLOWED_ATTRIBUTES = bleach.sanitizer.ALLOWED_ATTRIBUTES
ALLOWED_ATTRIBUTES['span'] = ['style']

ALLOWED_STYLES = [ 'color', 'font-family', 'font-size', 'font-style', 'font-weight', 'text-align', 'text-decoration', 'text-indent',
                   'background-color', 'background-image', 'background-repeat', 'background-size', 'border', 'border-bottom', 
                   'border-left', 'border-radius', 'border-right', 'border-top', 'margin', 'margin-bottom', 'margin-left', 
                   'margin-right', 'margin-top', 'padding', 'padding-bottom', 'padding-left', 'padding-right', 'padding-top',
                   'line-height', 'letter-spacing', 'word-spacing']

css_santizer = CSSSanitizer(allowed_css_properties=ALLOWED_STYLES)

cleaned_description = bleach.clean(description,tags=ALLOWED_TAGS,attributes=ALLOWED_ATTRIBUTES,css_sanitizer=css_santizer)

I hope this works for you or anybody facing this problem and you can see the documentation for more details.

Related Questions in PYTHON

  • new thread blocks main thread
  • Extracting viewCount & SubscriberCount from YouTube API V3 for a given channel, where channelID does not equal userID
  • Display images on Django Template Site
  • Difference between list() and dict() with generators
  • How can I serialize a numpy array while preserving matrix dimensions?
  • Protractor did not run properly when using browser.wait, msg: "Wait timed out after XXXms"
  • Why is my program adding int as string (4+7 = 47)?
  • store numpy array in mysql
  • how to omit the less frequent words from a dictionary in python?
  • Update a text file with ( new words+ \n ) after the words is appended into a list
  • python how to write list of lists to file
  • Removing URL features from tokens in NLTK
  • Optimizing for Social Leaderboards
  • Python : Get size of string in bytes
  • What is the code of the sorted function?

Related Questions in PYTHON-2.7

  • Initialize matrix
  • Why is my program adding int as string (4+7 = 47)?
  • How to save gensim LDA topics output to csv along with the scores?
  • Update a text file with ( new words+ \n ) after the words is appended into a list
  • Removing URL features from tokens in NLTK
  • python, global name not defined
  • Why does collections.OrderedDict use try and except to initialize variables?
  • Invalid URL: No host supplied : error while using Request.get(url) in Python
  • Python GUI application to copy files one location to another location
  • Why I receive CERTIFICATE_VERIFY_FAILED from google adwords api?
  • Excel worksheet to Numpy array
  • Python datetime.now() with timezone
  • local variable referenced before assignment in strange condition
  • Python 2.7 - find combinations of numbers in a list that add to another number
  • Can't install anything with pip2 on Windows 7 due to UnicodeDecodeError

Related Questions in SANITIZATION

  • Is .text() safe or not to sanitize data? [JQuery]
  • Strip JavaScript from HTML DOM Tree with JavaScript
  • Sanitizing JSON data for usage as JavaScript object
  • How to sanitize form values to allow text-only
  • Data validation / Sanitization callback function
  • angular-translate sanitisation fails with UTF characters
  • Jenkins jobs configuration checking before run it
  • Angular 2 - sanitizing HTML
  • Escaping content in @section tag
  • Using Regex with Prepared SQL Statements
  • Best practice: handle functions with lots of parameters and reserved names
  • PHP - Properly validate and/or sanitize form input
  • Sanitizing data in Yii 2 - Built in or extension?
  • Sanitization & Validation
  • Allow <a> and <b> tags in PHP function?

Related Questions in BLEACH

  • html5lib cannot be found in bleach installation
  • How to remove links from HTML completely with Bleach?
  • ERROR: Could not find a version that satisfies the requirement bleach==2.1.2 (from -r requirements.txt (line 1)) (from versions: none)
  • bleach stripping style that should be allowed
  • Prevent pip from upgrading a dependency
  • timyMCE allowed tags in django
  • BLEACH_DEFAULT_WIDGET django
  • Django Bleach with CKeditor?
  • Make Bleach to allow code tags
  • SQL syntax error on table name
  • Bleach and html5lib incompatible with tensorboard
  • python bleach: inconsistent cleaning behaviour
  • How to install a bleach module without using npm install?
  • Process fields in SQLAlchemy model (using flask_sqlalchemy)
  • bleach clean adds "<pre><code>“ tag at the beginning rather than cleaning

Trending Questions

  • UIImageView Frame Doesn't Reflect Constraints
  • Is it possible to use adb commands to click on a view by finding its ID?
  • How to create a new web character symbol recognizable by html/javascript?
  • Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
  • Heap Gives Page Fault
  • Connect ffmpeg to Visual Studio 2008
  • Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
  • How to avoid default initialization of objects in std::vector?
  • second argument of the command line arguments in a format other than char** argv or char* argv[]
  • How to improve efficiency of algorithm which generates next lexicographic permutation?
  • Navigating to the another actvity app getting crash in android
  • How to read the particular message format in android and store in sqlite database?
  • Resetting inventory status after order is cancelled
  • Efficiently compute powers of X in SSE/AVX
  • Insert into an external database using ajax and php : POST 500 (Internal Server Error)

Popular # Hahtags

javascript python java c# php android html jquery c++ css ios sql mysql r reactjs

Popular Questions

  • How do I undo the most recent local commits in Git?
  • How can I remove a specific item from an array in JavaScript?
  • How do I delete a Git branch locally and remotely?
  • Find all files containing a specific text (string) on Linux?
  • How do I revert a Git repository to a previous commit?
  • How do I create an HTML button that acts like a link?
  • How do I check out a remote Git branch?
  • How do I force "git pull" to overwrite local files?
  • How do I list all files of a directory?
  • How to check whether a string contains a substring in JavaScript?
  • How do I redirect to another webpage?
  • How can I iterate over rows in a Pandas DataFrame?
  • How do I convert a String to an int in Java?
  • Does Python have a string 'contains' substring method?
  • How do I check if a string contains a specific word?
.

Copyright © 2021 Jogjafile Inc.

  • Disclaimer
  • Privacy
  • TOS
  • Homegardensmart
  • Math
  • Aftereffectstemplates