Created
April 3, 2019 08:00
-
-
Save filipecosta90/9b1a8a06e8e0bcf0e646a4a6b5eef6a2 to your computer and use it in GitHub Desktop.
RedisGears CDN Sample imageserver.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
Image Server for our CDN RedisGears Example | |
""" | |
from wand.image import Image | |
def convert_to_format( image_binary, fmt ): | |
converted_bin = None | |
with Image(blob=image_binary) as original: | |
with original.convert(fmt) as converted: | |
converted_bin = converted.make_blob() | |
return converted_bin | |
def compress_quality_to_percent( image_binary, percent ): | |
compressed_bin = None | |
with Image(blob=image_binary) as original: | |
with original.clone() as image: | |
image.compression_quality = percent | |
compressed_bin = image.make_blob() | |
return compressed_bin | |
def builder_format( key_pattern, fmt, origin_field, destination_field ): | |
GearsBuilder()\ | |
.filter(lambda x: execute("type", x["key"]) == "hash" )\ | |
.filter(lambda x: origin_field in x["value"].keys() )\ | |
.filter(lambda x: destination_field not in x["value"].keys() )\ | |
.foreach(lambda x: execute("hset", x["key"], destination_field, convert_to_format(x["value"][origin_field],fmt ) ) )\ | |
.count()\ | |
.register(key_pattern) | |
def builder_compress( key_pattern, percent, origin_field, destination_field ): | |
GearsBuilder()\ | |
.filter(lambda x: execute("type", x["key"]) == "hash" )\ | |
.filter(lambda x: origin_field in x["value"].keys() )\ | |
.filter(lambda x: destination_field not in x["value"].keys() )\ | |
.foreach(lambda x: execute("hset", x["key"], destination_field, compress_quality_to_percent(x["value"][origin_field],percent ) ) )\ | |
.count()\ | |
.register(key_pattern) | |
def builder_timeseries( key_pattern, destination_timeseries, field_name ): | |
GearsBuilder()\ | |
.foreach(lambda x: execute('ts.incrby',destination_timeseries, 1, 'RESET', 1 ) )\ | |
.register(key_pattern) | |
def main(): | |
builder_format( "cdn:*", "PNG", "fetch_format_jpg", "fetch_format_png" ) | |
builder_format( "cdn:*", "JPG", "fetch_format_png", "fetch_format_jpg" ) | |
for img_fmt in ["png","jpg"]: | |
for compression in [60,70,80,90]: | |
builder_compress( "cdn:*", compression, "fetch_format_{fmt}".format(fmt=img_fmt), "fetch_format_{fmt},q_{q}".format(fmt=img_fmt,q=compression) ) | |
builder_timeseries("cdn:*", "size:cdn", "fetch_format_{fmt},q_{q}".format(fmt=img_fmt,q=compression) ) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment