Python django.http.HttpResponseServerError() Examples

The following are 30 code examples for showing how to use django.http.HttpResponseServerError(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.http , or try the search function .

Example 1
Project: browserscope   Author: elsigh   File: user_tests.py    License: Apache License 2.0 6 votes vote down vote up
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 2
Project: browserscope   Author: elsigh   File: gaeunit.py    License: Apache License 2.0 6 votes vote down vote up
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 3
Project: telemetry-analysis-service   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
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 4
Project: django-webmention   Author: easy-as-python   File: views.py    License: MIT License 6 votes vote down vote up
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 5
Project: zulip   Author: zulip   File: auth.py    License: Apache License 2.0 6 votes vote down vote up
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
Project: OAuth2PythonSampleApp   Author: IntuitDeveloper   File: views.py    License: Apache License 2.0 6 votes vote down vote up
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 7
Project: crash   Author: mmohrhard   File: views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
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 8
Project: django-leonardo   Author: django-leonardo   File: defaults.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 9
Project: luscan-devel   Author: blackye   File: defaults.py    License: GNU General Public License v2.0 6 votes vote down vote up
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
Project: django-ca   Author: mathiasertl   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 11
Project: django-htk   Author: hacktoolkit   File: pdf_utils.py    License: MIT License 6 votes vote down vote up
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 12
Project: CLAtoolkit   Author: kirstykitto   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 13
Project: OpsSystem   Author: hujingguang   File: views.py    License: MIT License 6 votes vote down vote up
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 14
Project: arches   Author: archesproject   File: concept.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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() 
Example 15
Project: browserscope   Author: elsigh   File: user_tests.py    License: Apache License 2.0 5 votes vote down vote up
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) 
Example 16
Project: browserscope   Author: elsigh   File: admin.py    License: Apache License 2.0 5 votes vote down vote up
def DataDumpKeys(request):
  """This is used by bin/data_dump.py to get ResultParent keys."""
  bookmark = request.REQUEST.get('bookmark')
  model_name = request.REQUEST.get('model')
  count = int(request.REQUEST.get('count', 0))
  fetch_limit = int(request.REQUEST.get('fetch_limit', 999))
  created_str = request.REQUEST.get('created', 0)
  created = None
  if created_str:
    created = datetime.datetime.strptime(created_str, '%Y-%m-%d %H:%M:%S')
  models = {
      'UserAgent': UserAgent,
      'ResultParent': ResultParent,
      'ResultTime': ResultTime,
      }
  model = models.get(model_name, UserAgent)
  query = pager.PagerQuery(model, keys_only=True)
  if created:
    query.filter('created >=', created)
    query.order('created')
  try:
    prev_bookmark, results, next_bookmark = query.fetch(fetch_limit, bookmark)
  except db.Timeout:
    logging.warn('db.Timeout during initial fetch.')
    return http.HttpResponseServerError('db.Timeout during initial fetch.')
  response_params = {
      'bookmark': next_bookmark,
      'model': model_name,
      'count': count + len(results),
      'keys': [str(key) for key in results]
      }
  if created_str:
    response_params['created'] = created_str
  return http.HttpResponse(content=simplejson.dumps(response_params),
                           content_type='application/json') 
Example 17
Project: browserscope   Author: elsigh   File: admin.py    License: Apache License 2.0 5 votes vote down vote up
def UpdateStatsCache(request):
  """Load rankers into memcache."""
  category = request.REQUEST.get('category')
  browsers_str = request.REQUEST.get('browsers')
  is_uncached_update = request.REQUEST.get('is_uncached_update')
  if not category:
    logging.info('UpdateStatsCache: Must set category')
    return http.HttpResponseServerError('Must set "category".')
  logging.info('UpdateStatsCache: category=%s, browsers=%s',
               category, browsers_str)
  if not browsers_str:
    logging.info('UpdateStatsCache: Must set "browsers".')
    return http.HttpResponseServerError('Must set "browsers".')
  browsers = browsers_str.split(',')
  if is_uncached_update:
    num_checked_browsers = len(browsers)
    browsers = result_stats.CategoryStatsManager.FindUncachedStats(
        category, browsers)
    logging.debug('Uncached \'%s\' stats (count: %s out of %s): %s',
                  category, len(browsers), num_checked_browsers, browsers)
  # Only process one browser in each task.
  if len(browsers) > 1:
    attempt = 0
    while attempt < 3:
      try:
        taskqueue.Task(params={
            'category': category,
            'browsers': ','.join(browsers[1:]),
            }).add(queue_name='update-stats-cache')
        break
      except:
        attempt += 1
  result_stats.CategoryStatsManager.UpdateStatsCache(category, browsers[:1])
  return http.HttpResponse('Success.') 
