def get_redact_notes(request): request_user = basicauth_get_user_by_emailaddr(request) if not request_user: logevent(request, 'ActivityLog.create POST', 401, jv3.utils.decode_emailaddr(request)) response = HttpResponse( JSONEncoder().encode( {'autherror': "Incorrect user/password combination"}), "text/json") response.status_code = 401 return response ## Filter out notes that have already been redacted notes = Note.objects.filter( owner=request_user).order_by("-created").exclude(jid=-1).exclude( contents="") numNotes = len(notes) userRedactedNotes = RedactedNote.objects.filter(owner=request_user) for redactedNote in userRedactedNotes: notes = notes.exclude(version=redactedNote.version, jid=redactedNote.jid) pass numNotesLeft = len(notes) ndicts = [extract_zen_notes_data(note) for note in notes] allNotes = [] for note in ndicts: allNotes.append({ "jid": note['jid'], "version": note['version'], "contents": note['noteText'], "deleted": note['deleted'], "created": str(note['created']), "edited": str(note['edited']) }) resultMap = { 'markAsRemoved': {}, 'markAsName': {}, 'markAsPassword': {}, 'markAsPhone': {} } redactedWordArray = WordMap.objects.filter(owner=request_user) for wMap in redactedWordArray: if wMap.wordType in resultMap: resultMap[wMap.wordType][wMap.privWord] = True pass userMeta = { 'userPoints': "0", 'totalNotes': str(numNotes), 'numNotesLeft': str(numNotesLeft) } response = HttpResponse( JSONEncoder().encode({ 'notes': allNotes, 'wordMapIndices': resultMap, 'userMeta': userMeta }), "text/json") response.status_code = 200 return response
def find_locations_in_radius(request): """ Determines the coordinates of the input address and finds all active locations within the specified radius. The results are returned as a JSON object. """ # This view should only be requested via an HTTP POST + XHR request if not (request.method == 'POST' and request.is_ajax()): raise Http404 json = JSONEncoder() # snag some needed info from the request address = request.POST.get('address', '') radius = float(request.POST.get('radius', 25)) try: # TODO: figure out how to make this better when more than one result # is retrieved coords = utils.get_coordinates(address=address) except StopIteration: # this happens if no matches were found err = {'error': 'Please enter a valid location!'} return render_to_response('reploc/json.js', {'json': json.encode(err)}) lat1, lng1 = float(coords[0]), float(coords[1]) # put stuff into a dictionary data = {'center': { 'address': address, 'lat': lat1, 'lng': lng1 }, 'locations': []} # this number is used a lot. I'm not math wiz, so I have no idea what it's # used for, but my guess is that it has something to do with trig (which I # conveniently skipped in school) C = 57.2958 # iterate over all active locations for location in Location.objects.active(): lat2, lng2 = location.coordinates # check the distance between the center and the location # source: http://www.meridianworlddata.com/Distance-Calculation.asp dist = 3963.189 * acos(sin(lat1 / C) * sin(lat2 / C) + cos(lat1 / C) \ * cos(lat2 / C) * cos(lng2 / C - lng1 / C)) # if the location is within the radius of the input address, add it to # our collection if dist <= radius: data['locations'].append(jsonify_location(location)) # send everything back as a JSON object return render_to_response('reploc/json.js', {'json': json.encode(data)}, mimetype='text/javascript')
def get_json_notes(request): request_user = basicauth_get_user_by_emailaddr(request) if not request_user: logevent(request, 'ActivityLog.create POST', 401, jv3.utils.decode_emailaddr(request)) response = HttpResponse( JSONEncoder().encode( {'autherror': "Incorrect user/password combination"}), "text/json") response.status_code = 401 return response ## Filter out notes that have already been redacted notes = _filter_dupes( request_user.note_owner.filter(deleted=0).order_by("-created")) ndicts = [extract_zen_notes_data(note) for note in notes] allNotes = [] for note in ndicts: allNotes.append({ "jid": note['jid'], "version": note['version'], "contents": note['noteText'], "deleted": note['deleted'], "created": str(note['created']), "edited": str(note['edited']) }) allNotes.sort(lambda x, y: cmp(x['created'], y['created'])) response = HttpResponse(JSONEncoder().encode({"notes": allNotes}), "text/json") response.status_code = 200 return response
def get_locations(request): """ Retrieves all locations for all active representatives and returns the collection as a JSON object. """ locations = Location.objects.active() json = JSONEncoder() data = {'locations': [jsonify_location(l) for l in locations]} return render_to_response('reploc/json.js', {'json': json.encode(data)}, mimetype='text/javascript')
def default(self, obj): if isinstance(obj, QuerySet): # `default` must return a python serializable # structure, the easiest way is to load the JSON # string produced by `serialize` and return it return loads(serialize('json', obj)) return JSONEncoder.default(self,obj)
def get_iphone(request): request_user = basicauth_get_user_by_emailaddr(request) if not request_user: logevent(request, 'ActivityLog.create POST', 401, jv3.utils.decode_emailaddr(request)) response = HttpResponse( JSONEncoder().encode( {'autherror': "Incorrect user/password combination"}), "text/json") response.status_code = 401 ## removed semi-colon?? return response notes = sort_user_notes(request_user) numNotes = len(notes) startIndex = int(request.GET.get("START_INDEX", 0)) endIndex = int(request.GET.get("END_INDEX", None)) if not endIndex: endIndex = numNotes notesLeft = numNotes - endIndex ndicts = [ extract_zen_notes_data(note) for note in notes[startIndex:endIndex] ] deltaIndex = endIndex - startIndex htmlblob = "\n".join([ "<li><div name='note' style='overflow:hidden;' id='%(jid)s' edited='%(edited)s' created='%(created)s' version='%(version)s' deleted='%(deleted)s' pk='%(pk)s' onClick='gid(\"%(jid)s\").blur(); zenNoteView.noteClicked(\"%(jid)s\")'><pre>%(noteText)s</pre></div></li>" % n for n in ndicts ]) # onBlur='zenNoteView.noteBlur(\"%(jid)s\")' if notesLeft > 0: ## height:25px was in style for new notes (=2 lines visible without pre tags) htmlblob += "<li><div id='reqMore'><button id='requestMore' onClick='zenAjax.requestMore()'>Get %s of %s more notes</button></div></li>" % ( min(deltaIndex, notesLeft), notesLeft) response = HttpResponse(htmlblob, 'text/html') response.status_code = 200 return response
def __init__(self, source, options={}, attrs={}, func_display=False): """source can be a list containing the autocomplete values or a string containing the url used for the XHR request. For available options see the autocomplete sample page:: http://jquery.bassistance.de/autocomplete/""" self.source = source self.func_display = func_display if len(options) > 0: #self.options = JSONEncoder().encode(options) opt_list = [] for k, v in options.items(): opt = '"%s":' % k if k == 'select': opt += v elif type(v) == types.StringType: opt += '"%s"' % v else: opt += JSONEncoder().encode(v) opt_list.append(opt) self.options = '{%s}' % (','.join(opt_list)) self.attrs.update(attrs)
def default(self, obj): # if it's a NoneType, return "" if type(obj) is types.NoneType: return Objectify("") # if it's a queryset, it's easy if isinstance(obj, QuerySet): return [Objectify(o) for o in obj] # maybe it's a normal object try: return JSONEncoder.default(self, obj) except TypeError, e: # maybe it's a Django object with an obj() method try: return obj.obj() except AttributeError: # maybe it's a Django object without an obj() method try: return loads(serialize('json', [obj])) # OK, I give up except Exception, e: return None
def default_getstate(obj): try: return obj.__getstate__() except AttributeError: # TODO: Fix this, must raise exception somehow from django.utils.simplejson import JSONEncoder return JSONEncoder.default(None, obj)
def default(self, obj): if isinstance(obj, datetime.datetime) or isinstance(obj, datetime.date): return obj.isoformat() if isinstance(obj, object): return dict(filter(lambda (x,y): not x.startswith('_'), obj.__dict__.items())) return JSONEncoder.default(self, obj)
def get_active_users(request): """ Retrieves a list of active users which is returned as plain JSON for easier manipulation with JavaScript. """ if request.is_ajax(): active = Visitor.objects.active().reverse() now = datetime.now() # we don't put the session key or IP address here for security reasons try: data = {'users': [{ 'id': v.id, #'user': uc(v.user), 'user_agent': uc(v.user_agent), 'referrer': uc(v.referrer), 'url': uc(v.url), 'page_views': v.page_views, 'geoip': v.geoip_data_json, 'last_update': (now - v.last_update).seconds, 'friendly_time': ', '.join(friendly_time((now - v.last_update).seconds)), } for v in active]} except: log.error('There was a problem putting all of the visitor data together:\n%s\n\n%s' % (traceback.format_exc(), locals())) return HttpResponse(content='{}', mimetype='text/javascript') response = HttpResponse(content=JSONEncoder().encode(data), mimetype='text/javascript') response['Content-Length'] = len(response.content) return response # if the request was not made via AJAX, raise a 404 raise Http404
def report(req): g = req.GET # check that the required fields # were all provided, or raise try: sc = g["sc"] qx_num = int(g["qx"]) qy_num = int(g["qy"]) except KeyError: return HttpResponse("Required fields: sc, qx, qy", content_type="text/plain", status=400) except ValueError: return HttpResponse("Invalid question number(s)", content_type="text/plain", status=400) # resolve the section code into a Section # object, question numbers into Questions section = Section.objects.get(code=sc) qx = section.questions.get(number=qx_num) qy = section.questions.get(number=qy_num) # fetch and check the # values of optional fields qx_type = getattr(Answer, g.get("tx", "str").upper()) qy_type = getattr(Answer, g.get("ty", "str").upper()) # find all of the submissions which have answers # to both question-x and question-y. if either # are missing, we can't draw any correlation, # so omit the data altogether submissions = [(subm, subm.answers.get(question__number=qx_num), subm.answers.get(question__number=qy_num)) for subm in Submission.objects.filter(section__code=sc) if subm.answers.filter( question__number__in=[qx_num, qy_num]).count() == 2] graph_data = [(ans_x.normalized(qx_type), ans_y.normalized(qy_type)) for subm, ans_x, ans_y in submissions] graph_data_json =\ JSONEncoder().encode( graph_data) return render_to_response( req, "questions/report.html", { "graph_data": graph_data_json, "submissions": submissions, "question_x": qx, "question_y": qy }) return HttpResponse("subm: %r\nans: %r" % (list(submissions), list(answers)), content_type="text/plain")
def default(self, obj): if isinstance(obj, datetime.datetime): return unicode(obj) if isinstance(obj, ValuesQuerySet): return list(obj) if isinstance(obj, QuerySet): return loads(serialize('json', obj)) return JSONEncoder.default(self, obj)
def _handle_max_log_request(self, user, clientid): ## return the max id (used by the client to determine which recordsneed to be retrieved.) maxdate, count = self._get_max_helper(user, clientid) print " returning ", maxdate, count return HttpResponse(JSONEncoder().encode({ 'value': long(maxdate), 'num_logs': long(count) }))
def default(self, obj): if isinstance(obj, datetime.datetime): return obj.strftime('%Y-%m-%d %H:%M:%S') if isinstance(obj, datetime.date): return obj.strftime('%Y-%m-%d') if isinstance(obj, object): return obj.__dict__ return JSONEncoder.default(self, obj)
def dailyCounts(request,set,relevant_date_accessor): counts = {} for i in range(set.count()): item = set[i] day = int(int(relevant_date_accessor(item))/(24*60*60*1000.0))*24*60*60*1000 counts[day] = counts.get(day,0) + 1; response = HttpResponse(JSONEncoder().encode(counts), "text/json") response.status_code = 200; return response
def read(self,request): request_user = authenticate_user(request); if not request_user: return self.responder.error(request, 401, ErrorDict({"autherror":"Incorrect user/password combination"})) if (request.GET['type'] == 'get_max_log_id'): clientid = self._get_client(request) ## "what is the last thing i sent?" try: return self._handle_max_log_request(request_user,clientid); except: print sys.exc_info() logging.error(str(sys.exc_info())) return HttpResponse(JSONEncoder().encode({'value':0, 'num_logs':0})) ## retrieve the entire activity log ## return self.responder.list(Event.objects.filter(owner=request_user), qs_user) return HttpResponse(JSONEncoder().encode([]), self.responder.mimetype)
def default(self, obj): if isinstance(obj, QuerySet): # `default` must return a python serializable # structure, the easiest way is to load the JSON # string produced by `serialize` and return it return loads(serialize('json', obj)) if isinstance(obj, models.Model): return dict([(attr, getattr(obj, attr)) for attr in [f.name for f in obj._meta.fields]]) return JSONEncoder.default(self, obj)
def getJSONData(self, model_list, sEcho, total_records): data = {"sEcho": sEcho, "iTotalRecords": total_records, "iTotalDisplayRecords": total_records} item = [] for model in model_list: item.append(model.to_dict()) data.update({"aaData": item}) jsonstr = JSONEncoder().encode(data) return jsonstr
def get_zen(request): iphone = True request_user = basicauth_get_user_by_emailaddr(request) if not request_user: logevent(request, 'ActivityLog.create POST', 401, jv3.utils.decode_emailaddr(request)) response = HttpResponse( JSONEncoder().encode( {'autherror': "Incorrect user/password combination"}), "text/json") response.status_code = 401 ## removed semi-colon?? return response notes = sort_user_notes(request_user) startIndex = int(request.GET.get("START_INDEX", 0)) noteLength = len(notes) endIndex = int(request.GET.get("END_INDEX", -1)) if endIndex == -1: iphone = False endIndex = noteLength additionalNotesWaiting = True if iphone and (endIndex >= noteLength): additionalNotesWaiting = False ## make magic happen ndicts = [ extract_zen_notes_data_extras(note) for note in notes[startIndex:endIndex] ] deltaIndex = endIndex - startIndex iconType = request.GET.get("ICON", 'none') if iconType == 'X': ## For zen site ##print "Called from /zen/ site" htmlblob = "\n".join([ "<div class='note' name='%(archiveState)s' style='display:%(startVisibility)s'><img class='deleteX' src='x.png' alt='Delete' onClick='zenNoteAjax.saveEditedNote(\"%(jid)s\", true)'/> <textarea name='note' id='%(jid)s' edited='%(edited)s' created='%(created)s' version='%(version)s' deleted='%(deleted)s' pk='%(pk)s' onFocus='zenNoteView.noteClicked(\"%(jid)s\")' cols='%(col)s' rows='%(row)s' hasFocus='false' hasSelect='false' onBlur='zenNoteView.noteBlur(\"%(jid)s\")' style='overflow:hidden'>%(noteText)s</textarea></div>" % n for n in ndicts ]) else: ## For tags site ##print "Called from /tags/ site" htmlblob = "\n".join([ "<div class='note' name='%(archiveState)s' style='display:%(startVisibility)s'><img class='deleteX' src='arrow-left.png' alt='Delete' onMouseOver='zenNoteView.dispNoteOptions(\"%(jid)s\", true)' onmouseout=\"zenNoteView.noteOptions.startTimer();\"/> <textarea name='note' id='%(jid)s' edited='%(edited)s' created='%(created)s' version='%(version)s' deleted='%(deleted)s' pk='%(pk)s' onFocus='zenNoteView.noteClicked(\"%(jid)s\")' cols='%(col)s' rows='%(row)s' hasFocus='false' hasSelect='false' onBlur='zenNoteView.noteBlur(\"%(jid)s\")' style='overflow:hidden'>%(noteText)s</textarea></div>" % n for n in ndicts ]) if iphone and additionalNotesWaiting: htmlblob += "\n <button id='requestMore' onClick='zeniPhone.requestMore()'>Get %s more notes</div>" % ( deltaIndex) elif iphone: htmlblob += "\n <button id='requestMore' style='display:none' onClick='zeniPhone.requestMore()'>Get %s more notes</div>" % ( deltaIndex) response = HttpResponse(htmlblob, 'text/html') response.status_code = 200 return response
def post_json_chrome_logs(request): """ Record Chrome usage logs, return timestamp of last log recorded. """ request_user = basicauth_get_user_by_emailaddr(request) if not request_user: logevent(request, 'post_json_chrome_logs POST', 401, jv3.utils.decode_emailaddr(request)) response = HttpResponse( JSONEncoder().encode( {'autherror': "Incorrect user/password combination"}), "text/json") response.status_code = 401 return response payload = JSONDecoder().decode(request.raw_post_data) logs = payload timestamp = 0 for log in logs: # Save each log, keep track of latest log's timestamp. # keys: time, action, noteid (>0 or -10), info (JSON string) # ext only: tabid (chrome ext tab), url (of focused tab) entry = ChromeLog() entry.owner = request_user entry.when = log['time'] timestamp = max(entry.when, timestamp) entry.action = log['action'] entry.noteid = log.get("noteid", None) entry.info = log.get("info", None) entry.url = log.get("url", None) entry.tabid = log.get("tabid", None) ## added in new rev entry.save() ## Return Response! response = HttpResponse( JSONEncoder().encode({ "lastTimeRecorded": timestamp, }), "text/json") response.status_code = 200 return response
def create_fake_complete_movie(request): """ INPUT : None OUTPUT : Create_Fake_Movie_WF's """ wf = Create_Fake_Movie_WF({}, None) result = wf.work() return HttpResponse(JSONEncoder().encode(", ".join([result["status"], str(result["already-existed"]), str(result["time-to-serve"])])))
def render_js(self, field_id): if isinstance(self.source, list): source = JSONEncoder().encode(self.source) elif isinstance(self.source, str): source = "'%s'" % escape(self.source) else: raise ValueError('source type is not valid') options = '' if self.options: options += ',%s' % self.options return u"""jQuery('#%s').autocomplete(%s%s);""" % (field_id, source, options)
def get_survey(request): # generates a personalized survey based on the contents of survey import jv3.study.survey cookie = request.GET['cookie'] (user, registration) = get_user_and_registration_from_cookie(cookie, request) if not user: print "no such user from cookie %s " % request.GET['cookie'] response = render_to_response('/500.html') response.status_code = 500 return response questions = [] survey = jv3.study.survey.get_survey_for_user(user) if not survey: print "no survey for user %s " % repr(user) response = render_to_response('/404.html') response.status_code = 404 return response for q in survey: questions.append(q) if q.has_key("qid") and len( jv3.models.SurveyQuestion.objects.filter(user=user, qid=q["qid"])) == 0: ## allocate a placeholder in the database to store our result q_model = jv3.models.SurveyQuestion() q_model.qid = q["qid"] q_model.user = user q_model.response = "" q_model.save() elif q.has_key("qid"): for sq in jv3.models.SurveyQuestion.objects.filter(user=user, qid=q["qid"]): q['response'] = sq.response else: ## textual pass return HttpResponse( get_template("jv3/surveyform.html").render({}) % { 'email': user.email, 'first_name': registration.first_name, 'last_name': registration.last_name, 'server': settings.SERVER_URL, 'cookie': cookie, 'questions': unicode(JSONEncoder().encode(questions)) }, "text/html")
def default(self, obj): if isinstance(obj, QuerySet): # `default` must return a python serializable # structure, the easiest way is to load the JSON # string produced by `serialize` and return it return loads(serialize('json', obj)) if isinstance(obj, models.Model): #do the same as above by making it a queryset first set_obj = [obj] set_str = serialize('json', set_obj) #eliminate brackets in the beginning and the end str_obj = set_str[1:len(set_str)-2] return str_obj return JSONEncoder.default(self,obj)
def __init__(self, source, options={}, attrs={}): """source can be a list containing the autocomplete values or a string containing the url used for the XHR request. For available options see the autocomplete sample page:: http://jquery.bassistance.de/autocomplete/""" self.options = {'matchContains': 'true', 'minChars': '2'} self.attrs = {'autocomplete': 'off'} self.source = source if len(options) > 0: self.options = JSONEncoder().encode(options) self.attrs.update(attrs)
def read(self, request): request_user = basicauth_get_user_by_emailaddr(request) if not request_user: logevent(request, 'ActivityLog.read', 401, {"requesting user:"******"autherror": "Incorrect user/password combintion"})) clientid = self._get_client(request) if (request.GET['type'] == 'get_max_log_id'): ## "what is the last thing i sent?" try: return self._handle_max_log_request(request_user, clientid) except: print sys.exc_info() logging.error(str(sys.exc_info())) return HttpResponse(JSONEncoder().encode({ 'value': 0, 'num_logs': 0 })) return HttpResponse(JSONEncoder().encode([]), self.responder.mimetype)
def get_detailed_infos_for_movie(request): """ INPUT : movie-id OUTPUT : Get_Detailed_Infos_For_Movie_Model_WF's output """ start = datetime.now() if request.method == "GET": HttpResponse("POST excepted") details_wf = Get_Detailed_Infos_For_Movie_Model_WF(request.POST, None) result = details_wf.work() result["time-to-serve"] += datetime.now() - start # return render_to_response("template_url", JSONEncoder().encode(str(result))) return HttpResponse(JSONEncoder().encode(str(result)))
def default(self, obj): """ Transform obj into a serializable object """ if isinstance(obj, QuerySet): return list(obj) elif obj.__class__.__name__=='Pin' or obj.__class__.__name__=='User': return obj.__dict__ elif isinstance(obj, datetime.datetime): return {'year':obj.year,'month':obj.month,'day': obj.day} elif isinstance(obj, Model): d=obj.__dict__ del d['_state'] return d return JSONEncoder.default(self,obj)
def __init__(self, source, options={}, attrs={}): """source can be a list containing the autocomplete values or a string containing the url used for the XHR request. For available options see the autocomplete sample page:: http://jquery.bassistance.de/autocomplete/ http://www.djangosnippets.org/snippets/233/""" self.options = None self.attrs = {'autocomplete': 'off'} self.source = source if len(options) > 0: self.options = JSONEncoder().encode(options) self.attrs.update(attrs)
def list_ajax(request, query, limit): users = request.user.get_permitted_objects("LIST", Contact).filter( Q(username__startswith=query) | Q(surname__istartswith=query) | Q(name__istartswith=query) | Q(mail__istartswith=query))[:limit] users = [{ 'id': user.id, 'label': "%s (%s)" % (user.username, ("%s %s" % (user.name, user.surname)).strip()), 'value': user.username } for user in users] return HttpResponse(JSONEncoder().encode(users), mimetype='application/json')
def __init__(self, source, options={}, attrs={}): """source can be a list containing the autocomplete values or a string containing the url used for the XHR request. For available options see the autocomplete sample page:: sources: http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/ demo: http://jquery.bassistance.de/autocomplete/ """ self.options = None self.attrs = {'autocomplete': 'on'} self.source = source if len(options) > 0: self.options = JSONEncoder().encode(options) self.attrs.update(attrs)
def default(self, obj): if isinstance(obj, QuerySet): # `default` must return a python serializable # structure, the easiest way is to load the JSON # string produced by `serialize` and return it return serialize('python', obj) if isinstance(obj, models.Model): # do the same as above by making it a queryset first set_obj = [obj] set_str = serialize('python', set_obj) return set_str[0] if isinstance(obj, datetime.datetime): return time.mktime(obj.timetuple()) if isinstance(obj, datetime.date): return time.mktime(obj.timetuple()) return JSONEncoder.default(self, obj)
def render(self, name, value, attrs=None): if value is None: value = '' value = smart_unicode(value) final_attrs = self.build_attrs(attrs, name=name) self.mce_settings['elements'] = "id_%s" % name mce_json = JSONEncoder().encode(self.mce_settings) # Print script head once per instance if self.print_head: head = load_javascript(TINYMCE_JS) else: head = u'' return mark_safe(u'''<textarea%s>%s</textarea> %s <script type="text/javascript">tinyMCE.init(%s)</script>''' % (flatatt(final_attrs), escape(value), head, mce_json))
def render(self, name, value, attrs=None): if value is None: value = '' if sys.version_info[0] == 2: from django.utils.encoding import smart_unicode value = smart_unicode(value) final_attrs = self.build_attrs(attrs, name=name) self.mce_settings['elements'] = "id_%s" % name mce_json = JSONEncoder().encode(self.mce_settings).replace("\"function", "function").replace("}\"", "}") return mark_safe(u'''<div%s>%s</div> <script type="text/javascript"> tinyMCE.init(%s); setTimeout(function () { $("#%s").focus(); }, 500); </script>''' % (flatatt(final_attrs), value, mce_json, self.mce_settings['elements']))
def dailyCounts2(request,set,field_name): # counts by issuing lots of queries ins sequences counts = {} datemin = int(set.order_by(field_name)[0].__getattribute__(field_name)) datemax = int(time.mktime(time.localtime())*1000) ## datemax = set.order_by("-%s"%field_name)[0].__getattribute__(field_name) ## print set.order_by("-%s"%field_name)[0] while datemin < datemax: ##print "datemin %s datemax %s " % (repr(time.ctime(datemin)),repr(time.ctime(datemax))) # print set.filter(**{""+field_name+"__gt":datemin,""+field_name+"__lt":datemax}).count() nextday = int(datemin) + 24*60*60*1000 counts[datemin] = set.filter(**{""+field_name+"__gt":datemin,""+field_name+"__lt":nextday}).count() datemin = nextday ## 24*60*60*1000 ## plus one day response = HttpResponse(JSONEncoder().encode(counts), "text/json") response.status_code = 200; return response
def calendar_day_json(request, year, month, day): date = datetime.strptime("%s-%s-%s" % (year, month, day), "%Y-%m-%d") list_hour_registrations = HourRegistration.objects.filter( date=date, creator=Core.current_user()) registrations = [{ 'id': reg.id, 'time_start': reg.time_start, 'time_end': reg.time_end, 'hours': str(reg.hours), 'order': reg.order.id, 'type': str(reg.type.id), 'customer_name': reg.get_customer_name(), 'order_name': reg.get_order_name(), 'description': reg.description } for reg in list_hour_registrations] return HttpResponse(JSONEncoder().encode(registrations), mimetype='application/json')
def detail_data(request, id): if not check_user_login(request): return login(request) user = request.session.get('user') budget = BudgetService().getBudget(id, user) if budget: budgetdetail_list = BudgetService().getBudgetDetailList(budget) filter_dict = { 'happentime >=': budget.begindate, 'happentime <=': budget.enddate } moneystat = MoneyService().getMoneyStat(filter_dict, budget.currency, user) for budgetdetail in budgetdetail_list: BudgetService().updateBudgetDetailActualMoney( budgetdetail, moneystat) jsondata = BudgetService().encode(budgetdetail_list) return HttpResponse(JSONEncoder().encode(jsondata)) else: return HttpResponse('')
def misc_json(request): allNotes = [] notes = RedactedNote.objects.all().order_by('created') notes.reverse() for note in notes: allNotes.append({ "type": "Note", "label": note.noteType, "contents": note.contents }) pass print 1 types = {"Note": {'pluralLabel': "Notes"}} print 2 response = HttpResponse( JSONEncoder().encode({ 'types': types, 'items': allNotes }), "text/json") response.status_code = 200 return response
def calendar_json(request, year, month): year = int(year) month = int(month) date = datetime.strptime("%s-%s-%s" % (year, month, 1), "%Y-%m-%d") NOW = datetime.now() CURRENT_WEEK = date.isocalendar()[1] cal_month = calendar.monthcalendar(year, month) temp_cal = [] #Build for week in cal_month: hours_count = 0 for day in week: if int(day) > 0: day_date = datetime.strptime( "%s-%s-%s" % (year, month, int(day)), "%Y-%m-%d") for reg in HourRegistration.objects.filter( date=day_date, creator=Core.current_user()): hours_count += float(reg.hours) if NOW == date: temp_cal.append((CURRENT_WEEK, day, "day today", hours_count)) elif (day > 0): temp_cal.append((CURRENT_WEEK, day, "day", hours_count)) else: temp_cal.append((CURRENT_WEEK, day, "", hours_count)) hours_count = 0 if CURRENT_WEEK == 52: CURRENT_WEEK = 0 CURRENT_WEEK += 1 return HttpResponse(JSONEncoder().encode(temp_cal), mimetype='application/json')
def default(self, o): if isinstance(o, Student): return o.__json__() return JSONEncoder.default(self, o)
def default(self, o): if isinstance(o, Bunch): return [o.objects, o.center] else: return JSONEncoder.default(self, o)
def default( self, obj ): if isinstance( self, QuerySet ): return loads( serializers.serialize( 'json', obj )) return JSONEncoder.default( self, obj )
def default(self, obj): if isinstance(obj, QuerySet): return loads(serialize('json', obj, use_natural_keys=True)) return JSONEncoder.default(self, obj)
def default(self, obj): if isinstance(obj, QuerySet): return [jsonify_model(o) for o in obj] if isinstance(obj, Model): return jsonify_model(obj) return JSONEncoder.default(self, obj)
def default(self, obj): ty = type(obj) if ty is datetime: return obj.strftime('%Y-%m-%d %H:%M:%S') else: return JSONEncoder.default(self, obj)