Skip to content

Instantly share code, notes, and snippets.

@zehome
Last active December 21, 2015 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zehome/6341211 to your computer and use it in GitHub Desktop.
Save zehome/6341211 to your computer and use it in GitHub Desktop.
Enable cross request for graphite/gunicorn

Create this file in your graphite installation directory: lib/python2.7/site-packages/graphite/crossmiddleware.py

import re
 
from django.utils.text import compress_string
from django.utils.cache import patch_vary_headers
 
from django import http
 
try:
    import settings 
    XS_SHARING_ALLOWED_ORIGINS = settings.XS_SHARING_ALLOWED_ORIGINS
    XS_SHARING_ALLOWED_METHODS = settings.XS_SHARING_ALLOWED_METHODS
except:
    XS_SHARING_ALLOWED_ORIGINS = '*'
    XS_SHARING_ALLOWED_METHODS = ['POST','GET','OPTIONS', 'PUT', 'DELETE']
 
 
class XsSharing(object):
    """
        This middleware allows cross-domain XHR using the html5 postMessage API.
         
 
        Access-Control-Allow-Origin: http://foo.example
        Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE
    """
    def process_request(self, request):
 
        if 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META:
            response = http.HttpResponse()
            response['Access-Control-Allow-Origin']  = XS_SHARING_ALLOWED_ORIGINS 
            response['Access-Control-Allow-Methods'] = ",".join( XS_SHARING_ALLOWED_METHODS ) 
            
            return response
 
        return None
 
    def process_response(self, request, response):
        # Avoid unnecessary work
        if response.has_header('Access-Control-Allow-Origin'):
            return response
 
        response['Access-Control-Allow-Origin']  = XS_SHARING_ALLOWED_ORIGINS 
        response['Access-Control-Allow-Methods'] = ",".join( XS_SHARING_ALLOWED_METHODS )
 
        return response

And add the middleware to settings:

echo MIDDLEWARE_CLASSES += ('crossmiddleware.XsSharing',) >> lib/python2.7/site-packages/graphite/settings.py

restart gunicorn ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment