def add_tag(req, person_stub='', tag='', category_slug='', is_ajax=False, redirect_to_tags_page=False): """ adds a tag to a user if they do not have tagging turned off """ if req.method == 'POST': if tag == '': tag = req.POST.get('tag', '').strip() if category_slug == '': category_slug = req.POST.get('tag_category_slug', '').strip() if tag == '': return json_response({'error': 'Please enter a tag that is not blank.'}) elif person_stub == '': return json_response({'error': 'Person not found.'}) person = Person.objects.get(stub=person_stub) # make sure tag does not already exist try: taggeditem = TaggedItem.objects.get( tag_category__slug=category_slug, object_id=person.id, tag__name__iexact=tag) except Exception: taggeditem = add_tags(person, tag, category_slug, req.user, 'person') person.expire_cache() expire_cache_group('tags') url = reverse('staff_directory:person', args=[person.stub]) if person.user != req.user: email_info = EmailInfo( subject='You were tagged in the staff directory!', text_template='staff_directory/email/user_tagged.txt', html_template='staff_directory/email/user_tagged.html', to_address=person.user.email, ) # set notification title = '%s %s tagged you with "%s"' % \ (req.user.first_name, req.user.last_name, tag) Notification.set_notification(req.user, req.user, "tagged", tag, person.user, title, url, email_info) if is_ajax: if redirect_to_tags_page: return json_response({'redirect': reverse('staff_directory:show_by_tag', args=[taggeditem.tag.slug])}) return json_response({'redirect': reverse('staff_directory:person', args=[person.stub])}) else: return HttpResponseRedirect(reverse('staff_directory:person', args=[person.stub]))
def test_wrap_httpresponse(self): testresp = HttpResponse('foo') def testfun(request): return testresp respfun = json_response(testfun) self.assertEqual(respfun(HttpRequest()), testresp)
def system_status(request): status = {} for name, label in models.Status.NAME_CHOICES: status[name] = models.Status.GetValue(name) return json_response(status)
def search_results_json(req, term='', context_models=''): all_results = [] term = req.GET.get('term', '') context_models = req.GET.get('model', '').split(',') p = {} indexes = sorted( _get_indexes(), key=lambda index: 0 if index[0].__name__.lower() in context_models else index[1].PRIORITY) for index in indexes: results = SearchQuerySet().filter(content=term).models(index[0]) results_count = results.count() for r in results[:5]: all_results.append( _create_category(r.display, r.index_name, term, r.model_name, r.url, results_count)) all_results.append({ 'category': 'Wiki', 'term': term, 'search_slug': 'wiki' }) return json_response(all_results)
def search_results_json(req, term='', context_models=''): all_results = [] term = req.GET.get('term', '') context_models = req.GET.get('model', '').split(',') p = {} indexes = sorted(_get_indexes(), key=lambda index: 0 if index[0].__name__.lower() in context_models else index[1].PRIORITY) for index in indexes: results = SearchQuerySet().filter(content=term).models(index[0]) results_count = results.count() for r in results[:5]: all_results.append(_create_category(r.display, r.index_name, term, r.model_name, r.url, results_count)) all_results.append({'category': 'Wiki', 'term': term, 'search_slug': 'wiki'}) return json_response(all_results)
def car_pc_service(request): user_name = request.POST['user_name'] password = request.POST['password'] models.Settings.SetValue(models.Settings.SERVICE_USER_NAME, user_name) models.Settings.SetValue(models.Settings.SERVICE_USER_PASSWORD, password, encrypt_it=True) return json_response('Ok')
def add_result(request): car = request.user.core_user.car value = request.POST['value'] sensor_pid = request.POST['sensor_pid'] result_dt = request.POST['result_dt'] params = { 'sensor_id': sensor_pid, 'car': car, 'value': value, 'result_dt': result_dt, } if models.SensorResult.objects.filter(**params).exists(): return json_response("Already same result exists.") else: models.SensorResult.objects.create(**params) return json_response("Ok")
def wrap(request, *args, **kwargs): person = Person.objects.get(stub=request.POST.get('person_stub')) if person.user == request.user or person.allow_tagging: return f(request, *args, **kwargs) else: errMsg = person.user.first_name + " " + person.user.last_name + " has chosen not to allow tagging." return json_response({'error': errMsg})
def test_wrap_plain_function(self): def testfun(request): return ['bla'] respfun = json_response(testfun) result = respfun(HttpRequest) self.assertIsInstance(result, HttpResponse) self.assertEqual(result['content-type'], 'text/json') self.assertEqual(json.loads(respfun(HttpRequest()).content), ['bla'])
def add_entry(request): """ Add a new blank entry to the book """ #Return HttpResponseForbidden here as cleaner code? and elsewhere... if not request.is_ajax(): return HttpResponseForbidden() if request.method != 'POST': return json_response({'success': False, 'error': 'wrong method'}) form = NewEntryForm(request.POST) if form.is_valid(): book = Book.objects.get(id=int(request.POST['book_id'])) entry = Entry(title=form.cleaned_data['title'], book=book) entry.save() url = entry.get_absolute_url() return json_response({'success': True, 'url': url}) else: return json_response({'success': False, 'error': 'missing argument'})
def setUp(self): def testfun(_, messages, userinfo): messages['success'] = True return {'messages': messages, 'user': userinfo.username} self.user = User.objects.create( username='******', email='*****@*****.**', password=_HASHED_DEFAULT_PASSWORD, token='testtoken') self.wrapped = api_token_required(json_response(testfun)) self.request = HttpRequest() self.request.method = 'POST'
def inner(request, *args, **kwargs): # for demonstration purpose, use plain username/password # in reality, this should be an API key or key/secret username = request.META.get("HTTP_API_USER") password = request.META.get("HTTP_API_USER_PASS") user = authenticate(username=username, password=password) if user: request.user = user return function(request, *args, **kwargs) else: return json_response({'error': _('Invalid account')})
def test_wrap_plain_function(self): def testfun(request): return ['bla'] respfun = json_response(testfun) result = respfun(HttpRequest) self.assertIsInstance(result, HttpResponse) self.assertEqual(result['content-type'], 'text/json') self.assertEqual( json.loads(respfun(HttpRequest()).content), ['bla'] )
def start_upload(request): if 'start' in request.POST: uploading = models.Status.GetValue(models.Status.VIDEO_UPLOAD_STARTED) if uploading == '1': return json_response("Already uploading") # start upload models.Status.SetValue(models.Status.VIDEO_UPLOAD_STARTED, '1') models.Command.objects.create(command=models.Command.START_VIDEO_UPLOAD) capturing = models.Status.GetValue(models.Status.VIDEO_STARTED) if capturing == '1': # restart capturing models.Status.SetValue(models.Status.VIDEO_STARTED, '0') time.sleep(1) # start video models.Status.SetValue(models.Status.VIDEO_STARTED, '1') return json_response("Started")
def users_by_division_json(req): result = {} divisions = OrgGroup.objects.filter(parent=None).exclude( title__icontains="Region").order_by('title') for d in divisions: result[d.title] = User.objects.filter(is_active=True).filter( Q(person__org_group=d) | Q(person__org_group__parent=d)).order_by( 'last_name', 'first_name').count() result_json = [] for k in result.keys(): result_json.append({'name': k, 'value': result[k]}) return json_response(result_json)
def start_upload(request): if 'start' in request.POST: uploading = models.Status.GetValue(models.Status.VIDEO_UPLOAD_STARTED) if uploading == '1': return json_response("Already uploading") # start upload models.Status.SetValue(models.Status.VIDEO_UPLOAD_STARTED, '1') models.Command.objects.create( command=models.Command.START_VIDEO_UPLOAD) capturing = models.Status.GetValue(models.Status.VIDEO_STARTED) if capturing == '1': # restart capturing models.Status.SetValue(models.Status.VIDEO_STARTED, '0') time.sleep(1) # start video models.Status.SetValue(models.Status.VIDEO_STARTED, '1') return json_response("Started")
def tags(request): """ Get exhaustive list of Tags for published Posts :return: tags [LIST] list of Post tags """ # Grab all published Posts post_query = Post.query(ancestor=get_blog_key()).filter(Post.published == True) # Remove duplicates tags = list(set(flatten_list([post.tags for post in post_query.iter()]))) return json_response(tags)
def search_tags_json(req, term='', model=''): if req.method == 'POST': term = req.POST.get('term', '').strip() return HttpResponseRedirect(reverse('search:tags_json', args=[term, ])) elif req.method == 'GET': if term.strip() == '': term = req.GET.get('term', '').strip() q = _get_query(term, ['name', ]) results = Tag.objects.filter(q) if model: # join with taggeditem may results in duplicates, requires distinct() results = results.filter(taggit_taggeditem_items__content_type__name=model).distinct() results = results[:5] results_json = [] for r in results: results_json.append({'label': r.name, 'value': r.name}) if len(results_json) > 0: return json_response(results_json) else: return json_response([{}])
def search_persons_json(req): json_resp = [] term = req.GET.get('term', '').strip() if term != '': q = _get_query(term, ['user__first_name', 'user__last_name']) matching_people = Person.objects.filter(q).filter( user__is_active=True).distinct()[:5] for person in matching_people: name = person.user.first_name + ' ' + person.user.last_name json_resp.append({'label': name, 'stub': person.stub, 'value': name}) return json_response(json_resp)
def get_number(request): try: if request.method == 'POST': number = request.POST[ 'number'] # MUST BE STRING => CASE int('021') -> 21 ('0' missing) rules = json.loads(request.POST['rules']) # Check rules (keys must be int) rules = {int(k): [i for i in v] for k, v in rules.items()} # Get words start_t = time.time() words_matched, total_lines, regex = get_words(number, mnemo=rules) end_t = time.time() - start_t # Prepare result res = '-----------------------------\n' res += '-- RAEFINDER --\n' res += '-----------------------------\n' res += '\n'.join(words_matched) # Print results if len(words_matched): res += '\n\n' res += '-------------------------------\n' res += '- Words matched: {:,}\n'.format(len(words_matched)) res += '- Words analyzed: {:,}\n'.format(total_lines) res += '- Elapsed time: %.5fs\n' % end_t res += '- Regex used: "%s"' % regex else: res += 'No words matched the expression' return json_response(msg=res) else: return json_response(msg='Invalid request', error=True) except Exception as e: return json_response(msg=str(e), error=True)
def edit_model_title(request, entry_id=None): """ Edit the name of an book or entry, depending which one is passed in""" if not request.is_ajax(): return HttpResponseForbidden() #if request.method != 'POST': # return json_response({'success': False, 'error': 'Should be a POST but is not'}) #Get new title #new_title = request.POST.get('new_title', None) # If we are editing the book title #if book_id: # try: # book = Book.objects.get(id=(int(book_id))) # if book.author != request.user: # return HttpResponseForbidden() # except Book.DoesNotExist: # return json_response({'success': False, 'error': 'Book not found'}) # book.setTitle(new_title) #Otherwise we are editing the model title #else: try: entry = Entry.objects.get(id=int(entry_id)) if entry.book.author != request.user: return HttpResponseForbidden() except Entry.DoesNotExist: return json_response({'success': False, 'error': 'Entry not found'}) # Set new title to current entry title entry.setTitle(new_title) return json_response({'success': True})
def stop_upload(request): if 'stop' in request.POST: models.Status.SetValue(models.Status.VIDEO_UPLOAD_STARTED, '0') models.Command.objects.create(command=models.Command.STOP_VIDEO_UPLOAD) capturing = models.Status.GetValue(models.Status.VIDEO_STARTED) if capturing == '1': # restart capturing models.Status.SetValue(models.Status.VIDEO_STARTED, '0') time.sleep(1) models.Status.SetValue(models.Status.VIDEO_STARTED, capturing) return json_response("Stopped")
def posts(request, post_id=None, tags=None, page=None, titles_only=False, published_only=False): """ Get Published Blog Posts :param tags [LIST] of tags to filter on [optional] :param page [INT] page number of Posts to return [optional] :param titles_only [BOOLEAN] return Post titles and stamps only [optional] :param published_only [BOOLEAN] return published Posts only [optional] :param post_id [LONG] Post identifier [optional] :return: posts [LIST] List of Posts """ # ID filter (if we get an ID parameter lets assume the user wants all the info on that Post) if post_id: post = Post.get_by_id(post_id, parent=get_blog_key()) iterator = [post] if post else [] else: # If no ID specified, get all Posts ordered by stamp for our Blog post_query = Post.query(ancestor=get_blog_key()).order(-Post.stamp) # Published filter if published_only: post_query = post_query.filter(Post.published == True) # Tag filter if tags: post_query = post_query.filter(Post.tags.IN(tags)) # Page Filter if page is not None: iterator = post_query.fetch(POST_PAGE_SIZE, offset=page * POST_PAGE_SIZE) else: iterator = post_query.fetch() # Preview or full Post if titles_only: response = json_response([post.preview() for post in iterator]) else: response = json_response([post.dictionary() for post in iterator]) return response
def users_by_division_json(req): result = {} divisions = OrgGroup.objects.filter( parent=None).exclude(title__icontains="Region").order_by('title') for d in divisions: result[d.title] = User.objects.filter(is_active=True).filter( Q(person__org_group=d) | Q(person__org_group__parent=d)).order_by( 'last_name', 'first_name').count() result_json = [] for k in result.keys(): result_json.append({'name': k, 'value': result[k]}) return json_response(result_json)
def unshare(request): if not request.is_ajax(): return HttpResponseForbidden() if request.method != 'POST': return json_response({'success': False, 'error': 'wrong method'}) shared = request.POST.get('shared', None) if not shared: return json_response({'success': False, 'error': 'missing argument'}) try: shared_elem = Shared.objects.get(id=int(shared)) except Shared.DoesNotExist: return json_response({'success': False, 'error': 'shared not found'}) # Does this make sense? If they are both not you, then return a forbidden access? # Will only change if it does NOT work if shared_elem.from_user != request.user and shared_elem.to_user != request.user: return HttpResponseForbidden() shared_elem.delete() return json_response({'success': True})
def setUp(self): def testfun(_, messages, userinfo): messages['success'] = True return {'messages': messages, 'user': userinfo.username} self.user = User.objects.create_user('testuser', '*****@*****.**', password=_TEST_PASSWORD, token='testtoken', is_active=True) self.wrapped = api_token_required(json_response(testfun)) self.request = HttpRequest() self.request.method = 'POST'
def create(request): user_name = _gen_username() password = _gen_password() car_name = request.POST['name'] car_description = request.POST.get('description', '') if models.Car.objects.filter( name=car_name, user__main_user__auth_user=request.user ).exists(): err_msg = 'Car with name "%s" for user "%s" already exists.' % (car_name, request.user) return json_response({'error': err_msg}, status=400) auth_user = AuthUser.objects.create_user(username=user_name, password=password) user = models.User.objects.create(auth_user=auth_user, is_car=True, main_user=request.user.core_user) models.Car.objects.create(user=user, name=car_name, description=car_description) result = { 'user_name': user_name, 'password': password, } return json_response(result)
def delete_book(request): if not request.is_ajax(): return HttpResponseForbidden() if request.method != 'POST': return json_response({'success': False, 'error': 'wrong method'}) book = request.POST.get('book', None) if not book: return json_response({'success': False, 'error': 'missing argument'}) try: delete_book = Book.objects.get(id=int(book)) except Book.DoesNotExist: return json_response({'success': False, 'error': 'book not found'}) if delete_book.author != request.user: return HttpResponseForbidden() """ Does it delete every entry also with the book itself? Do we have to do that or Django take care of that for us? """ delete_book.delete() return json_response({'success': True, 'url': reverse('core_home')})
def search_persons_json(req): json_resp = [] term = req.GET.get('term', '').strip() if term != '': q = _get_query(term, ['user__first_name', 'user__last_name']) matching_people = Person.objects.filter(q).filter( user__is_active=True).distinct()[:5] for person in matching_people: name = person.user.first_name + ' ' + person.user.last_name json_resp.append({ 'label': name, 'stub': person.stub, 'value': name }) return json_response(json_resp)
def devices(request): """ list of video devices in system """ result = [] for device in models.VideoDevice.GetExistingDevices(): result.append({ 'id': device.id, 'dev_path': device.dev_path, 'name': device.get_name(), 'resolution': device.resolution, 'available_resolutions': device.get_resolutions(), 'is_uses': device.is_uses, }) return json_response(result)
def browse(request): result = [] movies = glob.glob("%s/*.mp4" % settings.MOVIE_CONVERTED) for movie_path in movies: file_name = movie_path.split('/')[-1] file_size = os.path.getsize(movie_path) human_file_size = human_size(file_size) result.append({ 'name': file_name, 'size': human_file_size, }) return json_response(result)
def last_results(request): import obd.models results = [] for sensor in obd.models.Sensor.objects.all(): if sensor.results.exclude(value__in=('', 'NO DATA')).exists(): latest = sensor.results.exclude(value__in=('', 'NO DATA')).latest() results.append({ 'description': sensor.description, 'pid': sensor.pid, 'unit': sensor.unit, 'value': latest.value, 'date_time': latest.dc, }) return json_response(results)
def labour_admin_roster_job_category_fragment(request, vars, event, job_category): job_category = get_object_or_404(JobCategory, event=event, pk=job_category) vars.update( **labour_admin_roster_vars(request, event) ) hours = vars['hours'] vars.update( job_category=job_category, totals=[0 for i in hours], ) return json_response(dict( replace='#jobcategory-{0}-placeholder'.format(job_category.pk), content=render_string(request, 'labour_admin_roster_job_category_fragment.jade', vars) ))
def playlist(request): url = settings.VLC_HTTP + '/requests/playlist.xml' xml_tree = _get_xml(url) result = [] items = _find_element(xml_tree, 'leaf') for el in items: duration_human = None if el.attrib.get('duration'): duration = el.attrib['duration'] duration_human = _humanize_time(duration) result.append({ 'id': el.attrib.get('id'), 'name': el.attrib.get('name'), 'duration_sec': el.attrib.get('duration'), 'duration_human': duration_human, 'uri': el.attrib.get('uri'), 'current': el.attrib.get('current'), }) return json_response(result)
def set_current(request): card_name = request.POST['card_name'] models.Settings.SetValue(models.Settings.AUDIO_CARD, card_name) return json_response('Ok')
def set_device_uses(request, id): is_uses = int(request.POST['is_uses']) models.VideoDevice.objects.filter(id=id).update(is_uses=is_uses) return json_response("Ok")
def list_cards(request): result = {} result['cards'] = audio_cards_list() return json_response(result)
def share_book(request): if not request.is_ajax(): return HttpResponseForbidden() if request.method != 'POST': return json_response({'success': False, 'error': 'wrong method'}) # Have the hook default value as 'none' if value not found # is there a difference between this code and request.user? user = request.POST.get('user', None) #if not user: # return json_response({'success': False, 'error': 'missing argument'}) book = request.POST.get('book', None) entry = request.POST.get('entry', None) # I do not believe you can share an entry without sharing the corresponding book if not book and not entry and not user: return json_response({'success': False, 'error': 'missing argument'}) """ Ask the user for an email or username. If user does not exist, validate email anyway and return 404. """ try: shared_user = User.objects.get(Q(username=user) | Q(email=user)) except User.DoesNotExist: try: validate_email(user) except: is_email = False else: is_email = True params = { 'success': False, 'error': 'user not found', 'code': 404, 'is_email': is_email } return json_response(params) if book: try: shared_book = Book.objects.get(id=int(book)) except Book.DoesNotExist: return json_response({'success': False, 'error': 'book not found'}) else: shared_entry = None else: try: shared_entry = Entry.objects.get(id=int(entry)) except Entry.DoesNotExist: return json_response({ 'success': False, 'error': 'entry not found' }) else: shared_book = None if request.user == shared_user: return json_response({ 'success': False, 'error': "You can't share with yourself!" }) # If user did not want to share a book, it must have been an entry. # https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create if book: shared, created = Shared.objects.get_or_create(from_user=request.user, to_user=shared_user, book=shared_book) else: shared, created = Shared.objects.get_or_create(from_user=request.user, to_user=shared_user, entry=shared_entry) #If the object didn't have to be created, then user is already sharing either (book/entry) with that person. if not created: return json_response({ 'success': False, 'error': 'The book/entry is already shared with %s' % shared_user.profile.get_full_name() }) shared.save() result = render_to_string('share/share_list_block.html', {'share': shared}) data = {'success': True, 'result': result} return json_response(data)
def set_device_resolution(request, id): models.VideoDevice.objects.filter(id=id).update(resolution=request.POST['resolution']) return json_response("Ok")
return json_response({ 'success': False, 'error': 'missing argument' }, error=True) message = render_to_string('share/share_invitation.html', {'user_from': user_from}) try: send_mail('You are invited to use Nenjah', message, settings.EMAIL_FROM, [mail_to], fail_silently=True) except Exception, error: logging.exception("not able to send invitation") return json_response({'success': False, 'error': error}, error=True) return json_response({'success': True}) @login_required def sharing(request): shared_by_me = Shared.objects.filter(from_user=request.user).order_by( 'book', 'entry') shared_with_me = Shared.objects.filter(to_user=request.user) return render(request, 'share/sharing.html', { 'shared_by_me': shared_by_me, 'shared_with_me': shared_with_me })
def json_error(error): return json_response({'error': error})
def delete(request, id): url = settings.VLC_HTTP + '/requests/status.xml' params = {'command': 'pl_delete', 'id': id} _get_xml(url, params) return json_response('Ok')
def in_play(request): url = settings.VLC_HTTP + '/requests/status.xml' input_path = request.POST['input'] params = {'command': 'in_play', 'input': input_path} _get_xml(url, params) return json_response('Ok')
def halt(request): if 'halt' in request.POST: models.Command.objects.create(command=models.Command.SYSTEM_DOWN) return json_response("Ok")
def stop_capture(request): if 'stop' in request.POST: models.Status.SetValue(models.Status.VIDEO_STARTED, '0') return json_response("Stopped")
def seek(request): url = settings.VLC_HTTP + '/requests/status.xml' value = request.POST['value'] params = {'command': 'seek', 'val': value} _get_xml(url, params) return json_response('Ok')
def repeat(request): url = settings.VLC_HTTP + '/requests/status.xml' params = {'command': 'pl_repeat'} _get_xml(url, params) return json_response('Ok')
def stop_capture(request): if 'stop' in request.POST: models.Status.SetValue(models.Status.OBD_STARTED, '0') return json_response("Stopped")
def start_capture(request): if 'start' in request.POST: models.Status.SetValue(models.Status.OBD_STARTED, '1') return json_response("Started")
def start_capture(request): if 'start' in request.POST: models.Status.SetValue(models.Status.VIDEO_STARTED, '1') return json_response("Started")
def play(request): url = settings.VLC_HTTP + '/requests/status.xml' id = request.POST['id'] params = {'command': 'pl_play', 'id': id} _get_xml(url, params) return json_response('Ok')