Example 18
Project: browserscope   Author: elsigh   File: gaeunit.py    License: Apache License 2.0 5 votes vote down vote up
def _render_html(package_name, test_name):
    suite, error = _create_suite(package_name, test_name, _LOCAL_DJANGO_TEST_DIR)
    if not error:
        content = _MAIN_PAGE_CONTENT % (_test_suite_to_json(suite), _WEB_TEST_DIR, __version__)
        from django.http import HttpResponse
        return HttpResponse(content)
    else:
        from django.http import HttpResponseServerError
        return HttpResponseServerError(error) 
Example 19
Project: browserscope   Author: elsigh   File: gaeunit.py    License: Apache License 2.0 5 votes vote down vote up
def _render_plain(package_name, test_name):
    suite, error = _create_suite(package_name, test_name, _LOCAL_DJANGO_TEST_DIR)
    if not error:
        from django.http import HttpResponse
        response = HttpResponse()
        response["Content-Type"] = "text/plain"
        runner = unittest.TextTestRunner(response)
        response.write("====================\n" \
                        "GAEUnit Test Results\n" \
                        "====================\n\n")
        _run_test_suite(runner, suite)
        return response
    else:
        from django.http import HttpResponseServerError
        return HttpResponseServerError(error) 
Example 20
Project: GTDWeb   Author: lanbing510   File: defaults.py    License: GNU General Public License v2.0 5 votes vote down vote up
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()) 
Example 21
Project: sentry-python   Author: getsentry   File: views.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def handler500(request):
    return HttpResponseServerError("Sentry error: %s" % sentry_sdk.last_event_id()) 
Example 22
Project: FIR   Author: certsocietegenerale   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def update_comment(request, comment_id):
    c = get_object_or_404(Comments, pk=comment_id)
    i = c.incident
    if request.method == 'GET':
        if not request.user.has_perm('incidents.view_incidents', obj=i):
            ret = {'status': 'error', 'errors': ['Permission denied', ]}
            return HttpResponseServerError(dumps(ret), content_type="application/json")
        serialized = serializers.serialize('json', [c, ])
        return HttpResponse(dumps(serialized), content_type="application/json")
    else:
        comment_form = CommentForm(request.POST, instance=c)
        if not request.user.has_perm('incidents.handle_incidents', obj=i):
            comment_form.fields['action'].queryset = Label.objects.filter(group__name='action').exclude(
                name__in=['Closed', 'Opened', 'Blocked'])

        if comment_form.is_valid():

            c = comment_form.save()

            log("Comment edited: %s" % (comment_form.cleaned_data['comment'][:20] + "..."), request.user,
                incident=c.incident)

            if c.action.name in ['Closed', 'Opened', 'Blocked']:
                if c.action.name[0] != c.incident.status:
                    previous_status = c.incident.status
                    c.incident.status = c.action.name[0]
                    c.incident.save()
                    model_status_changed.send(sender=Incident, instance=c.incident, previous_status=previous_status)

            i.refresh_artifacts(c.comment)

            return render(request, 'events/_comment.html', {'comment': c, 'event': i})
        else:
            ret = {'status': 'error', 'errors': comment_form.errors}
            return HttpResponseServerError(dumps(ret), content_type="application/json")


# events ==================================================================== 
Example 23
Project: FIR   Author: certsocietegenerale   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def comment(request, incident_id, authorization_target=None):
    if authorization_target is None:
        i = get_object_or_404(
            Incident.authorization.for_user(request.user, comment_permissions),
            pk=incident_id)
    else:
        i = authorization_target

    if request.method == "POST":
        comment_form = CommentForm(request.POST)
        if not request.user.has_perm('incidents.handle_incidents'):
            comment_form.fields['action'].queryset = Label.objects.filter(group__name='action').exclude(
                name__in=['Closed', 'Opened', 'Blocked'])
        if comment_form.is_valid():
            com = comment_form.save(commit=False)
            com.incident = i
            com.opened_by = request.user
            com.save()
            log("Comment created: %s" % (com.comment[:20] + "..."), request.user, incident=com.incident)
            i.refresh_artifacts(com.comment)

            if com.action.name in ['Closed', 'Opened', 'Blocked'] and com.incident.status != com.action.name[0]:
                previous_status = com.incident.status
                com.incident.status = com.action.name[0]
                com.incident.save()
                model_status_changed.send(sender=Incident, instance=com.incident, previous_status=previous_status)

            return render(request, 'events/_comment.html', {'event': i, 'comment': com})
        else:
            ret = {'status': 'error', 'errors': comment_form.errors}
            return HttpResponseServerError(dumps(ret), content_type="application/json")

    return redirect('incidents:details', incident_id=incident_id)


# User ========================================================================== 
Example 24
Project: FIR   Author: certsocietegenerale   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def user_change_password(request):
    if not settings.USER_SELF_SERVICE.get('CHANGE_PASSWORD', True):
        messages.error(request, "Error: Password change administratively disabled.")
        return HttpResponseServerError(dumps({'status': 'error', 'errors': ['password change disabled.',]}),
                                       content_type="application/json")
    if request.method == "POST":
        form = PasswordChangeForm(user=request.user, data=request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, "Success! Password updated.")
            return HttpResponse(dumps({'status': 'success'}), content_type="application/json")

    ret = {'status': 'error', 'errors': form.errors}
    messages.error(request, form.errors)
    return HttpResponseServerError(dumps(ret), content_type="application/json") 
