当前位置: 首页>>代码示例>>Python>>正文


Python http.HttpResponseServerError方法代码示例

本文整理汇总了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()) 
开发者ID:elsigh,项目名称:browserscope,代码行数:21,代码来源:user_tests.py

示例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) 
开发者ID:elsigh,项目名称:browserscope,代码行数:23,代码来源:gaeunit.py

示例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 %}. 
开发者ID:mozilla,项目名称:telemetry-analysis-service,代码行数:23,代码来源:views.py

示例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") 
开发者ID:easy-as-python,项目名称:django-webmention,代码行数:27,代码来源:views.py

示例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)) 
开发者ID:zulip,项目名称:zulip,代码行数:22,代码来源:auth.py

示例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']) 
开发者ID:IntuitDeveloper,项目名称:OAuth2PythonSampleApp,代码行数:25,代码来源:views.py

示例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: */ 
开发者ID:mmohrhard,项目名称:crash,代码行数:24,代码来源:views.py

示例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({}))) 
开发者ID:django-leonardo,项目名称:django-leonardo,代码行数:20,代码来源:defaults.py

示例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 %}. 
开发者ID:blackye,项目名称:luscan-devel,代码行数:19,代码来源:defaults.py

示例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) 
开发者ID:mathiasertl,项目名称:django-ca,代码行数:26,代码来源:views.py

示例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 
开发者ID:hacktoolkit,项目名称:django-htk,代码行数:20,代码来源:pdf_utils.py

示例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}) 
开发者ID:kirstykitto,项目名称:CLAtoolkit,代码行数:26,代码来源:views.py

示例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')) 
开发者ID:hujingguang,项目名称:OpsSystem,代码行数:27,代码来源:views.py

示例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() 
开发者ID:archesproject,项目名称:arches,代码行数:33,代码来源:concept.py

示例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&notify=%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) 
开发者ID:elsigh,项目名称:browserscope,代码行数:39,代码来源:user_tests.py


注:本文中的django.http.HttpResponseServerError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。