LIBSASS(1)
π NAME π
okay so bestie, meet libsass β aka the libsass Documentation, and this is LIBSASS(1), no cap. It's giving "I compile your Sass so you never have to touch a Ruby or Node.js stack again" energy. π
This package provides a simple Python extension module sass which is binding LibSass (written in C/C++ by Hampton Catlin and Aaron Leung). It's very straightforward and there isn't any headache related Python distribution/deployment. That means you can add just libsass into your setup.py's install_requires list or requirements.txt file.
It currently supports CPython 2.6, 2.7, 3.5--3.7, and PyPy 2.3+! π
β¨ FEATURES β¨
like, the whole vibe check passed, fr fr:
- You don't need any Ruby/Node.js stack at all, for development or deployment either. π
- Fast. (LibSass is written in C++.) π₯
- Simple API. See example code for details.
- Custom functions. π
@importcallbacks.- Support both tabbed (Sass) and braces (SCSS) syntax.
- WSGI middleware for ease of development. It automatically compiles Sass/SCSS files for each request. See also
sassutils.wsgifor details. - setuptools/distutils integration. You can build all Sass/SCSS files using
setup.py build_sasscommand. See alsosassutils.distutilsfor details. - Works also on PyPy. π¦
- Provides prebuilt wheel (PEP 427) binaries for Windows and Mac. π
πΈ INSTALL πΈ
It's available on PyPI, so you can install it using pip:
$ pip install libsass
NOTE: π«Ά libsass requires some features introduced by the recent C++ standard. You need a C++ compiler that support those features. See also libsass project's README file.
π§ EXAMPLES π§
Compile a String of Sass to CSS
>>> import sass
>>> sass.compile(string='a { b { color: blue; } }')
'a b {\n color: blue; }\n'
Compile a Directory of Sass Files to CSS
>>> import sass
>>> import os
>>> os.mkdir('css')
>>> os.mkdir('sass')
>>> scss = """\
... $theme_color: #cc0000;
... body {
... background-color: $theme_color;
... }
... """
>>> with open('sass/example.scss', 'w') as example_scss:
... example_scss.write(scss)
...
>>> sass.compile(dirname=('sass', 'css'), output_style='compressed')
>>> with open('css/example.css') as example_css:
... print(example_css.read())
...
body{background-color:#c00}
π USER'S GUIDE π
Using with Flask
This guide explains how to use libsass with the Flask web framework. The sassutils package provides several tools that can be integrated into web applications written in Flask. π
Contents
- Using with Flask
- Directory layout
- Defining manifest
- Building Sass/SCSS for each request
- Building Sass/SCSS for each deployment
Directory layout
Imagine the project contained in such directory layout:
setup.pymyapp/__init__.pystatic/sass/css/
templates/
Sass/SCSS files will go inside myapp/static/sass/ directory. Compiled CSS files will go inside myapp/static/css/ directory. CSS files can be regenerated, so add myapp/static/css/ into your ignore list like .gitignore or .hgignore. π
Defining manifest
The sassutils defines a concept named manifest. Manifest is the build settings of Sass/SCSS. It specifies some paths related to building Sass/SCSS:
- The path of the directory which contains Sass/SCSS source files.
- The path of the directory which the compiled CSS files will go.
- The path, exposed to HTTP (through WSGI), of the directory that will contain the compiled CSS files.
Every package may have its own manifest. Paths have to be relative to the path of the package.
For example, in the above project, the package name is myapp. The path of the package is myapp/. The path of the Sass/SCSS directory is static/sass/ (relative to the package directory). The path of the CSS directory is static/css/. The exposed path is /static/css.
These settings can be represented as the following manifests:
{
'myapp': ('static/sass', 'static/css', '/static/css')
}
As you can see the above, the set of manifests are represented in dictionary, in which the keys are packages names and the values are tuples of paths. π
Building Sass/SCSS for each request
SEE ALSO:
Flask --- Hooking in WSGI Middlewares The section which explains how to integrate WSGI middlewares to Flask. Flask --- Application Dispatching The documentation which explains how Flask dispatches each request internally.
In development, manually building Sass/SCSS files for each change is a tedious task. SassMiddleware makes the web application build Sass/SCSS files for each request automatically. It's a WSGI middleware, so it can be plugged into the web app written in Flask.
SassMiddleware takes two required parameters:
- The WSGI-compliant callable object.
- The set of manifests represented as a dictionary.
So:
from flask import Flask
from sassutils.wsgi import SassMiddleware
app = Flask(__name__)
app.wsgi_app = SassMiddleware(app.wsgi_app, {
'myapp': ('static/sass', 'static/css', '/static/css')
})
And then, if you want to link a compiled CSS file, use the url_for() function:
<link href="{{ url_for('static', filename='css/style.scss.css') }}"
rel="stylesheet" type="text/css">
NOTE: π The linked filename isstyle.scss.css, not juststyle.scss. All compiled filenames have trailing.csssuffix.
Building Sass/SCSS for each deployment
NOTE: This section assumes that you use setuptools for deployment.
SEE ALSO:
Flask --- Deploying with Setuptools How to deploy Flask application using setuptools.
If libsass is installed in the site-packages (for example, your virtualenv), the setup.py script also gets a new command provided by libsass: build_sass. The command is aware of the sass_manifests option of setup.py and builds all Sass/SCSS sources according to the manifests.
Add these arguments to setup.py script:
setup(
# ...,
setup_requires=['libsass >= 0.6.0'],
sass_manifests={
'myapp': ('static/sass', 'static/css', '/static/css')
}
)
The setup_requires option makes sure that libsass is installed in site-packages (for example, your virtualenv) before the setup.py script. That means if you run the setup.py script and libsass isn't installed in advance, it will automatically install libsass first. π
The sass_manifests specifies the manifests for libsass.
Now setup.py build_sass will compile all Sass/SCSS files in the specified path and generates compiled CSS files inside the specified path (according to the manifests).
If you use it with sdist or bdist commands, the packed archive will also contain the compiled CSS files! π₯
$ python setup.py build_sass sdist
You can add aliases to make these commands always run the build_sass command first. Make setup.cfg config:
[aliases]
sdist = build_sass sdist
bdist = build_sass bdist
Now it automatically builds Sass/SCSS sources and include the compiled CSS files to the package archive when you run setup.py sdist. β¨
π Changelog π
Version 0.20.1
Released on August 27, 2020.
- (no changes, re-releasing to test build automation)
Version 0.20.0
Released on May 1, 2020.
- Produce abi3 wheels on macos / linux [#307 by Anthony Sottile]
- Follow up the libsass upstream: 3.6.4 --- See the release notes of LibSass 3.6.4. [#313 by Anthony Sottile]
Version 0.19.4
Released on November 3, 2019.
- Follow up the libsass upstream: 3.6.3 --- See the release notes of LibSass 3.6.3. [#304 by Anthony Sottile]
Version 0.19.3
Released on October 5, 2019.
- Follow up the libsass upstream: 3.6.2 --- See the release notes of LibSass 3.6.2. [#302 by Anthony Sottile]
Version 0.19.2
Released on June 16, 2019.
- Follow up the libsass upstream: 3.6.1 --- See the release notes of LibSass 3.6.1. [#298 by Anthony Sottile]
Version 0.19.1
Released on May 18, 2019.
- Re-release of 0.19.0 with windows python2.7 wheels [#297 by Anthony Sottile]
Version 0.19.0
Released on May 18, 2019.
- Follow up the libsass upstream: 3.6.0 --- See the release notes of LibSass 3.6.0. [#295 by Anthony Sottile]
Version 0.18.0
Release on March 13, 2019
- Add support for previous import path to importer callbacks [#287 #291 by Frankie Dintino]
Version 0.17.0
Release on January 03, 2019
- Add several new cli options [#279 #268 by Frankie Dintino]
--sourcemap-file: output file for source map--sourcemap-contents: embedsourcesContentin source map--sourcemap-embed: embedsourceMappingURLas data uri--omit-sourcemap-url: omit source map url comment from output--sourcemap-root: base path, emitted assourceRootin source map
- Fix
.sassinWsgiMiddleware(again) [#280 by Anthony Sottile]
Version 0.16.1
Released on November 25, 2018.
- Fix compilation on macos mojave [#276 #277 by Anthony Sottile]
- Fix
.sassinWsgiMiddlewareforstrip_extension=True[#278 by Anthony Sottile]
Version 0.16.0
Released on November 13, 2018.
- Use
-lc++link flag when compiling with clang [#270 by Christian Thieme #271 by Anthony Sottile] - Honor
strip_extensioninSassMiddleware[#274 by Anthony Sottile] - Follow up the libsass upstream: 3.5.5 --- See the release notes of LibSass 3.5.5. [#275 by Anthony Sottile]
Version 0.15.1
Released on September 24, 2018.
- Fix
setup.py sdist(regressed in 0.15.0) [#267 by Anthony Sottile]
Version 0.15.0
Released on September 16, 2018.
- Fix invalid escape sequences [#249 by Anthony Sottile]
- Add code of conduct [#251 by Nick Schonning]
- Add support for python3.7 and remove testing for python3.4 [#254 by Anthony Sottile]
- Add
strip_extensionoption for wsgi / distutils builder [#55 #258 by Anthony Sottile #260 by Morten Brekkevold] - Deprecate
sassc(replaced bypysassc). [#262 by Anthony Sottile] - Import abc classes from
collections.abcto removeDeprecationWarning[#264 by Gary van der Merwe #265 by Anthony Sottile]
Version 0.14.5
Released on April 25, 2018.
- Follow up the libsass upstream: 3.5.4 --- See the release notes of LibSass 3.5.4. [#247 by Anthony Sottile]
Version 0.14.4
Released on April 24, 2018.
- Add ability to specify imports for custom extensions. This provides a way to enable imports of
.cssfiles (which was removed in 3.5.3). Specify--import-extensions .cssto restore the previous behavior. [β #246 by Samuel Colvin]
Version 0.14.3
Released on April 23, 2018.
- libsass upstream follow-up, bestie:
3.5.3β go read the LibSass 3.5.3 release notes.[#244 by Anthony Sottile]π
Version 0.14.2
Released on March 16, 2018.
- libsass upstream follow-up:
3.5.2β peep the LibSass 3.5.2 release notes.[#243 by Anthony Sottile]β¨
Version 0.14.1
Released on March 12, 2018.
- libsass upstream follow-up:
3.5.1β peep the LibSass 3.5.1 release notes.[#242 by Anthony Sottile]π¦
Version 0.14.0
Released on March 6, 2018.
- libsass upstream follow-up:
3.5.0β peep the LibSass 3.5.0 release notes.[#241 by Anthony Sottile]πΈ - The
SassListtype gained an additional optionbracketed=Falseto match the upstream changes to thesass_listtype.[#184 by Anthony Sottile]β slay, compatibility ate. π
Version 0.13.7
Released on February 5, 2018.
- libsass upstream follow-up:
3.4.9β peep the LibSass 3.4.9 release notes.[#232 by Anthony Sottile]β¨
Version 0.13.6
Released on January 19, 2018.
- Not me getting emotional, but
libsass-pythonhas moved to thesassorganization! iconic π
Version 0.13.5
Released on January 11, 2018.
- libsass upstream follow-up:
3.4.8β peep the LibSass 3.4.8 release notes.[#228 by Anthony Sottile]π
Version 0.13.4
Released on November 14, 2017.
- libsass upstream follow-up:
3.4.7β peep the LibSass 3.4.7 release notes.[#226 by Anthony Sottile]π¦
Version 0.13.3
Released on October 11, 2017.
- Sort input files for determinism.
[#212 by Bernhard M. Wiedemann]β yes, we love a deterministic queen. π - Include
LICENSEfile in distributions.[#216 by Dougal J. Sutherland]π - Add a
pysasscentry to replacesassc.[#218 by Anthony Sottile]β¨ - Enable building with dynamic linking.
[#219 by Marcel Plch]π - libsass upstream follow-up:
3.4.6β peep the LibSass 3.4.6 release notes.[#221 by Anthony Sottile]π
Version 0.13.2
Released on June 14, 2017.
- Always add
cwdto import paths.[#208 by Anthony Sottile]β lowkey essential, fr fr. π
Version 0.13.1
Released on June 8, 2017.
- libsass upstream follow-up:
3.4.5β peep the LibSass 3.4.5 release notes.[#207 by Anthony Sottile]β¨
Version 0.13.0
Released on June 7, 2017.
- Use
getfullargspecwhen available in python 3.[#188 by Thom Wiggers]π - Use
sass_copy_c_stringinstead ofstrdupfor portability.[#196 by Anthony Sottile]π - Use
-std=gnu++0xto fix installation under cygwin.[#195 #197 by Anthony Sottile]π οΈ - Correct source map url.
[#201 #202 by Anthony Sottile]πΊοΈ - Remove
--watch.[#203 by Anthony Sottile]β it's gone, periodt. π - libsass upstream follow-up:
3.4.4β peep the LibSass 3.4.4 release notes.[#205 by Anthony Sottile]π
Version 0.12.3
Released on January 7, 2017.
- libsass upstream follow-up:
3.4.3β peep the LibSass 3.4.3 release notes.[#178 by Anthony Sottile]β¨
Version 0.12.2
Released on January 5, 2017.
- libsass upstream follow-up:
3.4.2β peep the LibSass 3.4.2 release notes.[#176 by Anthony Sottile]π¦
Version 0.12.1
Released on December 20, 2016.
- libsass upstream follow-up:
3.4.1β peep the LibSass 3.4.1 release notes.[#175 by Anthony Sottile]π
Version 0.12.0
Released on December 10, 2016.
- libsass upstream follow-up:
3.4.0β peep the LibSass 3.4.0 release notes.[#173 by Anthony Sottile]πΈ
Version 0.11.2
Released on October 24, 2016.
- Drop support for
python2.6.[#158 by Anthony Sottile]β rip, bestie. π - Deprecate
--watch.[#156 by Anthony Sottile]β lowkey a warning, highkey a vibe shift. β οΈ - Preserve line endings.
[#160 by Anthony Sottile]π - libsass upstream follow-up:
3.3.6β peep the LibSass 3.3.6 release notes.[#167 by Anthony Sottile]β¨
Version 0.11.1
Released on April 22, 2016.
- libsass upstream follow-up:
3.3.5β peep the LibSass 3.3.5 release notes.[#148 by Anthony Sottile]π
Version 0.11.0
Released on March 23, 2016.
- libsass upstream follow-up:
3.3.4β peep the LibSass 3.3.4 release notes.[#144 by Anthony Sottile]π¦ - Expose libsass version in
sassc --versionandsass.libsass_version.[β #142 #141 #140 by Anthony Sottile]π - Fix warning about unused enum on switch.
[#127 #131 by Anthony Sottile]π οΈ - Sourcemaps no longer imply source comments.
[#124 #130 by Tim Tisdall]πΊοΈ - Add
--source-commentsoption tosassc.[#124 #130 by Anthony Sottile]β¨ - Improve formatting of
CompileErrorunder python3.[#123 by Anthony Sottile]π - Raise when compiling a directory which does not exist.
[#116 #119 by Anthony Sottile]β no cap, that's a real error. π¨
Version 0.10.1
Released on January 29, 2016.
- libsass upstream follow-up:
3.3.3β peep the LibSass 3.3.3 release notes.[by Anthony Sottile]π - Allow
-tfor style likesassc.[#98 by Anthony Sottile]π
Version 0.10.0
Released on December 15, 2015.
- Support custom import callbacks.
[#81 by Alice ZoΓ« BevanβMcGregor, Anthony Sottile]πͺ - Disallow arbitrary kwargs in
compile().[#109 by Anthony Sottile]π«
Version 0.9.3
Released on December 03, 2015.
- Support
"indented"Sass compilation.[#41 by Alice ZoΓ« BevanβMcGregor]πΈ - Fix wheels on windows.
[#28 #49 by Anthony Sottile]π
Version 0.9.2
Released on November 12, 2015.
- libsass upstream follow-up:
3.3.2β peep the LibSass 3.3.2 release notes.[by Anthony Sottile]β¨ - Require VS 2015 to build on windows.
[#99 by Anthony Sottile]πͺ
Version 0.9.1
Released on October 29, 2015.
- libsass upstream follow-up:
3.3.1β peep the LibSass 3.3.1 release notes.[by Anthony Sottile]π
Version 0.9.0
Released on October 28, 2015.
- Fix a bug with writing UTF-8 to a file.
[#72 by Caleb Ely]π - Fix a segmentation fault on
^C.[#87 by Anthony Sottile]π - libsass upstream follow-up:
3.3.0β peep the LibSass 3.3.0 release notes.[#96 by Anthony Sottile]π¦
Version 0.8.3
Released on August 2, 2015.
- libsass upstream follow-up:
3.2.5β peep the LibSass 3.2.5 release notes.[#79, #80 by Anthony Sottile]β¨ - Fixed a bug that
*.sassfiles were ignored.[#78 by Guilhem MAS-PAITRAULT]β not the*.sassfiles catching strays. π
Version 0.8.2
Released on May 19, 2015.
- libsass upstream follow-up:
3.2.4β peep the LibSass 3.2.3, and 3.2.4 release notes.[#69 by Anthony Sottile]π - The default value of
SassMiddleware'serror_statusparameter was changed from'500 Internal Server Error'to'200 OK'so that Mozilla Firefox can render the error message well.[#67, #68, #70 by zxv]π¦
Version 0.8.1
Released on May 14, 2015.
- Fixed a bug that there was no
'expanded'insass.OUTPUT_STYLESbut'expected'instead which is a typo.[#66 by Triangle717]β a whole typo, bestie. π - Fixed broken FreeBSD build.
[#65 by Toshiharu Moriyama]π οΈ
Version 0.8.0
Released on May 3, 2015.
- libsass upstream follow-up:
3.2.2β peep the LibSass 3.2.0, 3.2.1, and 3.2.2 release notes.[#61, #52, #56, #58, #62, #64 by Anthony Sottile]β¨- Compact and expanded output styles.
[#37]π - Strings and interpolation closer to Ruby Sass. π
- The correctness of the generated sourcemap files. πΊοΈ
- Directive buddling. π¦
- Full support for the
@at-rootdirective. π³ - Full support for
!globalvariable scoping. π
- Compact and expanded output styles.
- Now underscored files are ignored when compiling a directory.
[#57 by Anthony Sottile]π - Fixed broken FreeBSD build.
[#34, #60 by Ilya Baryshev]π οΈ SassMiddlewarebecame to log syntax errors if exist during compilation tosassutils.wsgi.SassMiddlewarelogger with levelERROR.[#42]π¨
Version 0.7.0
Released on March 6, 2015.
Anthony Sottile contributed to the most of this release. Huge thanks to him! main character energy π
- libsass upstream follow-up:
3.1.0β peep the LibSass release note.[#38, #43 by Anthony Sottile]π- Custom functions and imports. πͺ
- Decrementing in
@forloops. π @debugand@error. πnotoperator. π«nth()for maps. πΊοΈinspect(). πfeature-exists(). βunique-id(). πrandom(). π²
- Added custom functions support.
[#13, #44 by Anthony Sottile]π οΈ- Added
sass.SassFunctionclass. π§© - Added
custom_functionsparameter tosass.compile()function. ποΈ - Added data types for custom functions:
sass.SassNumberπ’sass.SassColorπ¨sass.SassListπsass.SassMapπΊοΈsass.SassErrorπ¨sass.SassWarningβ οΈ
- Added
- Added
precisionparameter tosass.compile()function.[#39 by Andrea Stagi]π― sasschas a new-p/--precisionoption.[#39 by Andrea Stagi]β¨
Version 0.6.2
Released on November 25, 2014.
Although 0.6.0--0.6.1 have needed GCC (G++) 4.8+, LLVM Clang 3.3+, now it became back to only need GCC (G++) 4.6+, LLVM Clang 2.9+, or Visual Studio 2013 Update 4+. π§
- libsass upstream follow-up:
3.0.2β peep the libsass release note.[#33 by Rodolphe Pelloux-Prayer]π - Fixed a bug that
sassc --watchcrashed when a file is not compilable on the first try.[#32 by Alan Justino da Silva]π - Fixed broken build on Windows. πͺ
Version 0.6.1
Released on November 6, 2014.
- libsass upstream follow-up:
3.0.1β peep the LibSass release note. β¨ - Fixed a bug that
SassMiddlewarenever closes the socket on some WSGI servers e.g.eventlet.wsgi. π
Version 0.6.0
Released on October 27, 2014.
Note that since libsass-python 0.6.0 (and libsass 3.0) it requires C++11 to compile. Although 0.6.2 became back to only need GCC (G++) 4.6+, LLVM Clang 2.9+, from 0.6.0 to 0.6.1 you need GCC (G++) 4.8+, LLVM Clang 3.3+, or Visual Studio 2013 Update 4+. π
- libsass upstream follow-up:
3.0β peep the LibSass release note. π- Decent extends support. π§¬
- Basic Sass Maps Support. πΊοΈ
- Better UTF-8 Support. π
call()function. π- Better Windows Support. πͺ
- Spec Enhancements. π
- Added missing partial import support.
[#27 by item4]π§© SOURCE_COMMENTSbecame deprecated. β οΈsass.compile()'s parametersource_commentsnow can take onlyboolinstead ofstr. String values like'none','line_numbers', and'map'become deprecated, and will be obsolete soon. π«build_directory()function has a new optional parameteroutput_style. ποΈbuild()method has a new optional parameteroutput_style. π οΈ- Added
--output-style/-soption tobuild_sasscommand.[#25]β¨
Version 0.5.1
Released on September 23, 2014.
- Fixed a bug that
SassMiddlewareyieldedstrinstead ofbyteson Python 3. π - Fixed several Unicode-related bugs on Windows. πͺ
- Fixed a bug that
build_directory(),SassMiddleware, andbuild_sassdon't recursively build subdirectories. π
Version 0.5.0
Released on June 6, 2014.
- libsass upstream follow-up:
2.0β peep the LibSass release note. π - Added indented syntax support (
*.sassfiles). π - Added expanded selector support (BEM). β¨
- Added string functions. π
- Fixed UTF-8 support. π
- Backward incompatibility: broken extends. β οΈ like, that one bites, bestie.
Unstable version 0.4.2.20140529.cd3ee1cbe3
Released on May 29, 2014.
- Version scheme changed to use periods (
.) instead of hyphens (-) due to setuptools seems to treat hyphens special. π - Fixed malformed packaging that doesn't correctly preserve the package name and version.
Unstable Version 0.4.2-20140528-cd3ee1cbe3
Released on May 28, 2014.
- Follow up the libsass upstream:
cd3ee1cbe34d5316eb762a43127a3de9575454ee. π¦
Version 0.4.2
Released on May 22, 2014.
- Fixed build failing on Mac OS X 10.8 or earlier.
[#19] - Fixed
UnicodeEncodeErrorthatManifest.build_one()method rises when the input source contains any non-ASCII Unicode characters. π
Version 0.4.1
Released on May 20, 2014.
- Fixed
UnicodeEncodeErrorthat rise when the input source contains any non-ASCII Unicode characters.
Version 0.4.0
Released on May 6, 2014.
sasschas a new-w/--watchoption. π- Expose source maps support:
sasschas a new-m/-g/--sourcemapoption.SassMiddlewarenow also creates source map files with filenames followed by.mapsuffix.Manifest.build_one()method has a newsource_mapoption. This option builds also a source map file with the filename followed by.mapsuffix.sass.compile()has a new optional parametersource_comments. It can be one ofsass.SOURCE_COMMENTSkeys. It also has a new parametersource_map_filenamewhich is required only whensource_comments='map'.
- Fixed Python 3 incompatibility of
sasscprogram. - Fixed a bug that multiple
include_pathsdoesn't work on Windows.
Version 0.3.0
Released on February 21, 2014.
- Added support for Python 3.3.
[#7] - Dropped support for Python 2.5. π
- Fixed build failing on Mac OS X.
[#4, #5, #6 by Hyungoo Kang] - Now builder creates target recursive subdirectories even if it doesn't exist yet, rather than siliently fails.
[#8, #9 by Philipp Volguine] - Merged recent changes from libsass 1.0.1:
57a2f62--v1.0.1.- Supports variable arguments.
- Supports sourcemaps.
Version 0.2.4
Released on December 4, 2012.
- Added
sasscCLI executable script. - Added
sass.OUTPUT_STYLESconstant map. - Merged recent changes from libsass upstream:
e997102--a84b181.
Version 0.2.3
Released on October 24, 2012.
sassutils.distutils: Prevent double monkey patch of sdist.- Merged upstream changes of libsass.
Version 0.2.2
Released on September 28, 2012.
- Fixed a link error on PyPy and Linux.
- Fixed build errors on Windows.
Version 0.2.1
Released on September 12, 2012.
- Support Windows. πͺβ¨
Version 0.2.0
Released on August 24, 2012.
- Added new
sassutilspackage.- Added
sassutils.buildermodule to build the whole directory at a time. - Added
sassutils.distutilsmodule for distutils and setuptools integration. - Added
sassutils.wsgimodule which provides a development-purpose WSGI middleware.
- Added
- Added
build_sasscommand for distutils/setuptools.
Version 0.1.1
Released on August 18, 2012.
- Fixed segmentation fault for reading filename which does not exist. Now it raises a proper
exceptions.IOErrorexception. π«Ά
Version 0.1.0
Released on August 17, 2012. Initial version. π±
π REFERENCES π
pysassc β SassC compliant command line interface
This provides SassC compliant CLI executable named pysassc:
$ pysassc
Usage: pysassc [options] SCSS_FILE [CSS_FILE]
There are options as well:
-t <style>,--style <style>β Coding style of the compiled result. The same assass.compile()function'soutput_stylekeyword argument. Default isnested.-s <style>,--output-style <style>β Alias for-t/--style. Deprecated since version 0.11.0.-I <dir>,--include-path <dir>β Optional directory path to find@imported (S)CSS files. Can be multiply used.-m,-g,--sourcemapβ Emit source map. Requires the second argument (output CSS filename). The filename of source map will be the output CSS filename followed by.map. New in version 0.4.0.-p,--precisionβ Set the precision for numbers. Default is5. New in version 0.7.0.--source-commentsβ Include debug info in output. New in version 0.11.0.--sourcemap-fileβ Output file for source map. New in version 0.17.0.--sourcemap-contentsβ EmbedsourcesContentin source map. New in version 0.17.0.--sourcemap-embedβ EmbedsourceMappingUrlas data URI. New in version 0.17.0.--omit-sourcemap-urlβ Omit source map URL comment from output. New in version 0.17.0.--sourcemap-rootβ Base path, will be emitted tosourceRootin source-map as is. New in version 0.17.0.-v,--versionβ Prints the program version.-h,--helpβ Prints the help message.
sass β Binding of libsass
This simple C extension module provides a very simple binding of libsass, which is written in C/C++. It contains only one function and one exception type. ngl, minimal queen behavior. π
>>> import sass
>>> sass.compile(string='a { b { color: blue; } }')
'a b {
color: blue; }
'
exception sass.CompileError(msg)
The exception type that is raised by compile(). It is a subtype of exceptions.ValueError.
sass.MODES = frozenset({'dirname', 'filename', 'string'})
(frozenset) The set of keywords compile() can take.
sass.OUTPUT_STYLES = {'compact': 2, 'compressed': 3, 'expanded': 1, 'nested': 0}
(collections.abc.Mapping) The dictionary of output styles. Keys are output name strings, and values are flag integers.
sass.SOURCE_COMMENTS = {'default': 1, 'line_numbers': 1, 'map': 2, 'none': 0}
(collections.abc.Mapping) The dictionary of source comments styles. Keys are mode names, and values are corresponding flag integers.
New in version 0.4.0.
Deprecated since version 0.6.0.
class sass.SassColor(r, g, b, a)
class sass.SassError(msg)
class sass.SassFunction(name, arguments, callable_)
Custom function for Sass. It can be instantiated using from_lambda() and from_named_function() as well.
Parameters
- name (
str) -- the function name - arguments (
collections.abc.Sequence) -- the argument names - callable (
collections.abc.Callable) -- the actual function to be called
New in version 0.7.0.
- classmethod
from_lambda(name, lambda_)β Make aSassFunctionobject from the given lambda_ function. Since lambda functions don't have their name, it need its name as well. Arguments are automatically inspected.- Parameters
- name (
str) -- the function name - lambda (
types.LambdaType) -- the actual lambda function to be called
- name (
- Returns: a custom function wrapper of the lambda_ function
- Return type:
SassFunction
- Parameters
- classmethod
from_named_function(function)β Make aSassFunctionobject from the named function. Function name and arguments are automatically inspected.- Parameters
- function (
types.FunctionType) -- the named function to be called
- function (
- Returns: a custom function wrapper of the function
- Return type:
SassFunction
- Parameters
- property
signatureβ Signature string of the function.
class sass.SassList(items, separator, bracketed=False)
class sass.SassMap(*args, **kwargs)
Because sass maps can have mapping types as keys, we need an immutable hashable mapping type.
New in version 0.7.0.
class sass.SassNumber(value, unit)
class sass.SassWarning(msg)
sass.and_join(strings)
Join the given strings by commas with last ' and ' conjuction.
>>> and_join(['Korea', 'Japan', 'China', 'Taiwan'])
'Korea, Japan, China, and Taiwan'
Parameters
- strings -- a list of words to join
Returns
- a joined string
Return type
str,basestring
sass.compile(**kwargs)
There are three modes of parameters compile() can take: string, filename, and dirname.
The string parameter is the most basic way to compile Sass. It simply takes a string of Sass code, and then returns a compiled CSS string. β¨
Parameters
- string (
str) -- Sass source code to compile. it's exclusive tofilenameanddirnameparameters - output_style (
str) -- an optional coding style of the compiled result. choose one of:'nested'(default),'expanded','compact','compressed' - source_comments (
bool) -- whether to add comments about source lines.Falseby default - source_map_contents (
bool) -- embed include contents in map - source_map_embed (
bool) -- embedsourceMappingUrlas data URI - omit_source_map_url (
bool) -- omit source map URL comment from output - source_map_root (
str) -- base path, will be emitted in source map as is - include_paths (
collections.abc.Sequence) -- an optional list of paths to find@imported Sass/CSS source files - precision (
int) -- optional precision for numbers.5by default. - custom_functions (
set,collections.abc.Sequence,collections.abc.Mapping) -- optional mapping of custom functions. see also below custom functions description - custom_import_extensions -- (ignored, for backward compatibility)
- indented (
bool) -- optional declaration that the string is Sass, not SCSS formatted.Falseby default importers(collections.abc.Callable) β optional callback functions, bestie. see also the importer callbacks description down below π
Returns
the compiled CSS string β¨
Return type
str
Raises
sass.CompileError β when it fails for any reason (like, for example, the given Sass has broken syntax π)
okay so the filename way is the most commonly used one. you hand it a string of a Sass filename and it hands you back a compiled CSS string. iconic behaviour honestly π
Parameters
filename(str) β the filename of Sass source code to compile. it's exclusive to thestringanddirnameparameters πoutput_style(str) β an optional coding style of the compiled result. choose one of:'nested'(default),'expanded','compact','compressed'source_comments(bool) β whether to add comments about source lines.Falseby defaultsource_map_filename(str) β use source maps and indicate the source map output filename.Nonemeans not using source maps.Noneby default.source_map_contents(bool) β embed include contents in mapsource_map_embed(bool) β embedsourceMappingUrlas data URIomit_source_map_url(bool) β omit source map URL comment from outputsource_map_root(str) β base path, will be emitted in source map as isinclude_paths(collections.abc.Sequence) β an optional list of paths to find@imported Sass/CSS source filesprecision(int) β optional precision for numbers. 5 by default.custom_functions(set, collections.abc.Sequence, collections.abc.Mapping) β optional mapping of custom functions. see also the custom functions description down below π«Άcustom_import_extensionsβ (ignored, for backward compatibility)importers(collections.abc.Callable) β optional callback functions. see also the importer callbacks description down below π
Returns
the compiled CSS string, or a pair of the compiled CSS string and the source map string if source_map_filename is set π¦
Return type
str, tuple
Raises
sass.CompileErrorβ when it fails for any reason (for example the given Sass has broken syntax π)exceptions.IOErrorβ when the filename doesn't exist or cannot be read
now the dirname way is the one for automation, fr fr. it takes a pair of paths. the first of the dirname pair refers to the source directory, which contains several Sass source files to be compiled. Sass source files can be nested in directories, no biggie. the second of the pair refers to the output directory where the compiled CSS files get saved. the directory tree structure of the source directory gets maintained in the output directory too, slay. and if the dirname parameter is used, the function returns None. periodt.
Parameters
dirname(tuple) β a pair of(source_dir, output_dir). it's exclusive to thestringandfilenameparameters πoutput_style(str) β an optional coding style of the compiled result. choose one of:'nested'(default),'expanded','compact','compressed'source_comments(bool) β whether to add comments about source lines.Falseby defaultsource_map_contents(bool) β embed include contents in mapsource_map_embed(bool) β embedsourceMappingUrlas data URIomit_source_map_url(bool) β omit source map URL comment from outputsource_map_root(str) β base path, will be emitted in source map as isinclude_paths(collections.abc.Sequence) β an optional list of paths to find@imported Sass/CSS source filesprecision(int) β optional precision for numbers. 5 by default.custom_functions(set, collections.abc.Sequence, collections.abc.Mapping) β optional mapping of custom functions. see also the custom functions description down below πcustom_import_extensionsβ (ignored, for backward compatibility)
Raises
sass.CompileError β when it fails for any reason (for example the given Sass has broken syntax π)
now the custom_functions parameter can take three types of forms, and this is the part where you pick your fighter β¨
set/Sequence of SassFunctions
this is the most general form, bestie. it's pretty verbose, sure, but it can take any kind of callables like type objects, unnamed functions, and user-defined callables. the range?? unmatched.
sass.compile(
...,
custom_functions={
sass.SassFunction('func-name', ('$a', '$b'), some_callable),
...
}
)
Mapping of names to functions
less general, but way easier to use πΈ it's not... ok so it can take any kind of callables β wait, it can take any kind of functions defined using def/lambda syntax. it cannot take callables other than those, because inspecting arguments isn't always available for every kind of callable. lowkey fair.
sass.compile(
...,
custom_functions={
'func-name': lambda a, b: ...,
...
}
)
set/Sequence of named functions
not general, but literally the easiest-to-use form for named functions π
it can take only named functions, defined using def. it cannot take lambdas since names are unavailable for them. rip lambdas.
def func_name(a, b):
return ...
sass.compile(
...,
custom_functions={func_name}
)
newer versions of libsass let developers define callbacks to be called and given a chance to process @import directives. you can define yours by passing in a list of callables via the importers parameter. the callables must be passed as 2-tuples in the form:
(priority_int, callback_fn)
a priority of zero is acceptable, no gatekeeping here; priority determines the order callbacks are attempted π
these callbacks can accept one or two string arguments. the first argument is the path that was passed to the @import directive; the second (optional) argument is the previous resolved path, where the @import directive was found. the callbacks must either return None to indicate the path wasn't handled by that callback (so it continues with the others or falls back on internal libsass filesystem behaviour) or a list of one or more tuples, each in one of three forms:
- A 1-tuple representing an alternate path to handle internally; or,
- A 2-tuple representing an alternate path and the content that path represents; or,
- A 3-tuple representing the same as the 2-tuple with the addition of a
"sourcemap".
all tuple return values must be strings, ok bestie, no shortcuts π as a not-overly-realistic example:
def my_importer(path, prev):
return [(path, '#' + path + ' { color: red; }')]
sass.compile(
...,
importers=[(0, my_importer)]
)
now, within the style source, attempting to @import 'button'; will instead attach color: red as a property of an element with the imported name. the way that works?? obsessed πβ¨
- New in version 0.4.0: Added
source_commentsandsource_map_filenameparameters. - Changed in version 0.6.0: The
source_commentsparameter becomes to take onlyboolinstead ofstr. - Deprecated since version 0.6.0: Values like
'none','line_numbers', and'map'for thesource_commentsparameter are deprecated. - New in version 0.7.0: Added
precisionparameter. - New in version 0.7.0: Added
custom_functionsparameter. - New in version 0.11.0:
source_map_filenameno longer impliessource_comments. - New in version 0.17.0: Added
source_map_contents,source_map_embed,omit_source_map_url, andsource_map_rootparameters. - New in version 0.18.0: The importer callbacks can now take a second argument, the previously-resolved path, so that importers can do relative path resolution.
not me listing every single version bump π but like, the lore matters. keep it.
β¨ sassutils β Additional utilities related to Sass β¨
this package provides several additional utilities related to Sass which depends on the libsass core (the sass module). it's giving bonus content π
π sassutils.builder β Build the whole directory π
class sassutils.builder.Manifest(sass_path, css_path=None, wsgi_path=None, strip_extension=None)
building manifest of Sass/SCSS, bestie π¦
Parameters
sass_path(str, basestring) β the path of the directory that contains Sass/SCSS source filescss_path(str, basestring) β the path of the directory to store compiled CSS filesstrip_extension(bool) β whether to remove the original file extension
build(package_dir, output_style='nested')
builds the Sass/SCSS files in the specified sass_path. it finds sass_path and locates css_path as relative to the given package_dir. very main character of it π
Parameters
package_dir(str, basestring) β the path of package directoryoutput_style(str) β an optional coding style of the compiled result. choose one of:'nested'(default),'expanded','compact','compressed'
Returns
the set of compiled CSS filenames πΈ
Return type
frozenset
okay so real quick β that <code>output_style</code> thing is New in version 0.6.0 bestie, so jot that down π
build_one(package_dir, filename, source_map=False)
Builds one Sass/SCSS file. Just the one. Baby steps π
Parameters
package_dir(str,basestring) β the path of package directoryfilename(str,basestring) β the filename of Sass/SCSS source to compilesource_map(bool) β whether to use source maps. ifTrueit also write a source map to a filename followed by.mapsuffix. default isFalse
Returns β the filename of compiled CSS
Return type β str, basestring
New in version 0.4.0: Added optional source_map parameter.
resolve_filename(package_dir, filename)
Gets a proper full relative path of Sass source and CSS source that will be generated, according to package_dir and filename. It's giving matchmaker energy fr fr π«Ά
Parameters
package_dir(str,basestring) β the path of package directoryfilename(str,basestring) β the filename of Sass/SCSS source to compile
Returns β a pair of (sass, css) path
Return type β tuple
unresolve_filename(package_dir, filename)
Retrieves the probable source path from the output filename. Pass in a .css path to get out a .scss path. reverse uno card π
Parameters
package_dir(str) β the path of the package directoryfilename(str) β the css filename
Returns β the scss filename
Return type β str
sassutils.builder.SUFFIXES = frozenset({'sass', 'scss'})
(frozenset) The set of supported filename suffixes. That's it. That's the whole vibe β¨
sassutils.builder.SUFFIX_PATTERN = re.compile('[.](sass|scss)$')
(re.RegexObject) The regular expression pattern which matches to filenames of supported SUFFIXES. Regex girlies rise πΈ
sassutils.builder.build_directory(sass_path, css_path, output_style='nested', _root_sass=None, _root_css=None, strip_extension=False)
Compiles all Sass/SCSS files in path to CSS. Go big or go home π
Parameters
sass_path(str,basestring) β the path of the directory which contains source files to compilecss_path(str,basestring) β the path of the directory compiled CSS files will gooutput_style(str) β an optional coding style of the compiled result. choose one of:'nested'(default),'expanded','compact','compressed'
Returns β a dictionary of source filenames to compiled CSS filenames
Return type β collections.abc.Mapping
New in version 0.6.0: The output_style parameter.
sassutils.distutils β setuptools/distutils integration π οΈ
This module provides extensions (and some magical monkey-patches, sorry) of the standard distutils and setuptools (now it's named Distribute) for libsass.
To use this, add libsass into setup_requires (not install_requires) option of the setup.py script:
from setuptools import setup
setup(
# ...,
setup_requires=['libsass >= 0.6.0']
)
It will adds build_sass command to the setup.py script:
$ python setup.py build_sass
This commands builds Sass/SCSS files to compiled CSS files of the project and makes the package archive (made by sdist, bdist, and so on) to include these compiled CSS files.
To set the directory of Sass/SCSS source files and the directory to store compiled CSS files, specify sass_manifests option:
from setuptools import find_packages, setup
setup(
name='YourPackage',
packages=find_packages(),
sass_manifests={
'your.webapp': ('static/sass', 'static/css')
},
setup_requires=['libsass >= 0.6.0']
)
The option should be a mapping of package names to pairs of paths, e.g.:
{
'package': ('static/sass', 'static/css'),
'package.name': ('static/scss', 'static')
}
The option can also be a mapping of package names to manifest dictionaries:
{
'package': {
'sass_path': 'static/sass',
'css_path': 'static/css',
'strip_extension': True,
},
}
New in version 0.15.0: Addedstrip_extensionsoa.scssis compiled toa.cssinstead ofa.scss.css. This option will default toTruein the future.
New in version 0.6.0: Added--output-style/-soption tobuild_sasscommand.
class sassutils.distutils.build_sass(dist, **kw)
Builds Sass/SCSS files to CSS files. the main character, obviously π
finalize_options()
Set final values for all the options that this command supports. This is always called as late as possible, ie. after any option assignments from the command-line or from other commands have been done. Thus, this is the place to code option dependencies: if 'foo' depends on 'bar', then it is safe to set 'foo' from 'bar' as long as 'foo' still has the same value it was assigned in 'initialize_options()'.
This method must be implemented by all command classes.
get_package_dir(package)
Returns the directory, relative to the top of the source distribution, where package package should be found (at least according to the package_dir option, if any).
Copied from distutils.command.build_py.get_package_dir() method.
initialize_options()
Set default values for all the options that this command supports. Note that these defaults may be overridden by other commands, by the setup script, by config files, or by the command-line. Thus, this is not the place to code dependencies between options; generally, 'initialize_options()' implementations are just a bunch of "self.foo = None" assignments.
This method must be implemented by all command classes.
run()
A command's raison d'etre: carry out the action it exists to perform, controlled by the options initialized in 'initialize_options()', customized by other commands, the setup script, the command-line, and config files, and finalized in 'finalize_options()'. All terminal output and filesystem interaction should be done by 'run()'.
This method must be implemented by all command classes.
sassutils.distutils.validate_manifests(dist, attr, value)
Verifies that value is an expected mapping of package to sassutils.builder.Manifest. vibe check passed β
sassutils.wsgi β WSGI middleware for development purpose π¦
class sassutils.wsgi.SassMiddleware(app, manifests, package_dir={}, error_status='200 OK')
WSGI middleware for development purpose. Everytime a CSS file has requested it finds a matched Sass/SCSS source file and then compiled it into CSS.
It shows syntax errors in three ways:
Heading comment
The result CSS includes detailed error message in the heading CSS comment e.g.:
/*
Error: invalid property name
*/
Red text in body:before
The result CSS draws detailed error message in :before pseudo-class of body element e.g.:
body:before {
content: 'Error: invalid property name';
color: maroon;
background-color: white;
}
In most cases you could be aware of syntax error by refreshing your working document because it will removes all other styles and leaves only a red text.
logging
It logs syntax errors if exist during compilation to sassutils.wsgi.SassMiddleware logger with level ERROR.
To enable this:
from logging import Formatter, StreamHandler, getLogger
logger = getLogger('sassutils.wsgi.SassMiddleware')
handler = StreamHandler(level=logging.ERROR)
formatter = Formatter(fmt='*' * 80 + '\n%(message)s\n' + '*' * 80)
handler.setFormatter(formatter)
logger.addHandler(handler)
Or simply:
import logging
logging.basicConfig()
Parameters
app(collections.abc.Callable) β the WSGI application to wrapmanifests(collections.abc.Mapping) β build settings. the same format tosetup.pyscript'ssass_manifestsoptionpackage_dir(collections.abc.Mapping) β optional mapping of package names to directories. the same format tosetup.pyscript'spackage_diroption
Changed in version 0.4.0: It creates also source map files with filenames followed by .map suffix.
New in version 0.8.0: It logs syntax errors if exist during compilation tosassutils.wsgi.SassMiddlewarelogger with levelERROR.
static quote_css_string(s)
Quotes a string as CSS string literal. short, sweet, iconic π
CREDIT π
Hong Minhee wrote this Python binding of LibSass.
Hampton Catlin and Aaron Leung wrote LibSass, which is portable C/C++ implementation of Sass.
Hampton Catlin originally designed Sass language and wrote the first reference implementation of it in Ruby.
The above three softwares are all distributed under MIT license.
OPEN SOURCE π
GitHub (Git repository + issues)
https://github.com/sass/libsass-python
Azure Pipelines CI (linux + windows)
https://dev.azure.com/asottile/asottile/_build/latest?definitionId=22&branchName=master
Build Status.
Azure Pipelines Coverage (Test coverage)
https://dev.azure.com/asottile/asottile/_build/latest?definitionId=22&branchName=master
Coverage Status.
PyPI
https://pypi.org/pypi/libsass/
PyPI.
Changelog
changes
β¨ INDICES AND TABLES β¨
okay so if you're the kind of bestie who likes a little map of the docs (valid, iconic behaviour honestly), there's a whole lil navigation squad waiting for you π
genindexβ the general index, aka every single term alphabetised so you can find stuff without scrolling forever π¦modindexβ the module index, for when you're hunting down a specific module and not playing games πΈsearchβ the search page, because sometimes you just gotta type the thing and let the docs do the work β¨
no cap, these are your little shortcuts through the whole documentation forest π
π AUTHOR π
this whole thing was written by Hong Minhee β yes, the Hong Minhee, main character energy fr fr π
π COPYRIGHT π
Copyright Β© 2021, Hong Minhee
like, all of it. respect the craft bestie π«Ά
and that's a wrap on the whole page, we ate and left zero crumbs π β¨
source + version:LIBSASS(1), version0.20.1πΈ β datedOct 16, 2021π
now go forth and compile something gorgeous, you absolute legend π¦π
π¦ where this page comes from
- ubuntu jammy: python3-libsass 0.20.1-3build1 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms