def handleRpcCall(self, messages): for msg in messages: try: call = json.loads(msg) callId = call['id'] except: # pylint: disable=W0702 self.rpcStream.send(json.dumps({'result': None, 'error': 'malformed request'})) try: method = call['method'] _params = call['params'] if method == 'info': result = self.handleInfo() else: raise ValueError('unknown method %s' % method) self.rpcStream.send(json.dumps({'result': result, 'error': None, 'id': callId})) except: # pylint: disable=W0702 self.logException('handling rpc message') errClass, errObject = sys.exc_info()[:2] errText = '%s.%s: %s' % (errClass.__module__, errClass.__name__, str(errObject)) self.rpcStream.send(json.dumps({'result': None, 'error': errText, 'id': callId}))
def handleRpcCall(self, messages): for msg in messages: try: call = json.loads(msg) callId = call['id'] except: # pylint: disable=W0702 self.rpcStream.send(json.dumps({'result': None, 'error': 'malformed request'})) try: method = call['method'] _params = call['params'] if method == 'info': result = self.handleInfo() else: raise ValueError('unknown method %s' % method) self.rpcStream.send(json.dumps({'result': result, 'error': None, 'id': callId})) except: # pylint: disable=W0702 errClass, errObject, errTB = sys.exc_info()[:3] errText = '%s.%s: %s' % (errClass.__module__, errClass.__name__, str(errObject)) logging.warning(''.join(traceback.format_tb(errTB))) logging.warning(errText) logging.warning('while handling rpc message: %s', msg) self.rpcStream.send(json.dumps({'result': None, 'error': errText, 'id': callId}))
def editImage0(self, request, uuid, template): img = self.defaultImageModel.objects.get(uuid = uuid) ajax = request.POST.has_key('ajax') if request.method == 'POST': form = EditImageForm(request.POST, instance=img) if form.is_valid(): # FIX: update map, etc! updatedObject = form.save() if ajax: return HttpResponse(json.dumps({'result': updatedObject.getGeoJson()}), mimetype='application/json') else: if ajax: return HttpResponse(json.dumps({'error': {'code': -32099, 'message': 'invalid value in form field', 'data': form._get_errors()} }), mimetype='application/json') else: form = EditImageForm(instance=img) return (render_to_response (template, dict(img=img, form=form), context_instance = RequestContext(request)))
def mapSetSetsJson(request): obj = [dict(url=s.get_absolute_url(), viewUrl=s.getViewUrl(), name=s.name, author=s.author.username) for s in MapSet.objects.all()] return HttpResponse(json.dumps(obj), mimetype='application/json')
def jsonResponse(x, raw=False): if isinstance(x, basestring) or raw: text = x else: text = json.dumps(x, sort_keys=True, indent=4) return HttpResponse(text, mimetype='application/json; charset=UTF-8')
def xml2json(inName, outName): struct = xml2dict(inName) outText = json.dumps(struct, indent=4, sort_keys=True) if outName == '-': print outText else: file(outName, 'w').write(outText)
def mapSetView(request, userName, shortName): mapset = get_object_or_404(MapSet, author__username=userName, shortName=shortName) settingsFields = ('GEOCAM_MAP_SET_DISABLE_MAPS',) settingsObj = dict(((f, getattr(settings, f)) for f in settingsFields)) settingsJson = json.dumps(settingsObj, indent=4, sort_keys=True) return render_to_response('geocamMapSet/mapSetEdit.html', {'mapset': mapset, 'settingsJson': settingsJson}, context_instance=RequestContext(request))
def write(self, obj): pathDir = os.path.dirname(self.path) if not os.path.exists(pathDir): os.makedirs(pathDir) text = json.dumps(obj, indent=4, sort_keys=True) tmpPath = self.path + '.tmp' out = open(tmpPath, 'wb') out.write(text) out.close() # atomic overwrite to avoid any chance of corrupted file os.rename(tmpPath, self.path)
def statusBoardAnnouncementsJSON(request): announcementList = StatusboardAnnouncement.objects.\ filter(visible=True).order_by('-dateCreated') jsonList = [] for announcement in announcementList: jsonList.append({'id': announcement.id, 'priority': announcement.priority, 'visible': announcement.visible, 'dateCreated': announcement.dateCreated.isoformat() + 'Z', 'content': announcement.content, 'utcDateCreated': announcement.dateOfAnnouncement.isoformat() + 'Z', }) stuff = json.dumps(jsonList) return HttpResponse(stuff, content_type='text/plain')
def getExportSettings(self): exportedVars = ['SCRIPT_NAME', 'MEDIA_URL', 'DATA_URL', 'GEOCAM_AWARE_GALLERY_PAGE_COLS', 'GEOCAM_AWARE_GALLERY_PAGE_ROWS', 'GEOCAM_CORE_GALLERY_THUMB_SIZE', 'GEOCAM_CORE_DESC_THUMB_SIZE', 'GEOCAM_AWARE_MAP_BACKEND', 'GEOCAM_AWARE_USE_MARKER_CLUSTERING', 'GEOCAM_AWARE_USE_TRACKING'] exportDict = dict(((f, getattr(settings, f)) for f in exportedVars)) return json.dumps(exportDict)
def editImage0(self, request, imgId, template): img = self.defaultImageModel.objects.get(id=imgId) ajax = 'ajax' in request.POST if request.method == 'POST': form = EditImageForm(request.POST, instance=img) if form.is_valid(): updatedObject = form.save() if ajax: return HttpResponse(json.dumps({'result': updatedObject.getGeoJson()}), mimetype='application/json') else: if ajax: return HttpResponse(json.dumps({'error': {'code': -32099, 'message': 'invalid value in form field', 'data': form._get_errors()} }), mimetype='application/json') else: form = EditImageForm(instance=img) return render(request, template, dict(img=img, form=form), )
def getSubsystemGroupJson(): # gets the json of all active subsystems subsystemStatusDict = {} subsystemGroups = SubsystemGroup.objects.all() for subsystemGroup in subsystemGroups: subsystemStatusDict[subsystemGroup.name] = [] subsystems = Subsystem.objects.filter(group = subsystemGroup) for subsystem in subsystems: if subsystem.active: try: subsystemStatus = subsystem.getStatus() except: continue if subsystemStatus: subsystemStatusDict[subsystemGroup.name].append(subsystemStatus) subsystemStatusJson = json.dumps(subsystemStatusDict, indent=4, sort_keys=True) return subsystemStatusJson
def getServerDatetimeJSON(request): timestamp = datetime.utcnow() times = getMultiTimezones(timestamp) result = [] for name, time, _color in times: datedict = {'dayName': time.strftime("%a"), 'monthName': time.strftime("%b"), 'month': time.month, 'day': time.day, 'year': time.year, 'shortyear': timestamp.strftime("%y"), 'hour': time.strftime("%H"), 'hour12': time.strftime("%I"), 'ampm': time.strftime("%p"), 'min': time.strftime("%M"), 'sec': time.strftime("%S"), 'zone': name} result.append(datedict) datejson = json.dumps(result) return HttpResponse(datejson, content_type='application/json')
def statusBoardSchedule(request): eventList = StatusboardEvent.objects.\ filter(visible=True).filter(completed=False).order_by('dateOfEvent') #siteTimeOffset = datetime.timedelta(hours = settings.REMOTE_TIMEZONE_OFFSET) localTimes = [e.dateOfEvent.strftime("%m/%d/%Y %H:%M:%S") for e in eventList] siteTimeOffset = 0 siteTimes = [e.dateOfEvent + siteTimeOffset for e in eventList] eventsPlusSiteTimes = zip(eventList, siteTimes) schedHtml = render_to_response("xgds_status_board/schedule.html", {'eventList': eventList, 'eventsPlusSiteTimes': eventsPlusSiteTimes, 'STATUS_BOARD_TIMEZONES': settings.STATUS_BOARD_TIMEZONES, 'STATUS_BOARD_DATE_TIMEZONE': settings.STATUS_BOARD_DATE_TIMEZONE, }, context_instance=RequestContext(request)) resultDict = {'schedHtml': schedHtml.content, 'localTimes': localTimes, 'dateCount': eventList.count()} resultJson = json.dumps(resultDict) resp = HttpResponse(resultJson, content_type='application/json') return resp
def get_db_prep_value(self, value, connection=None, prepared=False): return json.dumps(value.__dict__)
def jsonFormErrorsResponse(form): errorDict = dict(((k, v) for k, v in form.errors.iteritems())) return HttpResponseBadRequest(json.dumps({'error': errorDict}, sort_keys=True, indent=4), mimetype='application/json; charset=UTF-8')
def jsonErrorResponse(error): return HttpResponseBadRequest(json.dumps({'error': error}, sort_keys=True, indent=4), mimetype='application/json; charset=UTF-8')
def announceConnect(self, moduleName, params): logging.info('module %s connected', moduleName) self.injectStream.send('central.connect.%s:%s' % (moduleName, json.dumps(params)))
def djangoHandler(topic, body): obj = json.loads(body) dataText = json.dumps([obj['data']]) modelInstance = self.deserializer(dataText)[0] return handler(topic, modelInstance)
def djangoHandler(topicPrefix, body): obj = json.loads(body) dataText = json.dumps([obj['data']]) modelInstance = list(self.deserializer(dataText))[0] return handler(topicPrefix, modelInstance.object)
def announceDisconnect(self, moduleName): logging.info('module %s disconnected', moduleName) self.injectStream.send('central.disconnect.%s:%s' % (moduleName, json.dumps({'timestamp': str(getTimestamp())})))
def get_db_prep_value(self, value, connection=None, prepared=False): if value is None: return value return json.dumps(value, separators=',:')
def __repr__(self): return json.dumps(self.__dict__, indent=4, sort_keys=True)
def getExportSettings(): exportDict = dict(((f, getattr(settings, f)) for f in EXPORT_SETTINGS)) return json.dumps(exportDict, indent=4, sort_keys=True)
def writeResponse(self, response): self.write_message('zmqProxy.response:' + json.dumps(response))
def dumps(obj): if settings.DEBUG: return json.dumps(obj, indent=4, sort_keys=True) # pretty print else: return json.dumps(obj, separators=(',',':')) # compact
def dumps(obj): return json.dumps(obj, sort_keys=True, indent=4)
def dumps(self, obj): if 1: return json.dumps(obj, indent=4, sort_keys=True) # pretty print for debugging else: return json.dumps(obj, separators=(',',':')) # compact
def sendJson(self, topic, obj): if isinstance(obj, dict): obj.setdefault('module', self.moduleName) obj.setdefault('timestamp', str(getTimestamp())) self.sendRaw(topic, json.dumps(obj))
def handleMessagePretty(topic, obj): print topic print json.dumps(obj, sort_keys=True, indent=4)