Skip to content

Instantly share code, notes, and snippets.

@Slater-Victoroff
Created September 4, 2014 13:08
Show Gist options
  • Save Slater-Victoroff/a39c2d41139c45814f78 to your computer and use it in GitHub Desktop.
Save Slater-Victoroff/a39c2d41139c45814f78 to your computer and use it in GitHub Desktop.
JS/CSS minification in python
import requests
import json
import urllib
URLS = {
'css': 'http://cssminifier.com/raw',
'js': 'http://javascript-minifier.com/raw'
}
def new_filepath(filepath):
"""
Returns a new filepath for the minified object
"""
split_path = filepath.rpartition('/')
file_split = split_path[-1].rpartition('.')
return '%s%s%s.min.%s' % (split_path[0], split_path[1], file_split[0], file_split[-1])
def minify(filepath):
"""
Minifies a css or js file passed to it
"""
url = URLS[filepath.rpartition('.')[-1]]
data = urllib.urlencode({'input': open(filepath, 'r').read()})
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
mini = requests.post(
URLS[filepath.rpartition('.')[-1]] + '?%s' % data,
data=data,
headers=headers
).content
new_filename = new_filepath(filepath)
with open(new_filename, 'w') as sink:
sink.write(mini)
if __name__ == "__main__":
minify('test.js')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment