Python django.http.HttpResponseServerError() Examples
The following are 30
code examples of django.http.HttpResponseServerError().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.http
, or try the search function
.
Example #1
Source File: views.py From OpsSystem with MIT License | 6 votes |
def refresh_host_info(request): salt=SaltByLocalApi('/etc/salt/master') host_info_dict=salt.get_host_info() for host,info_list in host_info_dict.iteritems(): if HostInfoModel.objects.filter(hostname=host.strip('')).count() >0: continue if HostInfoModel.objects.filter(hostname=host.strip('')).count()==0: if info_list[5] != '' and info_list[6] !='' and info_list[7] != '': host_info=HostInfoModel(hostname=host, ipaddress=info_list[1], cpuinfo=info_list[3], meminfo=info_list[4], group=info_list[5], osinfo=info_list[2], area=info_list[6], usage=info_list[7]) try: host_info.save() except Exception as e: return HttpResponseServerError(request) all_host=HostInfoModel.objects.all() for host in all_host: if host.hostname not in host_info_dict: host.delete() return HttpResponseRedirect(reverse('salts:host_info'))
Example #2
Source File: views.py From telemetry-analysis-service with Mozilla Public License 2.0 | 6 votes |
def server_error(request, template_name=ERROR_500_TEMPLATE_NAME): """ 500 error handler. :template: :file:`500.html` """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: if template_name != ERROR_500_TEMPLATE_NAME: # Reraise if it's a missing custom template. raise return http.HttpResponseServerError( "<h1>Server Error (500)</h1>", content_type="text/html" ) return http.HttpResponseServerError(template.render(request=request)) # This can be called when CsrfViewMiddleware.process_view has not run, # therefore need @requires_csrf_token in case the template needs # {% csrf_token %}.
Example #3
Source File: views.py From django-webmention with MIT License | 6 votes |
def receive(request): if "source" in request.POST and "target" in request.POST: source = request.POST.get("source") target = request.POST.get("target") webmention = None if not url_resolves(target): return HttpResponseBadRequest("Target URL did not resolve to a resource on the server") try: try: webmention = WebMentionResponse.objects.get(source=source, response_to=target) except WebMentionResponse.DoesNotExist: webmention = WebMentionResponse() response_body = fetch_and_validate_source(source, target) webmention.update(source, target, response_body) return HttpResponse("The webmention was successfully received", status=202) except (SourceFetchError, TargetNotFoundError) as e: webmention.invalidate() return HttpResponseBadRequest(str(e)) except Exception as e: return HttpResponseServerError(str(e)) else: return HttpResponseBadRequest("webmention source and/or target not in request")
Example #4
Source File: pdf_utils.py From django-htk with MIT License | 6 votes |
def render_to_pdf_response_pisa(template_name, context_dict): """Render to a PDF response using Pisa Caveat: xhtml2pdf / pisa seems to not be well-maintained and does not handle CSS3 https://github.com/xhtml2pdf/xhtml2pdf/issues/44 PyPI: https://pypi.python.org/pypi/pisa/ """ import cStringIO as StringIO from xhtml2pdf import pisa html = generate_html_from_template(template_name, context_dict) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode('utf-8')), result) if pdf: response = HttpResponse(result.getvalue(), mimetype='application/pdf') else: response = HttpResponseServerError('Error generating PDF file') return response
Example #5
Source File: auth.py From zulip with Apache License 2.0 | 6 votes |
def saml_sp_metadata(request: HttpRequest, **kwargs: Any) -> HttpResponse: # nocoverage """ This is the view function for generating our SP metadata for SAML authentication. It's meant for helping check the correctness of the configuration when setting up SAML, or for obtaining the XML metadata if the IdP requires it. Taken from https://python-social-auth.readthedocs.io/en/latest/backends/saml.html """ if not saml_auth_enabled(): return redirect_to_config_error("saml") complete_url = reverse('social:complete', args=("saml",)) saml_backend = load_backend(load_strategy(request), "saml", complete_url) metadata, errors = saml_backend.generate_metadata_xml() if not errors: return HttpResponse(content=metadata, content_type='text/xml') return HttpResponseServerError(content=', '.join(errors))
Example #6
Source File: views.py From django-ca with GNU General Public License v3.0 | 6 votes |
def get(self, request, serial): encoding = parse_encoding(request.GET.get('encoding', self.type)) cache_key = get_crl_cache_key(serial, algorithm=self.digest, encoding=encoding, scope=self.scope) crl = cache.get(cache_key) if crl is None: ca = self.get_object() encoding = parse_encoding(self.type) crl = ca.get_crl(expires=self.expires, algorithm=self.digest, password=self.password, scope=self.scope) crl = crl.public_bytes(encoding) cache.set(cache_key, crl, self.expires) content_type = self.content_type if content_type is None: if self.type == Encoding.DER: content_type = 'application/pkix-crl' elif self.type == Encoding.PEM: content_type = 'text/plain' else: # pragma: no cover # DER/PEM are all known encoding types, so this shouldn't happen return HttpResponseServerError() return HttpResponse(crl, content_type=content_type)
Example #7
Source File: views.py From CLAtoolkit with GNU General Public License v3.0 | 6 votes |
def updateclientapp(request): if request.method == 'POST': post_data = request.POST.copy() provider = post_data.pop("provider")[0] app = ClientApp.objects.get(provider=provider) form = RegisterClientAppForm(request.POST, instance=app) if form.is_valid(): app = form.save(commit=False) app.save() return redirect('/dashboard/myunits') else: return HttpResponse("ERROR: %s" % (form.errors)) else: provider_id = request.GET.get("provider_id") try: app = ClientApp.objects.get(id=provider_id) form = RegisterClientAppForm(instance=app) except ClientApp.DoesNotExist: return HttpResponseServerError('Error: Provider id not found') return render(request, 'clatoolkit/registerclientapp.html', {'registered': False, 'verb': 'Update', 'form': form})
Example #8
Source File: views.py From OAuth2PythonSampleApp with Apache License 2.0 | 6 votes |
def apiCall(request): access_token = request.session.get('accessToken', None) if access_token is None: return HttpResponse('Your Bearer token has expired, please initiate C2QB flow again') realmId = request.session['realmId'] if realmId is None: return HttpResponse('No realm ID. QBO calls only work if the accounting scope was passed!') refresh_token = request.session['refreshToken'] company_info_response, status_code = getCompanyInfo(access_token, realmId) if status_code >= 400: # if call to QBO doesn't succeed then get a new bearer token from refresh token and try again bearer = getBearerTokenFromRefreshToken(refresh_token) updateSession(request, bearer.accessToken, bearer.refreshToken, realmId) company_info_response, status_code = getCompanyInfo(bearer.accessToken, realmId) if status_code >= 400: return HttpResponseServerError() company_name = company_info_response['CompanyInfo']['CompanyName'] address = company_info_response['CompanyInfo']['CompanyAddr'] return HttpResponse('Company Name: ' + company_name + ', Company Address: ' + address['Line1'] + ', ' + address[ 'City'] + ', ' + ' ' + address['PostalCode'])
Example #9
Source File: defaults.py From luscan-devel with GNU General Public License v2.0 | 6 votes |
def server_error(request, template_name='500.html'): """ 500 error handler. Templates: :template:`500.html` Context: None """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: return http.HttpResponseServerError('<h1>Server Error (500)</h1>') return http.HttpResponseServerError(template.render(Context({}))) # This can be called when CsrfViewMiddleware.process_view has not run, # therefore need @requires_csrf_token in case the template needs # {% csrf_token %}.
Example #10
Source File: gaeunit.py From browserscope with Apache License 2.0 | 6 votes |
def django_test_runner(request): unknown_args = [arg for (arg, v) in request.REQUEST.items() if arg not in ("format", "package", "name")] if len(unknown_args) > 0: errors = [] for arg in unknown_args: errors.append(_log_error("The request parameter '%s' is not valid." % arg)) from django.http import HttpResponseNotFound return HttpResponseNotFound(" ".join(errors)) format = request.REQUEST.get("format", "html") package_name = request.REQUEST.get("package") test_name = request.REQUEST.get("name") if format == "html": return _render_html(package_name, test_name) elif format == "plain": return _render_plain(package_name, test_name) else: error = _log_error("The format '%s' is not valid." % cgi.escape(format)) from django.http import HttpResponseServerError return HttpResponseServerError(error)
Example #11
Source File: views.py From crash with Mozilla Public License 2.0 | 6 votes |
def upload_file(request): if request.method != 'POST': return HttpResponseNotAllowed('Only POST here') form = UploadFileForm(request.POST, request.FILES) if not form.is_valid(): logger.error("form is invalid with error: " + str(form.errors)) return HttpResponseBadRequest() file = request.FILES['upload_file_minidump'] try: crash_id = str(create_database_entry(file, form)) except (InvalidVersionException) as e: logger.error("invalid version exception " + str(e)) return HttpResponseServerError(str(e)) logger.info("uploaded crash: " + crash_id) return HttpResponse('Crash-ID=%s'%(crash_id)) # vim:set shiftwidth=4 softtabstop=4 expandtab: */
Example #12
Source File: defaults.py From django-leonardo with BSD 3-Clause "New" or "Revised" License | 6 votes |
def server_error(request, template_name='500.html'): """ 500 error handler. Templates: :template:`500.html` Context: None """ response = render_in_page(request, template_name) if response: return response try: template = loader.get_template(template_name) except TemplateDoesNotExist: return http.HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html') return http.HttpResponseServerError(template.render(Context({})))
Example #13
Source File: user_tests.py From browserscope with Apache License 2.0 | 6 votes |
def Table(request, key): """The User Test results table. Args: request: The request object. key: The Test.key() string. """ test = models.user_test.Test.get_mem(key) if not test: msg = 'No test was found with test_key %s.' % key return http.HttpResponseServerError(msg) params = { 'hide_nav': True, 'hide_footer': True, 'test': test, } return util.GetResults(request, 'user_test_table.html', params, test.get_test_set())
Example #14
Source File: views.py From CLAtoolkit with GNU General Public License v3.0 | 5 votes |
def myunits(request): context = RequestContext(request) # Get a users memberships to unit offerings memberships = UnitOfferingMembership.objects.filter(user=request.user, unit__enabled=True).select_related('unit') role = request.user.userprofile.role show_dashboardnav = False shownocontentwarning = False trello_attached = not request.user.userprofile.trello_account_name == '' github_attached = False tokens = OfflinePlatformAuthToken.objects.filter( user_smid=request.user.userprofile.github_account_name, platform=xapi_settings.PLATFORM_GITHUB) if len(tokens) == 1: github_attached = True has_token_list = {} for membership in memberships: token = UserAccessToken_LRS.objects.filter(user = request.user, clientapp = membership.unit.lrs_provider) has_user_token = True if len(token) == 1 else False if len(token) > 1: return HttpResponseServerError('More than one access token were found.') app = membership.unit.lrs_provider has_token_list[membership.unit.code] = {'lrs': app.provider, 'has_user_token': has_user_token} # if student check if the student has imported data if role == 'Student': if LearningRecord.objects.filter(user=request.user).count() == 0: shownocontentwarning = True context_dict = {'title': "My Units", 'memberships': memberships, 'show_dashboardnav': show_dashboardnav, 'shownocontentwarning': shownocontentwarning, 'role': role, 'trello_attached_to_acc': trello_attached, 'has_token_list': has_token_list, 'github_attached': github_attached} return render_to_response('dashboard/myunits.html', context_dict, context)
Example #15
Source File: views.py From PonyConf with Apache License 2.0 | 5 votes |
def volunteer_email_preview(request): form = PreviewVolunteerMailForm(request.POST or None) if not form.is_valid(): return HttpResponseServerError() volunteer = get_object_or_404(Volunteer, site=request.conference.site, pk=form.cleaned_data['volunteer']) preview = volunteer_email_render_preview(volunteer, form.cleaned_data['subject'], form.cleaned_data['body']) return HttpResponse(preview)
Example #16
Source File: views.py From PonyConf with Apache License 2.0 | 5 votes |
def talk_email_preview(request): form = PreviewTalkMailForm(request.POST or None) if not form.is_valid(): return HttpResponseServerError() speaker = get_object_or_404(Participant, site=request.conference.site, pk=form.cleaned_data['speaker']) talk = get_object_or_404(Talk, site=request.conference.site, pk=form.cleaned_data['talk']) preview = talk_email_render_preview(talk, speaker, form.cleaned_data['subject'], form.cleaned_data['body']) return HttpResponse(preview)
Example #17
Source File: views.py From PonyConf with Apache License 2.0 | 5 votes |
def speaker_email_preview(request): form = PreviewSpeakerMailForm(request.POST or None) if not form.is_valid(): return HttpResponseServerError() speaker = get_object_or_404(Participant, site=request.conference.site, pk=form.cleaned_data['speaker']) preview = speaker_email_render_preview(speaker, form.cleaned_data['subject'], form.cleaned_data['body']) return HttpResponse(preview)
Example #18
Source File: views.py From wharf with GNU Affero General Public License v3.0 | 5 votes |
def status(request): try: check_status() return HttpResponse("All good") except timeout_decorator.TimeoutError: return HttpResponseServerError("Timeout trying to get status")
Example #19
Source File: views.py From aries-vcr with Apache License 2.0 | 5 votes |
def error_view(request): if request.method == 'POST': post_data = request.body print(post_data) data = json.loads(post_data) if "subscription" in data and "test" in data["subscription"]: return JsonResponse({"thanks": "you"}) else: return HttpResponseServerError() return JsonResponse({"method": "notsupported"})
Example #20
Source File: views.py From aries-vcr with Apache License 2.0 | 5 votes |
def random_view(request): if request.method == 'POST': post_data = request.body print(post_data) data = json.loads(post_data) if "subscription" in data and "test" in data["subscription"]: return JsonResponse({"thanks": "you"}) else: if 0.5 < random.random(): return JsonResponse({"thanks": "you"}) else: return HttpResponseServerError() return JsonResponse({"method": "notsupported"})
Example #21
Source File: admin.py From cartoview with BSD 2-Clause "Simplified" License | 5 votes |
def uninstall_selected(modeladmin, request, queryset): for app in queryset: try: app_store = app.store.id if app.store else None installer = AppInstaller( app.name, store_id=app_store, user=request.user, version=app.version) installer.uninstall() except Exception as e: return HttpResponseServerError(e.message)
Example #22
Source File: views.py From CLAtoolkit with GNU General Public License v3.0 | 5 votes |
def lrs_oauth_callback(request): import os import urlparse user_id = request.user.id user = User.objects.get(id=user_id) status = request.GET.get('status') if status is not None and status == 'fail': return HttpResponseServerError('Could not get access token.') request_token = OAuthTempRequestToken.objects.get(user_id=user) verifier = request.GET.get('oauth_verifier') token = oauth.Token(request_token.token, request_token.secret) request_token.delete() #delete temp token token.set_verifier(verifier) # Get Consumer info #Todo: change (most definitely) (IMPORTANT!!) # consumer_key, consumer_secret = get_consumer_key_and_secret() app = ClientApp.objects.get(id = request_token.clientapp.id) client = oauth.Client(oauth.Consumer(app.get_key(), app.get_secret()), token) # Exchange request_token for authed and verified access_token resp,content = client.request(app.get_access_token_url(), "POST") access_token = dict(urlparse.parse_qsl(content)) if access_token['oauth_token']: UserAccessToken_LRS(user=user, access_token=access_token['oauth_token'], access_token_secret=access_token['oauth_token_secret'], clientapp = app).save() from django.shortcuts import render_to_response return render_to_response('xapi/get_access_token_successful.html')
Example #23
Source File: views.py From django-freeze with MIT License | 5 votes |
def generate_static_site(request): if request.user and request.user.is_staff and request.user.is_active: try: writer.write( scanner.scan(), html_in_memory = settings.FREEZE_ZIP_ALL, zip_all = settings.FREEZE_ZIP_ALL, zip_in_memory = False) return HttpResponse() except IOError: return HttpResponseServerError() else: raise PermissionDenied
Example #24
Source File: defaults.py From python2017 with MIT License | 5 votes |
def server_error(request, template_name=ERROR_500_TEMPLATE_NAME): """ 500 error handler. Templates: :template:`500.html` Context: None """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: if template_name != ERROR_500_TEMPLATE_NAME: # Reraise if it's a missing custom template. raise return http.HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html') return http.HttpResponseServerError(template.render())
Example #25
Source File: tests.py From edx-analytics-dashboard with GNU Affero General Public License v3.0 | 5 votes |
def test_process_template_response_with_error(self): """ The middleware should NOT process error responses. """ response = http.HttpResponseServerError() request = http.HttpRequest() response = self.middleware.process_template_response(request, response) self.assertFalse(hasattr(response, 'context_data'))
Example #26
Source File: views.py From Kiwi with GNU General Public License v2.0 | 5 votes |
def server_error(request): # pylint: disable=missing-permission-required """ Render the error page with request object which supports static URLs so we can load a nice picture. """ template = loader.get_template('500.html') return http.HttpResponseServerError(template.render({}, request))
Example #27
Source File: pdf_utils.py From django-htk with MIT License | 5 votes |
def render_to_pdf_response_pdfkit(template_name, context_dict, css_files=None): """Render to a PDF response using pdfkit `context_dict` is expected to be generated by htk.view_helpers.wrap_data PyPI: https://pypi.python.org/pypi/pdfkit Installation: https://github.com/JazzCore/python-pdfkit/wiki/Using-wkhtmltopdf-without-X-server Outstanding Issues: - """ import pdfkit html = generate_html_from_template(template_name, context_dict) base_url = context_dict['request']['base_uri'] #html = rewrite_relative_urls_as_absolute(html, base_url) options = { 'page-size' : 'Letter', 'orientation' : 'Portrait', 'margin-top' : '0.75in', 'margin-bottom' : '0.75in', 'margin-left' : '0.50in', 'margin-right' : '0.50in', 'encoding' : 'UTF-8', #'print_media_type' : False, #'title' : context_dict.get('title', 'PDF'), } pdf = pdfkit.from_string(html.encode('utf-8'), False, options=options, css=css_files) if pdf: response = HttpResponse(pdf, content_type='application/pdf') else: response = HttpResponseServerError('Error generating PDF file') return response
Example #28
Source File: pdf_utils.py From django-htk with MIT License | 5 votes |
def render_url_to_pdf_response(url): from htk.lib.slack.utils import webhook_call webhook_call(text=url) import pdfkit pdf = pdfkit.from_url(url, False, options=WKHTMLTOPDF_OPTIONS) if pdf: response = HttpResponse(pdf, content_type='application/pdf') else: response = HttpResponseServerError('Error generating PDF file') return response
Example #29
Source File: views.py From feedthefox with Mozilla Public License 2.0 | 5 votes |
def custom_500(request): return HttpResponseServerError(render(request, '500.html'))
Example #30
Source File: defaults.py From openhgsenti with Apache License 2.0 | 5 votes |
def server_error(request, template_name='500.html'): """ 500 error handler. Templates: :template:`500.html` Context: None """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: return http.HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html') return http.HttpResponseServerError(template.render())