Example 25
Project: peering-manager   Author: respawner   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def ServerError(request, template_name=ERROR_500_TEMPLATE_NAME):
    """
    Custom 500 handler to provide details when rendering 500.html.
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return HttpResponseServerError(
            "<h1>Server Error (500)</h1>", content_type="text/html"
        )
    type_, error, _ = sys.exc_info()

    return HttpResponseServerError(
        template.render({"exception": str(type_), "error": error})
    ) 
Example 26
Project: yata   Author: Kivou-2000607   File: handy.py    License: GNU General Public License v3.0 5 votes vote down vote up
def returnError(type=500, exc=None, msg=None, home=True, session=None):
    import traceback
    from django.utils import timezone
    from django.http import HttpResponseServerError
    from django.http import HttpResponseForbidden
    from django.http import HttpResponseNotFound
    from django.template.loader import render_to_string
    from player.models import Player

    if type == 403:
        msg = "Permission Denied" if msg is None else msg
        return HttpResponseForbidden(render_to_string('403.html', {'exception': msg, 'home': home}))
    if type == 404:
        msg = "Not Found" if msg is None else msg
        return HttpResponseNotFound(render_to_string('404.html', {'exception': msg, 'home': home}))
    else:
        message = traceback.format_exc().strip()
        print("[{:%d/%b/%Y %H:%M:%S}] ERROR 500 \n{}".format(timezone.now(), message))
        if session is not None and session.get("player", False):
            player = getPlayer(session["player"].get("tId"))
        else:
            player = Player.objects.filter(tId=-1).first()
        defaults = {"timestamp": tsnow()}
        try:
            player.error_set.update_or_create(short_error=exc, long_error=message, defaults=defaults)
        except BaseException as e:
            print("Meta error", e)
        return HttpResponseServerError(render_to_string('500.html', {'exception': exc, 'home': home})) 
Example 27
Project: pyas2   Author: abhishek-ram   File: views.py    License: GNU General Public License v2.0 5 votes vote down vote up
def server_error(request, template_name='500.html'):
    """ the 500 error handler.
        Templates: `500.html`
        Context: None
        str().decode(): bytes->unicode
    """
    exc_info = traceback.format_exc(None).decode('utf-8', 'ignore')
    pyas2init.logger.error(_(u'Ran into server error: "%(error)s"'), {'error': str(exc_info)})
    temp = template.loader.get_template(template_name)   # You need to create a 500.html template.
    return HttpResponseServerError(temp.render(template.Context({'exc_info': exc_info}))) 
Example 28
Project: pyas2   Author: abhishek-ram   File: views.py    License: GNU General Public License v2.0 5 votes vote down vote up
def client_error(request, template_name='400.html'):
    """ the 400 error handler.
        Templates: `400.html`
        Context: None
        str().decode(): bytes->unicode
    """
    exc_info = traceback.format_exc(None).decode('utf-8', 'ignore')
    pyas2init.logger.error(_(u'Ran into client error: "%(error)s"'), {'error': str(exc_info)})
    temp = template.loader.get_template(template_name)  # You need to create a 500.html template.
    return HttpResponseServerError(temp.render(template.Context({'exc_info': exc_info}))) 
Example 29
Project: django-webmention   Author: easy-as-python   File: test_views.py    License: MIT License 5 votes vote down vote up
def test_receive_when_general_exception_occurs(
    mock_url_resolves, mock_fetch_and_validate_source, test_source, test_target
):
    request = Mock()
    request.method = "POST"
    request.POST = {"source": test_source, "target": test_target}

    mock_url_resolves.return_value = True
    mock_fetch_and_validate_source.side_effect = Exception
    response = receive(request)

    mock_fetch_and_validate_source.assert_called_once_with(test_source, test_target)
    mock_url_resolves.assert_called_once_with(test_target)
    assert isinstance(response, HttpResponseServerError) 
Example 30
Project: oh-my-rss   Author: richshaw2015   File: views_api.py    License: MIT License 5 votes vote down vote up
def leave_a_message(request):
    """
    添加留言
    """
    uid = request.POST.get('uid', '').strip()[:100]

    content = request.POST.get('content', '').strip()[:500]
    nickname = request.POST.get('nickname', '').strip()[:20]
    contact = request.POST.get('contact', '').strip()[:50]

    user = get_login_user(request)

    if content:
        try:
            msg = Message(uid=uid, content=content, nickname=nickname, contact=contact, user=user)
            msg.save()

            logger.warning(f"有新的留言:`{content}")

            return get_all_issues(request)
        except:
            logger.error(f"留言增加失败:`{uid}`{content}`{nickname}`{contact}")
            return HttpResponseServerError('Inter error')

    logger.warning(f"参数错误:`{content}")
    return HttpResponseNotFound("Param error")