1import datetime 2import time 3 4from django.utils.timezone import get_current_timezone 5from django.core.urlresolvers import get_script_prefix 6from django.http import HttpResponse 7from django.shortcuts import render_to_response, get_object_or_404 8from pytz import timezone 9 10from graphite.util import json 11from graphite.events import models 12from graphite.render.attime import parseATTime 13 14 15def to_timestamp(dt): 16 return time.mktime(dt.timetuple()) 17 18 19class EventEncoder(json.JSONEncoder): 20 def default(self, obj): 21 if isinstance(obj, datetime.datetime): 22 return to_timestamp(obj) 23 return json.JSONEncoder.default(self, obj) 24 25 26def view_events(request): 27 if request.method == "GET": 28 context = { 'events' : fetch(request), 29 'slash' : get_script_prefix() 30 } 31 return render_to_response("events.html", context) 32 else: 33 return post_event(request) 34 35def detail(request, event_id): 36 e = get_object_or_404(models.Event, pk=event_id) 37 context = { 'event' : e, 38 'slash' : get_script_prefix() 39 } 40 return render_to_response("event.html", context) 41 42 43def post_event(request): 44 if request.method == 'POST': 45 event = json.loads(request.body) 46 assert isinstance(event, dict) 47 48 values = {} 49 values["what"] = event["what"] 50 values["tags"] = event.get("tags", None) 51 values["when"] = datetime.datetime.fromtimestamp( 52 event.get("when", time.time())) 53 if "data" in event: 54 values["data"] = event["data"] 55 56 e = models.Event(**values) 57 e.save() 58 59 return HttpResponse(status=200) 60 else: 61 return HttpResponse(status=405) 62 63def get_data(request): 64 if 'jsonp' in request.REQUEST: 65 response = HttpResponse( 66 "%s(%s)" % (request.REQUEST.get('jsonp'), 67 json.dumps(fetch(request), cls=EventEncoder)), 68 mimetype='text/javascript') 69 else: 70 response = HttpResponse( 71 json.dumps(fetch(request), cls=EventEncoder), 72 mimetype="application/json") 73 return response 74 75def fetch(request): 76 #XXX we need to move to USE_TZ=True to get rid of naive-time conversions 77 def make_naive(dt): 78 if 'tz' in request.GET: 79 tz = timezone(request.GET['tz']) 80 else: 81 tz = get_current_timezone() 82 local_dt = dt.astimezone(tz) 83 if hasattr(local_dt, 'normalize'): 84 local_dt = local_dt.normalize() 85 return local_dt.replace(tzinfo=None) 86 87 if request.GET.get("from", None) is not None: 88 time_from = make_naive(parseATTime(request.GET["from"])) 89 else: 90 time_from = datetime.datetime.fromtimestamp(0) 91 92 if request.GET.get("until", None) is not None: 93 time_until = make_naive(parseATTime(request.GET["until"])) 94 else: 95 time_until = datetime.datetime.now() 96 97 tags = request.GET.get("tags", None) 98 if tags is not None: 99 tags = request.GET.get("tags").split(" ") 100 101 return [x.as_dict() for x in 102 models.Event.find_events(time_from, time_until, tags=tags)] 103