Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 74bf994ef4
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 79 lines (57 sloc) 2.109 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
import sys
import time
import logging
import json

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from bs4 import BeautifulSoup

from django.conf import settings


fresh = False


class RefreshEventHandler(FileSystemEventHandler):

    def on_any_event(self, event):
        global fresh
        ACCEPTED_EXTENSIONS = getattr(settings, 'FRESH_ACCEPTED_EXTENSIONS', [
            '.py',
            '.html',
            '.js',
            '.css',
        ])
    
        for extension in ACCEPTED_EXTENSIONS:
            if event.src_path.lower().endswith(extension):
                fresh = True


class FreshMiddleware(object):

    def process_response(self, request, response):
        if not settings.DEBUG:
            return response

        global fresh
        mimetype = response._headers['content-type'][1]
        IGNORED_PAGES = getattr(settings, 'FRESH_IGNORED_PAGES', [
            '/admin/',
            '/admin_keywords_submit/',
        ])
        ignored = False

        for ignored_page in IGNORED_PAGES:
            if request.path.lower().startswith(ignored_page):
                ignored = True

        if not ignored:
            if mimetype == 'application/json':
                items = json.loads(response.content)
                if fresh and items.get('fresh') != None:
                    fresh = False
                    items['fresh'] = True
                    response.content = json.dumps(items)
            elif mimetype == 'text/html; charset=utf-8':
                soup = BeautifulSoup(response.content)
                script_fresh = soup.new_tag('script', src='/static/fresh/js/refresher.js')
                soup.head.append(script_fresh)
                response.content = soup.prettify()

        return response


    def watcher(self):
        observer = Observer()

        path = settings.SITE_ROOT
        event_handler = RefreshEventHandler()
        observer.schedule(event_handler, path, recursive=True)

        observer.start()

    def __init__(self):
        if settings.DEBUG:
            self.watcher()

Something went wrong with that request. Please try again.