Source

appengine-cdn / mcdn / utils.py

import os, re
from datetime import datetime, timedelta

from google.appengine.api import images

import flask
from flask import request

import werkzeug


def get_mimetype(name, default='text/plain'):
    import mimetypes
    (mimetype, _) = mimetypes.guess_type(name)
    if not mimetype:
        mimetype = default
    return mimetype


def make_response(content, mimetype=None, name=None):
    if hasattr(content, 'content') and hasattr(content, 'mimetype'):
        file = content
        format = '%a, %d %b %Y %H:%M:%S'

        etag_match = False
        date_match = False

        if 'HTTP_IF_NONE_MATCH' in request.environ:
            if request.environ['HTTP_IF_NONE_MATCH'] == file.etag:
                etag_match = True

        if 'HTTP_IF_MODIFIED_SINCE' in request.environ:
            since = request.environ['HTTP_IF_MODIFIED_SINCE']
            modified_date = file.upload_date.strftime(format)
            if modified_date == since:
                date_match = True

        if etag_match and date_match:
            response = flask.make_response(file.content)
            response.status_code = 302
        else:
            response = flask.make_response(file.content)

        response.mimetype = file.mimetype

        expires = file.upload_date + timedelta(days=365)
        modified = file.upload_date

        response.headers['Etag'] = file.etag
        response.headers['Last-Modified'] = modified.strftime(format)
        response.headers['Expires'] = expires.strftime(format)
        response.headers['Cache-Control'] = 'public, max-age=31536000'
        response.headers['Age'] = '14'
    else:
        if not mimetype and not name:
            raise ValueError("Can't guess mimetype without filename")

        if not mimetype:
            mimetype = get_mimetype(name)

        response = flask.make_response(content)
        response.mimetype = mimetype

    return response


_image_exts = (
    '.jpe',
    '.jpeg',
    '.jpg',
    '.png',
    '.gif',
    '.bmp',
    '.tif',
    '.ico',
)

def is_image_name(name):
    ext = os.path.splitext(name)[1]
    return ext in _image_exts


def parse_size(size):
    m = re.match(r'(\d+)x(\d+)(b|c)?', size)
    if not m:
        raise ValueError("Size must be in format 100x100, 100x100! or 100x100>")
    return (int(m.group(1)), int(m.group(2)), m.group(3))


def subdomain():
    host = request.environ['HTTP_HOST']
    return host.split('.', 1)[0]


def abort(status_code, description=None, **kwargs):
    try:
        flask.abort(status_code, description)
    except werkzeug.exceptions.HTTPException, exc:
        exc.__dict__.update(kwargs)
        raise