def post(request, *args, **kwargs): eigenaar = request.user try: opdracht_pk = int( kwargs['opdracht_pk'][:6]) # afkappen voor veiligheid opdracht = (Opdracht.objects.select_related('bron').get( pk=opdracht_pk, eigenaar=eigenaar)) # alleen eigen producten except (ValueError, Opdracht.DoesNotExist): raise Resolver404() if opdracht.is_afgehandeld or opdracht.is_vrijgegeven_voor_levering: raise Resolver404() opdracht.is_vrijgegeven_voor_levering = True opdracht.save() mailer_queue_email(opdracht.to_email, opdracht.subject, opdracht.mail_body) opdracht.is_afgehandeld = True opdracht.save() url = reverse('Producten:bekijk-opdracht', kwargs={'opdracht_pk': opdracht.pk}) return HttpResponseRedirect(url)
def resolve(self, path): path = force_text(path) tried = [] match = self.regex.search(path) if match: new_path = path[match.end():] for pattern in self.url_patterns: try: sub_match = pattern.resolve(new_path) except Resolver404 as e: sub_tried = e.args[0].get('tried') if sub_tried is not None: tried.extend([pattern] + t for t in sub_tried) else: tried.append([pattern]) else: if sub_match: sub_match_dict = dict(match.groupdict(), **self.default_kwargs) sub_match_dict.update(sub_match.kwargs) return ResolverMatch( self._decorate(sub_match.func), sub_match.args, sub_match_dict, sub_match.url_name, self.app_name or sub_match.app_name, [self.namespace] + sub_match.namespaces) tried.append([pattern]) raise Resolver404({'tried': tried, 'path': new_path}) raise Resolver404({'path': path})
def post(self, request, *args, **kwargs): """ deze functie wordt aangeroepen als een POST request ontvangen is. dit is gekoppeld aan het drukken op de Selecteer knop. """ form = KiesAccountForm(request.POST) form.full_clean() # vult cleaned_data account_pk = form.cleaned_data.get('selecteer') try: accountemail = AccountEmail.objects.get(account__pk=account_pk) except AccountEmail.DoesNotExist: raise Resolver404() # prevent upgrade if accountemail.account.is_staff: raise Resolver404() context = dict() context['account'] = accountemail.account # schrijf de intentie in het logboek schrijf_in_logboek(account=self.request.user, gebruikte_functie="Inloggen", activiteit="Wissel naar account %s" % repr(accountemail.account.username)) # maak een tijdelijke URL aan waarmee de inlog gedaan kan worden url = maak_tijdelijke_url_accountwissel( accountemail, naar_account=accountemail.account.username) context['login_as_url'] = url return render(self.request, TEMPLATE_LOGIN_AS_GO, context)
def get_queryset(self, *args, **kwargs): model = self.request.GET.get('model') if not model: model = self.request.POST.get('model') if len(model) > 13: raise Resolver404() model = eval(model) self.model = model if type(model).__name__ == 'ModelBase': if self.is_list_view: return model.objects.all() return model.objects raise Resolver404()
def post(request, *args, **kwargs): eigenaar = request.user try: opdracht_pk = int( kwargs['opdracht_pk'][:6]) # afkappen voor veiligheid if request.user.is_staff: opdracht = (Opdracht.objects.select_related('bron').get( pk=opdracht_pk)) else: opdracht = (Opdracht.objects.select_related('bron').get( pk=opdracht_pk, eigenaar=eigenaar)) # alleen eigen producten except (ValueError, Opdracht.DoesNotExist): raise Resolver404() if opdracht.is_afgehandeld or opdracht.is_vrijgegeven_voor_levering: raise Resolver404() # zet de bron (e-mail) opnieuw op verwerken inbox = opdracht.bron inbox.is_verwerkt = False inbox.save() # start the achtergrond taak verwerk_ping.ping() # wacht maximaal 3 seconden tot de achtergrond klaar is interval = 0.2 # om steeds te verdubbelen total = 0.0 # om een limiet te stellen while not inbox.is_verwerkt and total + interval <= 3.0: time.sleep(interval) total += interval # 0.0 --> 0.2, 0.6, 1.4, 3.0, 6.2 interval *= 2 # 0.2 --> 0.4, 0.8, 1.6, 3.2 inbox = Inbox.objects.get(pk=inbox.pk) # while # we hadden of een timeout, of het is gelukt try: opdracht = Opdracht.objects.get(bron=inbox) except Opdracht.DoesNotExist: # niet gevonden - dan maar terug naar de grote lijst url = reverse('Producten:opdrachten') else: # wel gevonden - meteen tonen url = reverse('Producten:bekijk-opdracht', kwargs={'opdracht_pk': opdracht.pk}) return HttpResponseRedirect(url)
def _resolver_resolve_to_name(resolver, path): tried = [] django1 = django.VERSION < (2, 0) if django1: match = resolver.regex.search(path) else: match = resolver.pattern.regex.search(path) if match: new_path = path[match.end():] for pattern in resolver.url_patterns: try: if isinstance(pattern, RegexURLPattern): name = _pattern_resolve_to_name(pattern, new_path) elif isinstance(pattern, RegexURLResolver): name = _resolver_resolve_to_name(pattern, new_path) except Resolver404 as e: if django1: tried.extend([(pattern.regex.pattern + ' ' + t) for t in e.args[0]['tried']]) else: tried.extend([(pattern.pattern.regex.pattern + ' ' + t) for t in e.args[0]['tried']]) else: if name: return name if django1: tried.append(pattern.regex.pattern) else: tried.append(pattern.pattern.regex.pattern) raise Resolver404({'tried': tried, 'path': new_path})
def resolve_page_id(self, path): """Resolves requested path similar way how resolve does, but instead of return callback,.. returns page_id to which was application assigned. """ tried = [] pattern = getattr(self, 'pattern', self) match = pattern.regex.search(path) if match: new_path = path[match.end():] for pattern in self.url_patterns: if isinstance(pattern, AppRegexURLResolver): try: return pattern.resolve_page_id(new_path) except Resolver404: pass else: try: sub_match = pattern.resolve(new_path) except Resolver404 as e: tried_match = e.args[0].get('tried') if tried_match is not None: tried.extend([[pattern] + t for t in tried_match]) else: tried.extend([pattern]) else: if sub_match: return getattr(pattern, 'page_id', None) pattern = getattr(pattern, 'pattern', pattern) tried.append(pattern.regex.pattern) raise Resolver404({'tried': tried, 'path': new_path})
def redirect_view(request, slug): if False: pass # if SuperlandingSettings.get_solo().enabled: # return Superlending else: try: object = Landing.objects.get(slug=slug) object_list = query_landing(object) paginator = Paginator(object_list, 30) page = request.GET.get('page') try: object_list = paginator.page(page) except PageNotAnInteger: object_list = paginator.page(1) except EmptyPage: object_list = paginator.page(paginator.num_pages) context = { 'object': object, 'object_list': object_list, 'seo': get_seo(request) or object } return render(request, 'landing/multilending.html', context) except ObjectDoesNotExist: current_site = get_current_site(request) full_path = request.get_full_path() r = get_object_or_404(Redirect, site=current_site, new_path__icontains=full_path) view, args, kwargs = resolve(r.old_path) if not view.__dict__: raise Resolver404() kwargs['request'] = request return view(*args, **kwargs)
def get(self, request, *args, **kwargs): """ deze functie handelt het GET verzoek af met de extra parameters (bevinding, op_pagina) retourneert het formulier """ if 'op_pagina' not in kwargs: # een gebruiker kan via de formulier-url bij deze GET functie komen # stuur ze weg raise Resolver404() gebruiker_naam = request.user.get_account_full_name() # bewaar twee parameters in de sessie - deze blijven server-side request.session['feedback_op_pagina'] = kwargs['op_pagina'] request.session['feedback_gebruiker'] = gebruiker_naam # geef het formulier aan de gebruiker om in te vullen form = SiteFeedbackForm(initial={'bevinding': '6'}) bev = kwargs['bevinding'] context = { 'form': form, 'formulier_url': reverse('Overig:feedback-formulier'), # URL voor de POST 'gebruiker_naam': gebruiker_naam, 'check_0': (bev == 'plus'), 'check_1': (bev == 'nul'), 'check_2': (bev == 'min') } menu_dynamics(request, context) return render(request, self.template_name, context)
def get_response(cls, request): resolver = get_resolver() resolver_match = resolver.resolve(request.path) callback, callback_args, callback_kwargs = resolver_match if not cls.check_resolver_match(callback, callback_args, callback_kwargs): raise Resolver404({'path': request.path}) request.resolver_match = resolver_match response = callback(request, *callback_args, **callback_kwargs) return response
def resolve(self, *args, **kwargs): # noqa D102 result = super(ModuleURLResolver, self).resolve(*args, **kwargs) if result and not getattr(self._module, 'installed', True): raise Resolver404({'message': 'Module not installed'}) result.url_name = ModuleMatchName(result.url_name) result.url_name.module = self._module return result
def get(request, *args, **kwargs): code = kwargs['code'] if code == '403a': raise PermissionDenied('test') if code == '403b': raise PermissionDenied() if code == '404a': raise Http404('test') if code == '404b': raise Http404() if code == '404c': raise Resolver404() if code == '500': # pragma: no branch # nog geen exceptie gevonden die hiervoor gebruikt kan worden return site_handler500_internal_server_error(request, None) raise Resolver404('Niet ondersteund code')
def pageNotFound(request, exception: Resolver404 = None): context = dict( error="Page Not Found", code="404", message="It looks like you found a glitch in the matrix..." ) if isinstance(exception, Resolver404): exception = exception.args[0] if isinstance(exception, dict): context['error'] = exception.get('path', '') + " Not Found" return render( request, "error.html", context=context, status=404 )
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.user.is_staff: context['is_staff'] = True try: opdracht_pk = int( kwargs['opdracht_pk'][:6]) # afkappen voor veiligheid if self.request.user.is_staff: opdracht = (Opdracht.objects.select_related('bron').get( pk=opdracht_pk)) else: opdracht = (Opdracht.objects.select_related('bron').get( pk=opdracht_pk, eigenaar=self.request.user)) # alleen eigen producten except (ValueError, Opdracht.DoesNotExist): raise Resolver404() context['opdracht'] = opdracht inbox = opdracht.bron try: data = json.loads(inbox.mail_text) except json.JSONDecodeError: context['inbox_error'] = 'Kan de mail niet tonen (fout 1)' else: # haal de plain-text uit de mail en ignore de rest try: body = data['TextBody'] except KeyError: context['inbox_error'] = 'Kan de mail niet tonen (fout 2)' else: body = body.replace('\r\n\r\n', '\n') context['inbox_body'] = body.splitlines() if not opdracht.is_afgehandeld: if not opdracht.is_vrijgegeven_voor_levering: context['url_vrijgeven'] = reverse( 'Producten:opdracht-vrijgeven', kwargs={'opdracht_pk': opdracht.pk}) context['url_opnieuw_analyseren'] = reverse( 'Producten:opnieuw-analyseren', kwargs={'opdracht_pk': opdracht.pk}) context['url_terug'] = reverse('Producten:opdrachten') return context
def _resolver_resolve_to_name(self, path): tried = [] match = self.regex.search(path) if match: new_path = path[match.end():] for pattern in self.url_patterns: try: name = _pattern_resolve_to_name(pattern, new_path) except Resolver404 as e: tried.extend([(pattern.regex.pattern + ' ' + t) for t in e.args[0]['tried']]) else: if name: return name tried.append(pattern.regex.pattern) raise Resolver404({'tried': tried, 'path': new_path})
def add_contributors(item,contributor_data): root = self.request.build_absolute_uri('/') for c in contributor_data: if c['profile_url'][:len(root)]==root: rest = c['profile_url'][len(root):] try: match = resolve(rest) if match.url_name != 'view_profile': raise Resolver404() pk = match.kwargs['pk'] user = User.objects.get(pk=pk) Contributor.objects.create(item=item,user=user) except (Resolver404,User.DoesNotExist): Contributor.objects.create(item=item,name=c['name'],profile_url=c['profile_url']) else: Contributor.objects.create(item=item,name=c['name'],profile_url=c['profile_url'])
def _resolver_resolve_to_name(resolver, path): tried = [] match = get_regex(resolver).search(path) if match: new_path = path[match.end():] for pattern in resolver.url_patterns: try: if isinstance(pattern, URLPattern): name = _pattern_resolve_to_name(pattern, new_path) elif isinstance(pattern, URLResolver): name = _resolver_resolve_to_name(pattern, new_path) except Resolver404 as e: tried.extend([(get_regex(pattern).pattern + ' ' + t) for t in e.args[0]['tried']]) else: if name: return name tried.append(get_regex(pattern).pattern) raise Resolver404({'tried': tried, 'path': new_path})
def get(self, request, *args, **kwargs): """ deze functie handelt het GET verzoek af met de extra parameters (bevinding, op_pagina) retourneert het formulier """ if 'op_pagina' not in kwargs: # een gebruiker kan via de POST-url voor het formulier bij deze GET functie komen # stuur ze weg raise Resolver404() if request.user.is_authenticated: gebruiker_naam = request.user.get_account_full_name() else: gebruiker_naam = 'Niet bekend (anoniem)' # bewaar twee parameters in de sessie - deze blijven server-side request.session['feedback_op_pagina'] = kwargs['op_pagina'] request.session['feedback_gebruiker'] = gebruiker_naam # geef het formulier aan de gebruiker om in te vullen form = SiteFeedbackForm( initial={'bevinding': '6'}) # TODO: werkt niet met materialcss radiobuttons bev = kwargs['bevinding'] context = { 'form': form, 'formulier_url': reverse('Overig:feedback-formulier'), # URL voor de POST 'gebruiker_naam': gebruiker_naam, 'check_0': (bev == 'plus' ), # TODO: workaround for materializecss radiobuttons in Django 'check_1': (bev == 'nul'), # see comment in site-feedback-formulier.dtl 'check_2': (bev == 'min') } return render(request, self.template_name, context)
def get(self, request, what=None): if not request.user.is_authenticated(): return redirect('login_user') if not what: raise Resolver404('Not Found') if what == 'admin_dashboard': if not request.user.user_type == "admin": raise PermissionDenied('permission denied') # preparing report data loan_rate = Decimal(0) ir = Interest.objects.all() if ir and ir.count() > 0: ir = ir[0] loan_rate = ir.interest monthly_rate, today, start_date, months_in_operation, form = monthly_rate_today( ) total_membership, expected_total_contributions = expected_contributions( monthly_rate) banked_cash_at_hand, un_banked_cash_at_hand, expected_total_cash_at_hand, variance = cash_at_hand( ) expenses = Expenses.objects.all().order_by('-date') temp_vars = { 'logo': os.path.join(MEDIA_URL, 'logo-web.png'), 'user': request.user, 'title': COMPANY_NAME, 'loan_rate': loan_rate, 'today': today, 'start_date': start_date, 'months_in_operation': months_in_operation, 'total_membership': total_membership, 'monthly_rate': monthly_rate, 'expected_total_contributions': expected_total_contributions, 'expected_total_cash_at_hand': expected_total_cash_at_hand, 'banked_cash_at_hand': banked_cash_at_hand, 'unbanked_cash_at_hand': un_banked_cash_at_hand, 'variance': variance, 'expenses': expenses, 'all_contributions': all_contributions(monthly=monthly_rate, today=today), 'all_loans': all_loans(), 'all_investments': all_investments(), 'income_statements': calculate_income_statement(), } try: template = get_template('print/dashboard.html') out_put = template.render(temp_vars) # using xhtml2pdf and not weasyprint to generate admin summary PDF file name = '{0}.pdf'.format(generate_report_filename()) response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'inline; filename="{0}.pdf"'.format( name) pisaStatus = pisa.CreatePDF(out_put, dest=response, link_callback=link_callback, default_css=my_css) # if error then show some funy view if pisaStatus.err: return HttpResponse('We had some errors <pre>' + out_put + '</pre>') return response except Exception as ex: raise Resolver404( 'Error Occurered while creating Admin PDF Template: ' + str(ex.message)) elif what == 'user_profile': # preparing report data today = date.today() contribution = get_user_contributions(request.user, today) investment = get_user_investments(request) loan = get_user_loans(request) temp_vars = { 'logo': os.path.join(MEDIA_URL, 'logo-web.png'), 'MEDIA_URL': MEDIA_URL, 'user': request.user, 'title': COMPANY_NAME, 'today': today, 'contributions': contribution['contributions'], 'summary': contribution['summary'], 'i_manage': investment['i_manage'], 'a_member': investment['a_member'], 'others': investment['other'], 'on_loan': loan['on_loan'], 'on_pay': loan['on_pay'], 'credit': loan['credit'], } try: template = get_template('print/user_profile.html') out_put = template.render(temp_vars) # using weasyprint to print the user profile PDF page try: name = '{0}.pdf'.format(generate_report_filename()) HTML(string=out_put, base_url=request.build_absolute_uri()).write_pdf( os.path.join(REPORT_ROOT, name)) fs = FileSystemStorage(REPORT_ROOT) with fs.open(name) as pdf: response = HttpResponse(pdf, content_type='application/pdf') response[ 'Content-Disposition'] = 'inline; filename={0}.pdf'.format( name) return response except Exception as e: raise Resolver404( 'An Error Occurred... While processing the file' + str(e.message)) except TemplateDoesNotExist: raise Resolver404('User Template Not Found') else: raise Resolver404('URL Not Understood')
def get(self, request, what=None): if not request.user.is_authenticated(): return redirect('login_user') if not what: raise Resolver404('Not Found') if what == 'users': if not request.user.has_perms(['can_view_user']): raise PermissionDenied('permission denied') self.query_sets = User.objects.all() self.columns = [ 'account_id', 'first_name', 'last_name', 'email', 'contact', 'address', 'date_joined', 'username', 'user_status' ] self.file_name = 'members-list-' + self.date_today elif what == 'contributions': if not request.user.has_perms(['can_view_contributions']): raise PermissionDenied('permission denied') self.query_sets = Contribution.objects.all() self.columns = [ 'user_id', 'contribution_date', 'deposit', 'penalty', 'total' ] self.file_name = 'contributions-list-' + self.date_today elif what == 'investments': if not request.user.has_perms(['can_view_investments']): raise PermissionDenied('permission denied') self.file_name = 'investments-list-' + self.date_today return excel.make_response_from_a_table(Investment, self.file_type, file_name=self.file_name) elif what == 'loans': if not request.user.has_perms(['can_view_loans']): raise PermissionDenied('permission denied') self.query_sets = Loan.objects.all() self.columns = [ 'user_id', 'loan_date', 'loan_duration', 'loan_amount', 'amount_paid', 'sur_charge', 'sub_total', 'loan_interest', 'total_amount', 'outstanding_balance', 'loan_status' ] self.file_name = 'Loans-list-' + self.date_today elif what == 'user_contributions': self.query_sets = Contribution.objects.filter(user=request.user) self.columns = [ 'user_id', 'contribution_date', 'deposit', 'penalty', 'total' ] self.file_name = 'my_contributions-' + self.date_today else: raise Resolver404('URL Not Understood') if not self.query_sets or not self.columns or not self.file_name: raise Resolver404('Could Not export data') try: return excel.make_response_from_query_sets( self.query_sets, self.columns, self.file_type, file_name=self.file_name) except Exception as e: raise e
def handle_no_permission(self): """ gebruiker heeft geen toegang --> doe alsof dit niet bestaat """ raise Resolver404()
def raiseError404(request): raise Resolver404("Trial Error")
def handle(data): raise Resolver404("GOT A 404")
def process(self, request, **kw): page_url = self.parent.get_absolute_url() # Provide a way for appcontent items to customize URL processing by # altering the perceived path of the page: if "path_mapper" in self.app_config: path_mapper = get_object(self.app_config["path_mapper"]) path, page_url = path_mapper( request.path, page_url, appcontent_parameters=self.parameters ) else: path = request._feincms_extra_context["extra_path"] # Resolve the module holding the application urls. urlconf_path = self.app_config.get("urls", self.urlconf_path) try: fn, args, kwargs = resolve(path, urlconf_path) except (ValueError, Resolver404): raise Resolver404( str("Not found (resolving %r in %r failed)") % (path, urlconf_path) ) # Variables from the ApplicationContent parameters are added to request # so we can expose them to our templates via the appcontent_parameters # context_processor request._feincms_extra_context.update(self.parameters) # Save the application configuration for reuse elsewhere request._feincms_extra_context.update( {"app_config": dict(self.app_config, urlconf_path=self.urlconf_path)} ) view_wrapper = self.app_config.get("view_wrapper", None) if view_wrapper: fn = partial( get_object(view_wrapper), view=fn, appcontent_parameters=self.parameters ) output = fn(request, *args, **kwargs) if isinstance(output, HttpResponse): if self.send_directly(request, output): return output elif output.status_code == 200: if self.unpack(request, output) and "view" in kw: # Handling of @unpack and UnpackTemplateResponse kw["view"].template_name = output.template_name kw["view"].request._feincms_extra_context.update( output.context_data ) else: # If the response supports deferred rendering, render the # response right now. We do not handle template response # middleware. if hasattr(output, "render") and callable(output.render): output.render() self.rendered_result = mark_safe(output.content.decode("utf-8")) self.rendered_headers = {} # Copy relevant headers for later perusal for h in ("Cache-Control", "Last-Modified", "Expires"): if h in output: self.rendered_headers.setdefault(h, []).append(output[h]) elif isinstance(output, tuple) and "view" in kw: kw["view"].template_name = output[0] kw["view"].request._feincms_extra_context.update(output[1]) else: self.rendered_result = mark_safe(output) return True # successful