def get(self, request): title = unquote(request.GET.get('title', "")) name = unquote(request.GET.get('name', "")) url = request.get_full_path().split("&name=")[0] # print(url) # print(unquote(title)) phone = Comments.objects.filter( Q(phone_title=title), Q(comment__icontains=name) | Q(user_name__icontains=name)).order_by('id') counter = phone.count() user_counter = phone.values('user_name').distinct().count() try: sent_avg = f" {phone.aggregate(Avg('sentiments'))['sentiments__avg']:0.2f} " except: sent_avg = 0 queryset = phone.values('sentiments') condtions = {'sentiments__gte': 0.5} plus = queryset.filter(**condtions).count() queryset = phone.values('sentiments') condtions = {'sentiments__lte': 0.5} minus = queryset.filter(**condtions).count() template = loader.get_template('phone_detail.html') return HttpResponse(template.render(locals()))
def library(request, libname, version=None): libname = unquote(libname) if version: version = unquote(version) lib = Library.objects.filter(name=libname, version=version).get() else: lib = Library.objects.filter(name=libname).order_by("id")[0:1].get() if not lib: raise Http404("No library matches the given query.") libdoc = LibraryDoc(lib) versions = [x.version for x in Library.objects.filter(name=libname) if x.version != lib.version] return render_to_response("library.html", {"lib": libdoc, "versions": versions})
def library(request, libname, version=None): libname = unquote(libname) if version: version = unquote(version) lib = Library.objects.filter(name=libname, version=version).get() else: lib = Library.objects.filter(name=libname).order_by('id')[0:1].get() if not lib: raise Http404('No library matches the given query.') libdoc = LibraryDoc(lib) versions = [x.version for x in Library.objects.filter(name=libname) if x.version != lib.version] return render_to_response('library.html', {'lib': libdoc, 'versions': versions})
def test_url_encode(self): pp = "QwToU/09ys0B8SVKmBnv5OKTax2s1+Mlxj0OywiF77U=" encoded = quote(pp) print("\n") print(encoded) self.assertEquals("QwToU/09ys0B8SVKmBnv5OKTax2s1%2BMlxj0OywiF77U%3D", encoded) decoded = unquote(encoded) print(decoded) self.assertEquals(pp, decoded) decoded = unquote(encoded) print(decoded) self.assertEquals(pp, decoded)
def extraer_thumbnail(video): img_name = os.path.basename(unquote(video.video.url).replace( ' ', '_')).split('.')[0] + '.jpg' date_url = str(datetime.datetime.now().year) + '/' + str( datetime.datetime.now().month) + '/' img_ruta = os.path.join(settings.BASE_DIR, 'media/img/') + date_url if not os.path.exists(img_ruta): os.makedirs(img_ruta) sleep(0.05) subprocess.call([ 'ffmpeg', '-i', os.path.join(settings.BASE_DIR, 'media/videos/' + date_url) + os.path.basename(unquote(video.video.url).replace(' ', '_')), '-ss', '00:00:00.000', '-vframes', '1', img_ruta + img_name, '-y' ]) return 'img/' + date_url + img_name
def setDescrAction(request, key, rid): if request.method == 'POST': controller = checkControllerOwner(request.user.username, key) if not controller: messages.error(request, _('Invalid Parameters')) return redirect('controllers_index') try: rid = unquote(rid) rule = Rule.objects.get(key=key, description=rid) except: messages.error(request, _('Invalid Parameters')) return redirect('controllers_index') newdescr = request.POST['newdescr'] if newdescr and newdescr != rule.description: try: if Rule.objects.filter(key=key, description=newdescr).count() > 0: messages.error(request, _('This Rule Description does not exist, please choose another one')) else: rule = Rule.objects.get(key=key, description=rid) rule.description = newdescr rule.save() _sendRulesBack(key, rule.zid) messages.info(request, _('The Rule has been modified')) except Exception as e: messages.error(request, _('Sorry, an internal software error occurred')) messages.error(request, e) return redirect('automation', key=key)
def test_can_get_individual_bank_details(self): bank = self.create_assessment_bank() url = '{0}/{1}'.format(self.banks, unquote(str(bank.ident))) req = self.client.get(url) self.ok(req) data = self.json(req) self.assertEqual(data['id'], str(bank.ident))
def process_request(self, request): """ Reads url name, args, kwargs from GET parameters, reverses the url and resolves view function Returns the result of resolved view function, called with provided args and kwargs Since the view function is called directly, it isn't ran through middlewares, so the middlewares must be added manually The final result is exactly the same as if the request was for the resolved view. """ if request.path == self.ANGULAR_REVERSE: url_name = request.GET.get('djng_url_name') url_args = request.GET.getlist('djng_url_args', None) url_kwargs = {} # Read kwargs for param in request.GET: if param.startswith('djng_url_kwarg_'): url_kwargs[param[15:]] = request.GET[ param] # [15:] to remove 'djng_url_kwarg' prefix url = unquote( reverse(url_name, args=url_args, kwargs=url_kwargs, urlconf=self.urlconf)) assert not url.startswith( self.ANGULAR_REVERSE), "Prevent recursive requests" # rebuild the request object with a different environ request.environ['PATH_INFO'] = url query = request.GET.copy() query.pop('djng_url_name', None) query.pop('djng_url_args', None) request.environ['QUERY_STRING'] = query.urlencode() new_request = WSGIRequest(request.environ) request.__dict__ = new_request.__dict__
def test_can_delete_item(self): item = self.create_item(self.bank) self.num_items(1) url = '{0}/{1}'.format(self.items, unquote(str(item.ident))) req = self.client.delete(url) self.deleted(req) self.num_items(0)
def get(self, request): market_hash = unquote(self.request.GET.get('market_hash')) summary_comment, _ = SummaryComment.objects.get_or_create(market_hash=market_hash) logger.debug('summary_comment:%s' % summary_comment) serializer = SummaryCommentSerializer(summary_comment) return create_success_data_response(serializer.data)
def setDescrAction(request, key, rid): if request.method == 'POST': controller = checkControllerOwner(request.user.username, key) if not controller: messages.error(request, _('Invalid Parameters')) return redirect('controllers_index') try: rid = unquote(rid) rule = Rule.objects.get(key=key, description=rid) except: messages.error(request, _('Invalid Parameters')) return redirect('controllers_index') newdescr = request.POST['newdescr'] if newdescr and newdescr != rule.description: try: if Rule.objects.filter(key=key, description=newdescr).count() > 0: messages.error( request, _('This Rule Description does not exist, please choose another one' )) else: rule = Rule.objects.get(key=key, description=rid) rule.description = newdescr rule.save() _sendRulesBack(key, rule.zid) messages.info(request, _('The Rule has been modified')) except Exception as e: messages.error(request, _('Sorry, an internal software error occurred')) messages.error(request, e) return redirect('automation', key=key)
def process_request(self, request): """ Reads url name, args, kwargs from GET parameters, reverses the url and resolves view function Returns the result of resolved view function, called with provided args and kwargs Since the view function is called directly, it isn't ran through middlewares, so the middlewares must be added manually The final result is exactly the same as if the request was for the resolved view. """ if request.path == self.ANGULAR_REVERSE: url_name = request.GET.get('djng_url_name') url_args = request.GET.getlist('djng_url_args', None) url_kwargs = {} # Read kwargs for param in request.GET: if param.startswith('djng_url_kwarg_'): url_kwargs[param[15:]] = request.GET[param] # [15:] to remove 'djng_url_kwarg' prefix url = unquote(reverse(url_name, args=url_args, kwargs=url_kwargs)) assert not url.startswith(self.ANGULAR_REVERSE), "Prevent recursive requests" # rebuild the request object with a different environ request.path = request.path_info = url request.environ['PATH_INFO'] = url query = request.GET.copy() for key in request.GET: if key.startswith('djng_url'): query.pop(key, None) if six.PY3: request.environ['QUERY_STRING'] = query.urlencode() else: request.environ['QUERY_STRING'] = query.urlencode().encode('utf-8') # Reconstruct GET QueryList in the same way WSGIRequest.GET function works request.GET = http.QueryDict(request.environ['QUERY_STRING'])
def test_getting_item_los_when_has_none_returns_empty_list(self): item = self.create_item(self.bank, with_lo=False) url = '{0}items/{1}/objectives/'.format(self.url, unquote(str(item.ident))) req = self.client.get(url) self.ok(req) data = self.json(req) self.assertEqual(data['data']['count'], 0)
def test_can_get_individual_item_details(self): item = self.create_item(self.bank) url = '{0}/{1}'.format(self.items, unquote(str(item.ident))) req = self.client.get(url) self.ok(req) data = self.json(req) self.assertEqual(data['id'], str(item.ident))
def test_can_delete_bank(self): bank = self.create_assessment_bank() self.num_banks(1) url = '{0}/{1}'.format(self.banks, unquote(str(bank.ident))) req = self.client.delete(url) self.deleted(req) self.num_banks(0)
def get(self, request, *args, **kwargs): """Set up login url.""" if not reverse('secure_login') in request.META['HTTP_REFERER']: request.session['facebook_login_redirect_url'] = \ request.META['HTTP_REFERER'] return redirect(unquote(request.GET['auth_url']))
def get_context_data(self, **kwargs): context = { 'app': _('Perms'), 'app_url': unquote(reverse_lazy("perms:jenkins-permission-list")), 'action': _('Jenkins permission detail'), } kwargs.update(context) return super().get_context_data(**kwargs)
def test_can_get_bank_items(self): item = self.create_item(self.bank) url = '{0}banks/{1}/items'.format(self.url, unquote(str(self.bank.ident))) req = self.client.get(url) self.ok(req) data = self.json(req) self.assertEqual(len(data['data']['results']), 1) self.assertEqual(data['data']['results'][0]['id'], str(item.ident))
def test_can_get_item_learning_objectives(self): item = self.create_item(self.bank, with_lo=True) url = '{0}items/{1}/objectives/'.format(self.url, unquote(str(item.ident))) req = self.client.get(url) self.ok(req) data = self.json(req) self.assertEqual(data['data']['count'], 1) self.assertEqual(data['data']['results'][0]['id'], self._lo)
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update({ 'app': _('Jenkins'), 'app_url': unquote(reverse_lazy("cis:ci-list")), 'action': _('Job logs'), 'JMS_TITLE': _('Jenkins-Jumpserver'), }) return context
def process_request(self, request): """ Reads url name, args, kwargs from GET parameters, reverses the url and resolves view function Returns the result of resolved view function, called with provided args and kwargs Since the view function is called directly, it isn't ran through middlewares, so the middlewares must be added manually The final result is exactly the same as if the request was for the resolved view. Parametrized urls: djangoUrl.reverse can be used with parametrized urls of $resource In that case the reverse url is something like: /angular/reverse/?djng_url_name=orders&djng_url_kwarg_id=:id $resource can either replace the ':id' part with say 2 and we can proceed as usual, reverse with reverse('orders', kwargs={'id': 2}). If it's not replaced we want to reverse to url we get a request to url '/angular/reverse/?djng_url_name=orders&djng_url_kwarg_id=' which gives a request.GET QueryDict {u'djng_url_name': [u'orders'], u'djng_url_kwarg_id': [u'']} In that case we want to ignore the id param and only reverse to url with name 'orders' and no params. So we ignore args and kwargs that are empty strings. """ if request.path == self.ANGULAR_REVERSE: url_name = request.GET.get('djng_url_name') url_args = request.GET.getlist('djng_url_args', []) url_kwargs = {} # Remove falsy values (empty strings) url_args = filter(lambda x: x, url_args) # Read kwargs for param in request.GET: if param.startswith('djng_url_kwarg_'): # Ignore kwargs that are empty strings if request.GET[param]: url_kwargs[param[15:]] = request.GET[ param] # [15:] to remove 'djng_url_kwarg' prefix url = unquote(reverse(url_name, args=url_args, kwargs=url_kwargs)) assert not url.startswith( self.ANGULAR_REVERSE), "Prevent recursive requests" # rebuild the request object with a different environ request.path = request.path_info = url request.environ['PATH_INFO'] = url query = request.GET.copy() for key in request.GET: if key.startswith('djng_url'): query.pop(key, None) if six.PY3: request.environ['QUERY_STRING'] = query.urlencode() else: request.environ['QUERY_STRING'] = query.urlencode().encode( 'utf-8') # Reconstruct GET QueryList in the same way WSGIRequest.GET function works request.GET = http.QueryDict(request.environ['QUERY_STRING'])
def get_url(self, row): # b64编码 解决url带\的问题 job_name = base64.b64encode( row.get('name').encode('utf-8')).decode('utf-8') version = int(row.get('nextBuildNumber', 1)) - 1 return unquote( reverse('cis:ci-log', kwargs={ 'job_name': job_name, 'version': version }))
def test_can_update_bank(self): bank = self.create_assessment_bank() url = '{0}/{1}'.format(self.banks, unquote(str(bank.ident))) payload = {"displayName": "a second name"} req = self.client.put(url, data=payload, format='json') self.updated(req) data = self.json(req) self.assertEqual(data['id'], str(bank.ident)) self.assertEqual(data['displayName']['text'], payload['displayName'])
def process_request(self, request): """ Reads url name, args, kwargs from GET parameters, reverses the url and resolves view function Returns the result of resolved view function, called with provided args and kwargs Since the view function is called directly, it isn't ran through middlewares, so the middlewares must be added manually The final result is exactly the same as if the request was for the resolved view. Parametrized urls: djangoUrl.reverse can be used with parametrized urls of $resource In that case the reverse url is something like: /angular/reverse/?djng_url_name=orders&djng_url_kwarg_id=:id $resource can either replace the ':id' part with say 2 and we can proceed as usual, reverse with reverse('orders', kwargs={'id': 2}). If it's not replaced we want to reverse to url we get a request to url '/angular/reverse/?djng_url_name=orders&djng_url_kwarg_id=' which gives a request.GET QueryDict {u'djng_url_name': [u'orders'], u'djng_url_kwarg_id': [u'']} In that case we want to ignore the id param and only reverse to url with name 'orders' and no params. So we ignore args and kwargs that are empty strings. """ if request.path == self.ANGULAR_REVERSE: url_name = request.GET.get('djng_url_name') url_args = request.GET.getlist('djng_url_args', []) url_kwargs = {} # Remove falsy values (empty strings) url_args = filter(lambda x: x, url_args) # Read kwargs for param in request.GET: if param.startswith('djng_url_kwarg_'): # Ignore kwargs that are empty strings if request.GET[param]: url_kwargs[param[15:]] = request.GET[param] # [15:] to remove 'djng_url_kwarg' prefix url = unquote(reverse(url_name, args=url_args, kwargs=url_kwargs)) assert not url.startswith(self.ANGULAR_REVERSE), "Prevent recursive requests" # rebuild the request object with a different environ request.path = request.path_info = url request.environ['PATH_INFO'] = url query = request.GET.copy() for key in request.GET: if key.startswith('djng_url'): query.pop(key, None) if six.PY3: request.environ['QUERY_STRING'] = query.urlencode() else: request.environ['QUERY_STRING'] = query.urlencode().encode('utf-8') # Reconstruct GET QueryList in the same way WSGIRequest.GET function works request.GET = http.QueryDict(request.environ['QUERY_STRING'])
def get(self, request): params = request.query_params seller = unquote(params.get('seller')) logger.debug("seller is %s" % seller) queryset = Product.objects.filter(status=0).filter( Q(owner_address=seller)) serializer = ProductSerializer(queryset, many=True) return JsonResponse({ 'status': 1, 'message': 'success', 'data': serializer.data })
def get_context_data(self, **kwargs): jenkins_granted = self.get_queryset() jenkins_remain = JenkinsCi.objects.exclude( id__in=[a.id for a in jenkins_granted]) context = { 'app': _('Perms'), 'app_url': unquote(reverse_lazy("perms:jenkins-permission-list")), 'action': _('Jenkins related tasks'), 'jenkins_remain': jenkins_remain, } kwargs.update(context) return super().get_context_data(**kwargs)
def transcoding(video): print("Iniciando transcoding...") original = os.path.basename(unquote(video.video.url).replace(' ', '_')) date_url = str(datetime.datetime.now().year) + '/' + str( datetime.datetime.now().month) + '/' convertido = original.split('.')[0] + '.mp4' ruta = os.path.join(settings.BASE_DIR, 'media/videos/') + date_url subprocess.call([ 'ffmpeg', '-i', ruta + original, ruta + convertido, ], ) os.remove(ruta + original) return ruta + convertido
def get_context_data(self, **kwargs): jksApi = JenkinsApi() jobName = unquote( base64.b64decode(kwargs.get('job_name')).decode('utf-8')) parameters, referencedDict = jksApi.get_job_parameters(jobName) context = { 'app': _('Jenkins'), 'action': _('Create project'), 'parameters': parameters, 'referencedDict': referencedDict, 'job_name': jobName, 'JMS_TITLE': _('Jenkins-Jumpserver'), } kwargs.update(context) return super().get_context_data(**kwargs)
def get_redirect_url(self, *args, **kwargs): if 'what' in kwargs: what = kwargs['what'] else: what = self.request.POST['what'] if what == 'playlist': redirect_uri = 'http://15.164.50.5:8000/playlist/callback/' elif what == 'toptrack': redirect_uri = 'http://15.164.50.5:8000/playlist/toptracks/callback/' elif what == 'topartist': redirect_uri = 'http://15.164.50.5:8000/playlist/topartists/callback/' scope = 'playlist-read-private playlist-read-collaborative user-top-read' self.url = unquote(get_auth(redirect_uri, scope)) return super().get_redirect_url(*args, **kwargs)
def get(self, request): market_hash = unquote(self.request.GET.get('market_hash')) logger.debug("market_hash is %s" % market_hash) queryset = Comment.objects.filter(Q(market_hash=market_hash)).order_by('-created') page_set = PageNumberPagination().paginate_queryset( queryset=queryset, request=request, view=self ) serializer = CommentSerializer(page_set, many=True) comments = serializer.data comment_list = [] for item in comments: comment_list.append(Comment.fill_attr(item)) return create_success_data_response(comment_list)
def deleteAction(request, key, rid): controller = checkControllerOwner(request.user.username, key) if not controller: messages.error(request, _('Invalid Parameters')) return redirect('controllers_index') try: rid = unquote(rid) rule = Rule.objects.get(key=key, description=rid) zid = rule.zid Rule.objects.filter(key=key, description=rid).delete() _sendRulesBack(key, zid) messages.info(request, _('The Rule has been removed')) except Exception as e: messages.error(request, _('Sorry, an internal software error occurred')) logger.error(e) return redirect('automation', key=key)
def slack(request): body_decoded = request.body.decode('utf-8') parsed_response = {} for keyvalue in body_decoded.split('&'): key, value = keyvalue.split('=') parsed_response[key] = unquote(value) response_data = { 'response_type': 'ephemeral', 'text': 'Walk up successfully recorded', 'attachments': [ { 'text': parsed_response['text'] } ] } return HttpResponse( json.dumps(response_data), content_type='application/json')
def disableAction(request, key, rid): controller = checkControllerOwner(request.user.username, key) if not controller: messages.error(request, _('Invalid Parameters')) return redirect('controllers_index') try: rid = unquote(rid) rule = Rule.objects.get(key=key, description=rid) except: messages.error(request, _('Invalid Parameters')) return redirect('controllers_index') rule.is_active = False rule.save() _sendRulesBack(key, rule.zid) messages.info(request, _('The Rule has been modified')) return redirect('automation', key=key)
def get_context_data(self, **kwargs): users = [ str(i) for i in self.object.users.all().values_list('id', flat=True) ] user_remain = current_org.get_org_members( exclude=('Auditor', )).exclude(cipermission=self.object) user_groups_remain = UserGroup.objects.exclude( cipermission=self.object) context = { 'app': _('Perms'), 'app_url': unquote(reverse_lazy("perms:jenkins-permission-list")), 'action': _('Jenkins permission user list'), 'users': users, 'users_remain': user_remain, 'user_groups_remain': user_groups_remain, } kwargs.update(context) return super().get_context_data(**kwargs)
def test_can_update_item(self): item = self.create_item(self.bank) url = '{0}/{1}'.format(self.items, unquote(str(item.ident))) test_cases = [{ 'displayName': 'a new name' }, { 'learningObjectiveIds': ['mc3-objective%3A9730%40MIT-OEIT'] }] for payload in test_cases: req = self.client.put(url, data=payload, format='json') self.updated(req) data = self.json(req) key = payload.keys()[0] if key == 'displayName': self.assertEqual(data['displayName']['text'], payload['displayName']) else: self.assertEqual(data[key], payload[key])
def process_request(self, request): """ Reads url name, args, kwargs from GET parameters, reverses the url and resolves view function Returns the result of resolved view function, called with provided args and kwargs Since the view function is called directly, it isn't ran through middlewares, so the middlewares must be added manually The final result is exactly the same as if the request was for the resolved view. """ if request.path == self.ANGULAR_REVERSE: url_name = request.GET.get('djng_url_name') url_args = request.GET.getlist('djng_url_args', None) url_kwargs = {} # Read kwargs for param in request.GET: if param.startswith('djng_url_kwarg_'): url_kwargs[param[15:]] = request.GET[param] # [15:] to remove 'djng_url_kwarg' prefix url = unquote(reverse(url_name, args=url_args, kwargs=url_kwargs, urlconf=self.urlconf)) assert not url.startswith(self.ANGULAR_REVERSE), "Prevent recursive requests" # rebuild the request object with a different environ request.environ['PATH_INFO'] = url query = request.GET.copy() query.pop('djng_url_name', None) query.pop('djng_url_args', None) for param in request.GET: if param.startswith('djng_url_kwarg_'): query.pop(param, None) if request.method == 'GET': if query: url += '?%s' % (query.urlencode(), ) # TODO(simon) (Sep 10, 2015): Allow configuration of 301 vs 302? return http.HttpResponsePermanentRedirect(url) request.environ['QUERY_STRING'] = query.urlencode() new_request = WSGIRequest(request.environ) request.__dict__ = new_request.__dict__
def process_request(self, request): """ Reads url name, args, kwargs from GET parameters, reverses the url and resolves view function Returns the result of resolved view function, called with provided args and kwargs Since the view function is called directly, it isn't ran through middlewares, so the middlewares must be added manually The final result is exactly the same as if the request was for the resolved view. """ if request.path == self.ANGULAR_REVERSE: url_name = request.GET.get('djng_url_name') url_args = request.GET.getlist('djng_url_args', None) url_kwargs = {} # Read kwargs for param in request.GET: if param.startswith('djng_url_kwarg_'): url_kwargs[param[15:]] = request.GET[param] # [15:] to remove 'djng_url_kwarg' prefix url = unquote(reverse(url_name, args=url_args, kwargs=url_kwargs)) assert not url.startswith(self.ANGULAR_REVERSE), "Prevent recursive requests" # attributes session = request.session user = request.user # rebuild the request object with a different environ request.environ['PATH_INFO'] = url query = request.GET.copy() query.pop('djng_url_name', None) query.pop('djng_url_args', None) query_string = query.urlencode() if six.PY3: request.environ['QUERY_STRING'] = query_string else: request.environ['QUERY_STRING'] = query_string.encode('utf-8') new_request = WSGIRequest(request.environ) request.__dict__ = new_request.__dict__ request.user = user request.session = session
def editAction(request, key, rid): conds = [] actions = [] controller = checkControllerOwner(request.user.username, key) if not controller: messages.error(request, _('Invalid Parameters')) return redirect('controllers_index') try: rid = unquote(rid) rule = Rule.objects.get(key=key, description=rid) except: messages.error(request, _('Invalid Parameters')) return redirect('automation', key=key) if request.method == 'POST': form = AddRuleForm(request.POST) condition_formset = formsets.formset_factory(create_RuleConditionForm(key), formset=RuleConditionFormSet) cformset = condition_formset(request.POST, prefix='condition') action_formset = formsets.formset_factory(create_RuleActionForm(key), formset=RuleActionFormSet) aformset = action_formset(request.POST, prefix='action') if form.is_valid() and cformset.is_valid() and aformset.is_valid(): # Check rule description uniqueness count = Rule.objects.filter(key=key, description=form.cleaned_data['description']).count() if rule.description != form.cleaned_data['description'] and count > 0: messages.error(request, _('This Rule Description already exists, please choose another one')) form.fields['description'].initial = rule.description else: _updateRuleFromForm(rule, controller, key, form, cformset, aformset) rule.save() _sendRulesBack(key, controller.zid) messages.info(request, _('The Rule has been correctly updated')) return redirect('automation', key=key) else: messages.error(request, _('Invalid Form Values')) else: # not a POST form = AddRuleForm(initial={'description': rule.description}) condition_formset = formsets.formset_factory(create_RuleConditionForm(key), formset=RuleConditionFormSet, extra=0) for cond in rule.conditions: d = { 'conditiontype': cond.condtype, } if cond.condtype == RuleCondition.THRESHOLD: d['csensor_name'] = Sensor.buildInternalName(cond.devid, cond.instid, cond.sid) d['cvalue'] = cond.value d['testtype'] = cond.testtype d['duration'] = cond.duration elif cond.condtype == RuleCondition.STATUS: d['csensor_name2'] = Sensor.buildInternalName(cond.devid, cond.instid, cond.sid) d['cvalue2'] = cond.value d['testtype2'] = cond.testtype elif cond.condtype == RuleCondition.TIME: d['starttime'] = cond.starttime #d['endtime'] = cond.endtime d['alldays'] = True if not cond.days else False d['sunday'] = True if '0' in cond.days else False d['monday'] = True if '1' in cond.days else False d['tuesday'] = True if '2' in cond.days else False d['wednesday'] = True if '3' in cond.days else False d['thursday'] = True if '4' in cond.days else False d['friday'] = True if '5' in cond.days else False d['saturday'] = True if '6' in cond.days else False elif cond.condtype == RuleCondition.SUNTIME: d['sunevt'] = cond.sunevt d['sunoffset'] = cond.sunoffset d['sundelay'] = cond.sundelay d['alldays'] = True if not cond.days else False d['sunday'] = True if '0' in cond.days else False d['monday'] = True if '1' in cond.days else False d['tuesday'] = True if '2' in cond.days else False d['wednesday'] = True if '3' in cond.days else False d['thursday'] = True if '4' in cond.days else False d['friday'] = True if '5' in cond.days else False d['saturday'] = True if '6' in cond.days else False conds.append(d) action_formset = formsets.formset_factory(create_RuleActionForm(key), formset=RuleActionFormSet, extra=0) for action in rule.actions: d = { 'actiontype': action.actiontype, } if action.actiontype == RuleAction.SENSORCMD: d['asensor_name'] = Sensor.buildInternalName(action.devid, action.instid, action.sid) d['avalue'] = action.value elif action.actiontype == RuleAction.EMAILCMD: d['email'] = action.email d['subject'] = action.subject d['content'] = action.content actions.append(d) logger.debug(conds) logger.debug(actions) context = { 'form': form, 'condition_formset': condition_formset(prefix='condition', initial=conds), 'action_formset': action_formset(prefix='action', initial=actions), 'contr': controller, 'rule': rule, } return render(request, 'automation/edit.html', context)
def get(self, request, *args, **kwargs): """Set up URLs for Google Plus login.""" if not reverse("secure_login") in request.META["HTTP_REFERER"]: request.session["google_plus_login_redirect_url"] = request.META["HTTP_REFERER"] return redirect(unquote(request.GET["auth_url"]))