def wrapper(self, request, room_id, *args, **kwargs): """ Check if browser is attempting to subscribe to an event stream. """ if request.META.get('HTTP_ACCEPT') == 'text/event-stream': set_hold_stream(request, self._stream_name(room_id)) return HttpResponse(content_type='text/event-stream') return view_func(self, request, room_id, *args, **kwargs)
def item(request, headline_id): h = get_object_or_404(Headline, pk=headline_id) if request.wscontext: ws = request.wscontext if ws.is_opening(): ws.accept() ws.subscribe('headline-%s' % headline_id) while ws.can_recv(): message = ws.recv() if message is None: ws.close() break return HttpResponse() elif request.method == 'GET': if request.META.get('HTTP_ACCEPT') == 'text/event-stream': resp = HttpResponse(content_type='text/event-stream') set_hold_stream(resp, 'headline-%s' % headline_id) return resp else: wait = request.META.get('HTTP_WAIT') if wait: wait = int(wait) if wait < 1: wait = None if wait > 300: wait = 300 inm = request.META.get('HTTP_IF_NONE_MATCH') etag = '"%s"' % calendar.timegm(h.date.utctimetuple()) if inm == etag: resp = HttpResponseNotModified() if wait: set_hold_longpoll(resp, 'headline-%s' % headline_id, timeout=wait) else: resp = _json_response(h.to_data()) resp['ETag'] = etag return resp elif request.method == 'PUT': hdata = json.loads(request.read()) h.type = hdata['type'] h.title = hdata.get('title', '') h.text = hdata.get('text', '') h.save() hdata = h.to_data() hjson = json.dumps(hdata) etag = '"%s"' % calendar.timegm(h.date.utctimetuple()) rheaders = {'ETag': etag} hpretty = json.dumps(hdata, indent=4) + '\n' formats = list() formats.append(HttpResponseFormat(body=hpretty, headers=rheaders)) formats.append(HttpStreamFormat('event: update\ndata: %s\n\n' % hjson)) formats.append(WebSocketMessageFormat(hjson)) publish('headline-%s' % headline_id, formats) resp = _json_response(hdata) resp['ETag'] = etag return resp else: return HttpResponseNotAllowed(['GET', 'PUT'])
def item(request, headline_id): h = get_object_or_404(Headline, pk=headline_id) if request.wscontext: ws = request.wscontext if ws.is_opening(): ws.accept() ws.subscribe(headline_id) while ws.can_recv(): message = ws.recv() if message is None: ws.close() break return HttpResponse() elif request.method == 'GET': if request.META.get('HTTP_ACCEPT') == 'text/event-stream': resp = HttpResponse(content_type='text/event-stream') set_hold_stream(request, headline_id) return resp else: wait = request.META.get('HTTP_WAIT') if wait: wait = int(wait) if wait < 1: wait = None if wait > 300: wait = 300 inm = request.META.get('HTTP_IF_NONE_MATCH') etag = '"%s"' % calendar.timegm(h.date.utctimetuple()) if inm == etag: resp = HttpResponseNotModified() if wait: set_hold_longpoll(request, headline_id, timeout=wait) else: resp = _json_response(h.to_data()) resp['ETag'] = etag return resp elif request.method == 'PUT': hdata = json.loads(request.read()) h.type = hdata['type'] h.title = hdata.get('title', '') h.text = hdata.get('text', '') h.save() hdata = h.to_data() hjson = json.dumps(hdata) etag = '"%s"' % calendar.timegm(h.date.utctimetuple()) rheaders = {'Content-Type': 'application/json', 'ETag': etag} hpretty = json.dumps(hdata, indent=4) + '\n' formats = list() formats.append(HttpResponseFormat(body=hpretty, headers=rheaders)) formats.append(HttpStreamFormat('event: update\ndata: %s\n\n' % hjson)) formats.append(WebSocketMessageFormat(hjson)) publish(headline_id, formats) resp = _json_response(hdata) resp['ETag'] = etag return resp else: return HttpResponseNotAllowed(['GET', 'PUT'])
def todos(request, list_id): if request.method == 'OPTIONS': resp = HttpResponse() resp['Access-Control-Max-Age'] = '3600' return resp if request.method == 'HEAD': last_cursor = TodoItem.get_last_cursor(list_id) resp = HttpResponse() resp['Link'] = _changes_link(list_id, last_cursor.cur) return resp elif request.method == 'GET': stream = request.GET.get('stream') after = request.GET.get('after_change') wait = request.META.get('HTTP_WAIT') if stream: stream = (stream == 'true') if wait: wait = int(wait) if stream: set_hold_stream(request, Channel('todos-%s' % list_id)) return HttpResponse(content_type='text/plain') else: if after: try: items, last_cursor = TodoItem.get_after(list_id, after) except TodoItem.DoesNotExist: return HttpResponseNotFound() else: items, last_cursor = TodoItem.get_all(list_id) resp = _list_response(list_id, items) resp['Link'] = _changes_link(list_id, last_cursor.cur) if len(items) == 0 and wait: set_hold_longpoll(request, Channel('todos-%s' % list_id, prev_id=last_cursor.cur), timeout=wait) return resp elif request.method == 'POST': params = json.loads(request.body) i = TodoItem(list_id=list_id) if 'text' in params: i.text = params['text'] if 'completed' in params: if not isinstance(params['completed'], bool): return HttpResponseBadRequest('completed must be a bool\n', content_type='text/plain') i.completed = params['completed'] try: cursor = i.save() except TodoItem.LimitError: return HttpResponseForbidden('limit reached\n', content_type='text/plain') if cursor.cur != cursor.prev: _publish_item(list_id, i, cursor) resp = _item_response(i, status=201) resp['Location'] = reverse('todos-item', args=[list_id, i.id]) return resp else: return HttpResponseNotAllowed(['HEAD', 'GET', 'POST'])
def messages(request): # The wscontext property is set by the django-grip middleware if the # request is related to a WebSocket session. if request.wscontext: ws = request.wscontext if ws.is_opening(): # Accept all new connections, subscribe them to a channel, and # send a welcome message. ws.accept() ws.subscribe('messages') ws.send('Welcome to the Test API') # Handle any messages in the request. while ws.can_recv(): m = ws.recv() if m is None: # The recv() function returns None if the WebSocket # connection was closed. In that case, we'll acknowledge # by closing as well. ws.close() break # Relay incoming message to listeners. publish_message(m) # Since the request was related to a WebSocket session, the # django-grip middleware will override whatever we return here. # However, we still have to return a valid object in order to # satisfy Django. return HttpResponse() # If we get here, then the request was not related to a WebSocket # session and we should treat it like a regular request. if request.method == 'GET': # Set the request to hold open as a stream, subscribed to a # channel. set_hold_stream(request, 'messages') # Return the initial response for the stream. The django-grip # middleware will ensure that additional instructions are # included in the response, so that the proxy knows to hold # the connection open. return HttpResponse('Welcome to the Test API\n', content_type='text/plain') else: return HttpResponseNotAllowed(['GET'])
def stream(req, inbox_id): if req.method == 'GET': try: db.inbox_get(inbox_id) except redis_ops.InvalidId: return HttpResponseBadRequest('Bad Request: Invalid id\n') except redis_ops.ObjectDoesNotExist: return HttpResponseNotFound('Not Found\n') except: return HttpResponse('Service Unavailable\n', status=503) set_hold_stream(req, grip_prefix + 'inbox-%s' % inbox_id) return HttpResponse('[opened]\n', content_type='text/plain') else: return HttpResponseNotAllowed(['GET'])
def board(request, board_id): if request.method == 'GET': try: board = Board.get(board_id) except ObjectDoesNotExist: return HttpResponseNotFound('Not Found\n') accept = request.META['HTTP_ACCEPT'] if accept: accept = accept.split(',')[0].strip() if accept == 'text/event-stream': set_hold_stream(request, str(board_id)) return HttpResponse(content_type='text/event-stream') else: players = Player.get_top_for_board(board, limit=5) return _board_response(board, players) else: return HttpResponseNotAllowed(['GET'])
def events(request, topic): set_hold_stream(request, topic) return HttpResponse(content_type='text/event-stream')
def home(request): body = ''.join(reversed(r.lrange('bufs', 0, -1))) set_hold_stream(request, 'audio') return HttpResponse(body, content_type='audio/mpeg')