本文整理匯總了Python中django.http.HttpResponseServerError方法的典型用法代碼示例。如果您正苦於以下問題:Python http.HttpResponseServerError方法的具體用法?Python http.HttpResponseServerError怎麽用?Python http.HttpResponseServerError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.http
的用法示例。
在下文中一共展示了http.HttpResponseServerError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: Table
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseServerError [as 別名]
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())
示例2: django_test_runner
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseServerError [as 別名]
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)
示例3: server_error
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseServerError [as 別名]
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 %}.
示例4: receive
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseServerError [as 別名]
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")
示例5: saml_sp_metadata
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseServerError [as 別名]
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))
示例6: apiCall
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseServerError [as 別名]
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'])
示例7: upload_file
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseServerError [as 別名]
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: */
示例8: server_error
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseServerError [as 別名]
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({})))
示例9: server_error
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseServerError [as 別名]
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 %}.
示例10: get
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseServerError [as 別名]
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)
示例11: render_to_pdf_response_pisa
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseServerError [as 別名]
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
示例12: updateclientapp
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseServerError [as 別名]
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})
示例13: refresh_host_info
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseServerError [as 別名]
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'))
示例14: add_concepts_from_sparql_endpoint
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseServerError [as 別名]
def add_concepts_from_sparql_endpoint(request, conceptid):
if request.method == "POST":
json = request.body
if json is not None:
data = JSONDeserializer().deserialize(json)
parentconcept = Concept({"id": conceptid, "nodetype": data["model"]["nodetype"]})
if parentconcept.nodetype == "Concept":
relationshiptype = "narrower"
elif parentconcept.nodetype == "ConceptScheme":
relationshiptype = "hasTopConcept"
provider = get_sparql_providers(data["endpoint"])
try:
parentconcept.subconcepts = provider.get_concepts(data["ids"])
except Exception as e:
return HttpResponseServerError(e.message)
for subconcept in parentconcept.subconcepts:
subconcept.relationshiptype = relationshiptype
parentconcept.save()
parentconcept.index()
return JSONResponse(parentconcept, indent=4)
else:
return HttpResponseNotAllowed(["POST"])
return HttpResponseNotFound()
示例15: WebPagetest
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpResponseServerError [as 別名]
def WebPagetest(request, key):
"""Sends an API request to run one's test page on WebPagetest.org."""
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)
current_user = users.get_current_user()
if (test.user.key().name() != current_user.user_id() and not
users.is_current_user_admin()):
return http.HttpResponse('You can\'t play with tests you don\'t own')
# Help users autorun their tests by adding autorun=1 to the test url.
test_url_parts = list(urlparse.urlparse(test.url))
test_url_query = dict(cgi.parse_qsl(test_url_parts[4]))
test_url_query.update({'autorun': '1'})
test_url_parts[4] = urllib.urlencode(test_url_query)
test_url = urlparse.urlunparse(test_url_parts)
# TODO(elsigh): callback url.
webpagetest_url = ('%s&url=%s¬ify=%s' %
(WEBPAGETEST_URL, test_url,
urllib.quote('elsigh@gmail.com')))
webpagetests = {}
# See http://goo.gl/EfK1r for WebPagetest instructions.
for location in WEBPAGETEST_LOCATIONS:
url = '%s&location=%s' % (webpagetest_url, location)
response = urlfetch.fetch(url)
json = simplejson.loads(response.content)
webpagetests[location] = json
params = {
'test': test,
'webpagetests': webpagetests
}
return util.Render(request, 'user_test_webpagetest.html', params)