def wrapper(request, *args, **kwargs): s = request.session if 'address' not in s: messages.warning(request, LOGIN_REQUIRED) s['return'] = request.get_full_path() return redirect('login') else: try: usr = FaucetUser.objects.get(address=s['address']) if usr.enabled == False: s.flush() messages.warning(request, ACCOUNT_DISABLED) return redirect('default') if not usr.email_confirmed: messages.warning( request, SafeString(SAFE_ACCOUNT_NOT_YET_CONFIRMED % (reverse('activation_helper')))) except ObjectDoesNotExist: usr = None messages.warning(request, INVALID_SESSION, 'danger') s.flush() s['return'] = request.get_full_path() return redirect('login') return function(request, *args, **kwargs)
def get_context_data(self, *args, **kwargs): page_context = {} # load the profile profile_method = settings.WAZIMAP.get('timeseries_profile_builder', None) self.profile_name = settings.WAZIMAP.get('timeseries_profile', 'default') if not profile_method: raise ValueError( "You must define WAZIMAP.profile_builder in settings.py") profile_method = import_string(profile_method) profile_data = profile_method(self.geo, self.profile_name, self.request) profile_data['geography'] = self.geo.as_dict_deep() profile_data = enhance_api_data(profile_data) page_context.update(profile_data) profile_data_json = SafeString( json.dumps(profile_data, cls=DjangoJSONEncoder)) page_context.update({'profile_data_json': profile_data_json}) # is this a head-to-head view? page_context['head2head'] = 'h2h' in self.request.GET return page_context
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) g = geojson.Serializer() geo_data = Area.objects.filter(pk=self.kwargs['pk']) data = g.serialize(geo_data, geometry_field='geom', fields=('name', )) context['geom'] = SafeString(json.loads(data)) return context
def populateCalendar(request): """ @function: populateCalendar @description: Fills the calendar with the appointments for an individual (depends on type of user) """ currentUser = request.user usr = User.objects.get(username=currentUser.username) personObj = Person.objects.get(user=usr) events = [] docExists = Doctor.objects.filter(personID=personObj).exists() patientExists = Patient.objects.filter(personID=personObj.id).exists() # if the doctor exists then the viewer is a doctor if docExists: viewer = Doctor.objects.get(personID=personObj) appointmentExists = Appointment.objects.filter( doctorID=viewer.id).exists() if appointmentExists: appointmentSet = Appointment.objects.filter( doctorID=viewer.id, aptDate__gte=datetime.today()) for appt in appointmentSet: event = {} event['title'] = "Patient: " + appt.patientID.__str__() startString = datetime.combine( appt.aptDate, appt.aptTime).strftime('%Y-%m-%dT%X') event["start"] = startString event[ "description"] = "You have an appointment with <b> Dr. " + appt.doctorID.__str__() + " </b> at <b>" \ + appt.aptTime.strftime('%I') + "</b> on <b> " + appt.aptDate.strftime( '%x') + "</b> for the following reason: <br><em>" \ + appt.reason + "</em>" event["allDay"] = False events.append(event) events = dumps(events) elif patientExists: viewer = Patient.objects.get(personID=personObj) appointmentExists = Appointment.objects.filter( patientID=viewer.id).exists() if appointmentExists: appointmentSet = Appointment.objects.filter( patientID=viewer.id, aptDate__gte=datetime.today()) for appt in appointmentSet: event = {} event['title'] = appt.doctorID.__str__() startString = datetime.combine( appt.aptDate, appt.aptTime).strftime('%Y-%m-%dT%X') event["start"] = startString event[ "description"] = "You have an appointment with <b> Dr. " + appt.doctorID.__str__() + " </b> at <b>" \ + appt.aptTime.strftime('%I') + "</b> on <b> " + appt.aptDate.strftime( '%x') + "</b> for the following reason: <br><em>" \ + appt.reason + "</em>" event["allDay"] = False events.append(event) events = dumps(events) return SafeString(events)
def test(request, level_id): if request.method == 'GET': try: level = Level.objects.get(id=level_id) words = random.sample(level.word.all(), min(level.total_word, level.words)) data = [] for w in words: data.append({ 'word': w.word, 'images': w.make_ques, 'audio': w.audio, 'id': w.id, 'answer': -1, 'categories': [c.name for c in w.category.all()] }) return render_to_response( 'test.html', RequestContext( request, { 'fill_active': 1, 'index': [i for i in range(1, len(data) + 1)], 'data': SafeString(json.dumps(data)), 'know_active': 1 })) except: return render_to_response( 'error.html', RequestContext(request, {'error': '生成试题错误,请稍后再试'})) else: data = request.POST.get('data', '') if not data: return render_to_response( 'error.html', RequestContext(request, {'error': '怎么没有data参数'})) else: res = json.loads(data) paper = Paper() paper.user = request.user paper.level = Level.objects.get(id=level_id) paper.score = 0 paper.time = 0 paper.save() success = 0 total = 0 for qa in res: total += 1 question = Question() question.word = Word.objects.get(id=qa['id']) if qa['answer'] == qa['images']['result']: question.result = 1 success += 1 else: question.result = 0 question.save() paper.questions.add(question) paper.score = int(success * 100 / total) paper.save() return HttpResponseRedirect('/know/test/report/%d' % paper.id)
def hl_instance(value): if value is None or value == '': return '' def zero_if_none(value): return value if value is not None else 0 return SafeString('<a href="/tracker/instance/view/%s/">%s</a> [%s/%s : %s]' % tuple(map( lambda val: escape(str(val)), (value.uuid, value.user_interface, zero_if_none(value.players), zero_if_none(value.max_players), value.activity) )))
def _load_details_from_template(self, title, template_path): public_identifier_details_content = loader.render_to_string( template_path, ) return HTML.details( title, SafeString(public_identifier_details_content), )
def render(self, name, value, attrs=None): svg_img = qrcode.make(value, image_factory=qrcode.image.svg.SvgPathImage) # We write out a valid SVG document svg_raw = BytesIO() svg_img.save(svg_raw) # Then, take advantage of modern browsers' support for inline <svg> images return SafeString(svg_raw.getvalue().decode("ascii"))
def lg_am(request): am, pm = fbprophet_main.get_json() print(am[0]) context = { 'day': SafeString(am), 'corp': 'lg', } return render(request, 'blog/chart_realtime.html', context)
def form_valid(self, form): self.course = form.cleaned_data['course'] self.course.students.add(self.request.user) safe_title = escape(self.course) self.success_message = SafeString( f'Congratulations you have successfully enrolled the <strong>{safe_title}</strong> course!' ) return super().form_valid(form)
def load(self): self.view = import_string('app.examples.' + self.basename + '.view') self.module = import_string('app.examples.' + self.basename) docstr = import_string('app.examples.' + self.basename + '.__doc__') self.name, description = docstr.split('\n\n', 1) self.description = SafeString(add_links_to_docs(description)) self.python_source = render_python_source(self.python_path)
def render(self, request): # This is sort of weird because we're decoding the # content in a HttpResponse; it's not an ideal API, # but we want the examples be as conventional as # possible so they don't confuse readers, and having # them return HttpResponse objects like normal Django # views is the easiest way to accomplish that. return SafeString(self.view(request).content.decode('utf-8'))
def as_hidden(self): mystr = '' mystr += self['sequence'].as_hidden() + '\n' mystr += self['useremail'].as_hidden() + '\n' mystr += self['workdir'].as_hidden() + '\n' return SafeString(mystr)
def flash_player(song_id): return SafeString('''<embed src="http://grooveshark.com/songWidget.swf" type="application/x-shockwave-flash" width="250" height="40" flashvars="hostname=cowbell.grooveshark.com&songIDs=%s&style=metal&p=0" allowscriptaccess="always" wmode="window">''' % song_id)
def test_force_escape_safe_string(self): html = "<h1>hello world</h1>" safe_string = SafeString(html) escaped_string = force_escape(safe_string) expected = "<h1>hello world</h1>" self.assertEqual(escaped_string, expected)
def result(request, album_id): album = get_object_or_404(MockTest, pk=album_id) if request.method == 'POST': post_data = json.loads(request.body) album.opt_answer = post_data album.save() try: mockt = MockTest.objects.get(pk=album_id) except MockTest.DoesNotExist: raise Http404("MockTest Does not exist") return render( request, 'mock_result.html', { 'mock': SafeString(mockt.mock), 'info': SafeString(mockt.opt_answer['save']), 'obj': mockt })
def urldisplay(url): if url.startswith("http"): display_url = url.replace("http://", "").replace("https://", "") return SafeString( f"<a href='{url}' title='{url}' rel='nofollow' class='flex items-center mr-1 truncate'>{iconify(url)}<span class='truncate'>{escape(display_url)}</span></a>" ) else: return url
def test_safe_status(self): """ Translating a string requiring no auto-escaping shouldn't change the "safe" status. """ from django.utils.safestring import mark_safe, SafeString, SafeUnicode s = mark_safe('Password') self.assertEqual(SafeString, type(s)) activate('de') try: self.assertEqual(SafeUnicode, type(ugettext(s))) finally: deactivate() self.assertEqual('aPassword', SafeString('a') + s) self.assertEqual('Passworda', s + SafeString('a')) self.assertEqual('Passworda', s + mark_safe('a')) self.assertEqual('aPassword', mark_safe('a') + s) self.assertEqual('as', mark_safe('a') + mark_safe('s'))
def urldisplay(url): if url.startswith("http"): display_url = url.replace("http://", "").replace("https://", "") return SafeString( f"<a href='{url}' title='{url}' rel='nofollow'>{escape(display_url if len(display_url) < 40 else display_url[:40] + '...')}</a>" ) else: return url
def test_profile_display(self): """Test that our template tag returns the short name hyperlinked to the URL""" def mock_get_url(): return 'http://example.com/profile/shyguy' self.author.get_absolute_url = mock_get_url display = andablog_tags.author_display(self.author) self.assertEqual(display, SafeString('<a href="http://example.com/profile/shyguy">ShyGuy</a>'))
def post(self, request, *args, **kwargs): result = super().post(request, *args, **kwargs) safe_title = escape(self.object.title) safe_technology = escape(self.object.technology) message = SafeString( f'Course <strong>{safe_title} {safe_technology}</strong> removed.') messages.success(request, message) return result
def test_force_escape_regular_string(self): html = "hello world" safe_string = SafeString(html) escaped_string = force_escape(safe_string) expected = "hello world" self.assertEqual(escaped_string, expected)
def get_context_data(self, *args, **kwargs): geography_id = self.geo_id try: s3_key = self.s3_profile_key(geography_id) except Exception: s3_key = None if s3_key and s3_key.exists(): memfile = cStringIO.StringIO() s3_key.get_file(memfile) memfile.seek(0) compressed = gzip.GzipFile(fileobj=memfile) # Read the decompressed JSON from S3 profile_data_json = compressed.read() # Load it into a Python dict for the template profile_data = json.loads(profile_data_json) # Also mark it as safe for the charts on the profile profile_data_json = SafeString(profile_data_json) else: profile_data = geo_profile(geography_id) if profile_data: profile_data = enhance_api_data(profile_data) profile_data_json = SafeString( json.dumps(profile_data, cls=LazyEncoder)) if s3_key is None: logger.warn( "Could not save to S3 because there was no connection to S3." ) else: self.write_profile_json(s3_key, profile_data_json) else: raise Http404 page_context = { 'profile_data_json': profile_data_json, 'canonical_url': self.canonical_url } page_context.update(profile_data) return page_context
def index(request): code = request.GET.get('code', None) batch_id = request.GET.get('state', None) if code is None or batch_id is None: return _error(request, u'非法调用', u'参数异常') userInfo = auth.fetchUserInfo(code) if userInfo is None: return _error(request, u'非法调用', u'参数异常') openid = userInfo.getOpenId() order = data.fetchOrder(batch_id, openid) if order is not None: #return _error(request, u'重复提交订单', u'重复提交订单') url = '%s/order?orderId=%s' % (DOMAIN_URL, order.id) return HttpResponseRedirect(url) tel = data.fetchCustomerTel(openid) tel = tel if tel is not None else '' batch = data.fetchBatch(batch_id) if batch is None: return _error(request, u'服务异常', u'未知的团购批次') expireTime = data.fetchBatchExpireTime(batch.id) if expireTime == 0: return _error(request, u'对不起', u'该团购已经结束') commodities = data.parseToCommodities(batch) orderAmounts = data.fetchOrderAmounts(batch.id) commoditiesJson = data.parseToCommoditiesJson(batch) distsJson = data.parseToDistJson(batch) wxConfigJson = auth.createWXConfigJson( request.get_raw_uri(), ['onMenuShareAppMessage', 'closeWindow']) shareUrl = '%s/r?id=%s' % (DOMAIN_URL, batch_id) context = RequestContext( request, { 'batch': batch, 'commodities': commodities, 'orderAmounts': orderAmounts, 'expireTime': expireTime, 'commoditiesJson': SafeString(commoditiesJson), 'distsJson': SafeString(distsJson), 'wxConfigJson': SafeString(json.dumps(wxConfigJson)), 'userInfo': userInfo, 'userInfoJson': SafeString(userInfo.json()), 'tel': tel, 'shareUrl': shareUrl }) template = loader.get_template('web/index.html') return HttpResponse(template.render(context))
def user(request): video_id = 1 logs = TimeLog.objects.filter() poll_results = PieChart.objects.get(video_id=video_id) return render(request, "yougam/user.html", { "logs": logs, "json": SafeString(poll_results.json_data) })
def details(request, album_id): try: mockt = MockTest.objects.get(pk=album_id) except MockTest.DoesNotExist: raise Http404("MockTest Does not exist") return render(request, 'mock.html', { 'mock': SafeString(mockt.mock), 'info': mockt })
def html(self): """ Return the html version of the markdown. Wraps it as a SafeString so it will display without being escaped. This should probably be done and cached somewhere and let this method do a lookup for the cached version. An alternative would be to double the storage in the DB but that could mean having to update the whole DB if we fix something about martor. Storing this in a memcached instance would probably be better """ # TODO: Store the results in memcached for speed return SafeString(markdownify(self.text))
def encore_entrypoint_js(context: Dict, entrypoint: str) -> SafeString: js = encore.get_js(entrypoint) if 'encore_loaded_js' not in context: context['encore_loaded_js'] = set() if 0 == len(js): return SafeString('') buffer = '' for script in js: if script in context['encore_loaded_js']: continue buffer += '<script src="%s" defer></script>\n' % script context['encore_loaded_js'].add(script) return SafeString(buffer.strip())
def render(self, context, nested=False): if self.message_context: message_context = self.message_context.resolve(context) else: message_context = None # Update() works like a push(), so corresponding context.pop() is at # the end of function context.update( {var: val.resolve(context) for var, val in self.extra_context.items()} ) singular, vars = self.render_token_list(self.singular) if self.plural and self.countervar and self.counter: count = self.counter.resolve(context) if not isinstance(count, (Decimal, float, int)): raise TemplateSyntaxError( "%r argument to %r tag must be a number." % (self.countervar, self.tag_name) ) context[self.countervar] = count plural, plural_vars = self.render_token_list(self.plural) if message_context: result = translation.npgettext(message_context, singular, plural, count) else: result = translation.ngettext(singular, plural, count) vars.extend(plural_vars) else: if message_context: result = translation.pgettext(message_context, singular) else: result = translation.gettext(singular) default_value = context.template.engine.string_if_invalid def render_value(key): if key in context: val = context[key] else: val = default_value % key if "%s" in default_value else default_value return render_value_in_context(val, context) data = {v: render_value(v) for v in vars} context.pop() try: result = result % data except (KeyError, ValueError): if nested: # Either string is malformed, or it's a bug raise TemplateSyntaxError( "%r is unable to format string returned by gettext: %r " "using %r" % (self.tag_name, result, data) ) with translation.override(None): result = self.render(context, nested=True) if self.asvar: context[self.asvar] = SafeString(result) return "" else: return result
def encore_entrypoint_css(context: Dict, entrypoint: str) -> SafeString: css = encore.get_css(entrypoint) if 'encore_loaded_css' not in context: context['encore_loaded_css'] = set() if 0 == len(css): return SafeString('') buffer = '' for stylesheet in css: if stylesheet in context['encore_loaded_css']: continue buffer += '<link rel="stylesheet" href="%s">' % stylesheet context['encore_loaded_css'].add(stylesheet) return SafeString(buffer.strip())