python类HttpResponseServerError()的实例源码

views.py 文件源码 项目:dj-paypal 作者: HearthSim 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def post(self, request):
        if "HTTP_PAYPAL_TRANSMISSION_ID" not in request.META:
            # Do not even attempt to process/store the event if there is
            # no paypal transmission id so we avoid overfilling the db.
            return HttpResponseBadRequest()

        trigger = WebhookEventTrigger.from_request(request)

        if trigger.exception:
            # An exception happened, return 500
            return HttpResponseServerError()

        if not trigger.valid:
            # Webhook Event did not validate, return 400
            return HttpResponseBadRequest()

        return HttpResponse(str(trigger.id))
views.py 文件源码 项目:challenge-legi 作者: jshacks 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def search(request):
    q = request.GET.get('q')
    if not q:
        return HttpResponseBadRequest("GET['q'] not set!")
    q = q.strip()

    try:
        document_ids = search_ids(q)
    except SearchError as e:
        return HttpResponseServerError(str(e))
    documents = [get_document(id).parsed for id in document_ids]

    data = {
        'status': 'ok',
        'query': q,
        'document_ids': document_ids,
        'documents': documents,
        'results': len(document_ids),
    }
    r = JsonResponse(data)
    r["Access-Control-Allow-Origin"] = '*'
    return r
views.py 文件源码 项目:tecken 作者: mozilla-services 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def task_tester(request):
    if request.method == 'POST':
        cache.set('marco', 'ping', 100)
        sample_task.delay('marco', 'polo', 10)
        return http.HttpResponse(
            'Now make a GET request to this URL\n',
            status=201,
        )
    else:
        if not cache.get('marco'):
            return http.HttpResponseBadRequest(
                'Make a POST request to this URL first\n'
            )
        for i in range(3):
            value = cache.get('marco')
            if value == 'polo':
                return http.HttpResponse('It works!\n')
            time.sleep(1)

        return http.HttpResponseServerError(
            'Tried 4 times (4 seconds) and no luck :(\n'
        )
views.py 文件源码 项目:valhalla 作者: LCOGT 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get(self, request):
        try:
            last_query_time = parse(request.query_params.get('last_query_time'))
        except (TypeError, ValueError):
            last_query_time = cache.get('isDirty_query_time', (timezone.now() - timedelta(days=7)))

        url = settings.POND_URL + '/pond/pond/blocks/new/?since={}&using=default'.format(last_query_time.strftime('%Y-%m-%dT%H:%M:%S'))
        now = timezone.now()
        try:
            response = requests.get(url)
            response.raise_for_status()
        except Exception as e:
            return HttpResponseServerError({'error': repr(e)})

        pond_blocks = response.json()
        is_dirty = update_request_states_from_pond_blocks(pond_blocks)
        cache.set('isDirty_query_time', now, None)

        # also factor in if a change in requests (added, updated, cancelled) has occurred since we last checked
        last_update_time = max(Request.objects.latest('modified').modified,
                               UserRequest.objects.latest('modified').modified)
        is_dirty |= last_update_time >= last_query_time

        return Response({'isDirty': is_dirty})
views.py 文件源码 项目:OAuth2PythonSampleApp 作者: IntuitDeveloper 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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'])
middleware.py 文件源码 项目:service-notifications 作者: rehive 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def readiness(self, request):
        # Connect to each database and do a generic standard SQL query
        # that doesn't write any data and doesn't depend on any tables
        # being present.
        try:
            from django.db import connections
            for name in connections:
                cursor = connections[name].cursor()
                cursor.execute("SELECT 1;")
                row = cursor.fetchone()
                if row is None:
                    return HttpResponseServerError("db: invalid response")

        except Exception as e:
            logger.exception(e)
            return HttpResponseServerError("db: cannot connect to database.")

        return HttpResponse("OK")
views.py 文件源码 项目:no-design-slack-clone 作者: metsavaht 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def server_error(request, template_name='500.html'):
    if request.is_ajax() or request.META.get('HTTP_ACCEPT', 'text/plain') == 'application/json':
        return JsonResponse({
            'sentry': sentry_id_from_request(request),
            'error': {
                'title': _('Something went wrong'),
            }
        }, status=500)

    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html')

    message = _('Something went wrong on our side... \n Please hold on while we fix it.').replace('\n', '<br>')
    return HttpResponseServerError(template.render({
        'sentry': sentry_id_from_request(request),
        'error': {
            'title': _('Something went wrong'),
            'message': message,
            'sentry': _('Fault code: #'),
        }
    }))
views.py 文件源码 项目:django-project-template 作者: thorgate 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def server_error(request, template_name='500.html'):
    if request.is_ajax() or request.META.get('HTTP_ACCEPT', 'text/plain') == 'application/json':
        return JsonResponse({
            'sentry': sentry_id_from_request(request),
            'error': {
                'title': _('Something went wrong'),
            }
        }, status=500)

    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html')

    message = _('Something went wrong on our side... \n Please hold on while we fix it.').replace('\n', '<br>')
    return HttpResponseServerError(template.render({
        'sentry': sentry_id_from_request(request),
        'error': {
            'title': _('Something went wrong'),
            'message': message,
            'sentry': _('Fault code: #'),
        }
    }))
views.py 文件源码 项目:telemetry-analysis-service 作者: mozilla 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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 %}.
views.py 文件源码 项目:protolegi 作者: gabriel-v 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def search(request):
    q = request.GET.get('q')
    if not q:
        return HttpResponseBadRequest("GET['q'] not set!")
    q = q.strip()

    try:
        document_ids = search_ids(q)
    except SearchError as e:
        return HttpResponseServerError(str(e))
    documents = [get_document(id).parsed for id in document_ids]

    data = {
        'status': 'ok',
        'query': q,
        'document_ids': document_ids,
        'documents': documents,
        'results': len(document_ids),
    }
    r = JsonResponse(data)
    r["Access-Control-Allow-Origin"] = '*'
    return r
views.py 文件源码 项目:djangocms-onepage-example 作者: thorgate 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def server_error(request, template_name='500.html'):
    if request.is_ajax() or request.META.get('HTTP_ACCEPT', 'text/plain') == 'application/json':
        return JsonResponse({
            'sentry': sentry_id_from_request(request),
            'error': {
                'title': _('Something went wrong'),
            }
        }, status=500)

    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html')

    return HttpResponseServerError(template.render({
        'sentry': sentry_id_from_request(request),
        'error': {
            'title': _('Something went wrong'),
            'message': ('%s' %
                        _('Something went wrong on our side... \n Please hold on while we fix it.')).replace('\n',
                                                                                                             '<br>'),
            'sentry': _('Fault code: #'),
        }
    }))
views.py 文件源码 项目:PythonGuru 作者: aronekob34 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def edit_profile(request):

    try:

        if request.method == 'GET':
            account_form = forms.EditAccountForm(instance=request.user.account)

            if request.user.account.account_type == 'Individual':
                del account_form.fields['business_name']

        elif request.method == 'POST':
            account_form = forms.EditAccountForm(request.POST, instance=request.user.account)

            if account_form.is_valid():
                account_form.save()
                return HttpResponseRedirect(reverse('account:view-profile'))

    except ObjectDoesNotExist:
        logger.error('No account profile found for user {}'.format(request.user))
        return HttpResponseServerError()

    return render(request, 'account/edit_profile.html', {'account_form': account_form})
views.py 文件源码 项目:pyadselfservice 作者: kanayak123 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def ADValidate(request):
     getd = unquote(request.GET.get('token'))
     tokenverify = signer.unsign(getd, max_age=int(settings.PYADSELFSERVICE_STOUT))
     if request.method == 'POST':
        form = renderform(request.POST)
        if form.is_valid():
           output = do_validate(form.cleaned_data['username'], form.cleaned_data['attr3'], form.cleaned_data['attr4'], form.cleaned_data['attr5'])
           if output == 'YGFRafd827343wdhgFDHGFDSFGHVFSNC':
             cipher_text = encrypt_val(form.cleaned_data['username'])
             data = signer.sign(cipher_text)
             return HttpResponseRedirect('/otp?key=' + quote(data))
           else:
#             value = "You have entered invalid details. Please go back and try again %s" %str(output)
             value = str(output)
             return HttpResponseServerError(template.render(Context({'exception_value': value,})))

     return render(request, 'index.html', {'form': renderform()})
views.py 文件源码 项目:pyadselfservice 作者: kanayak123 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def resetpass(request):
   getd = unquote(request.GET.get('key'))
   crypted_data = signer.unsign(getd, max_age=int(settings.PYADSELFSERVICE_STOUT))
   prim_key = {'username' : getd}
   if request.method == 'POST':
      form = passreset(request.POST)
      if form.is_valid():
         base32 = calc_base32(crypted_data)
         newpassword = form.cleaned_data['newpassword']
         confirmpassword = form.cleaned_data['confirmpassword']
         if newpassword and newpassword != confirmpassword:
            value = "Your New Password and Confirm Password did not match. Please go back and try again."
            return HttpResponseServerError(template.render(Context({'exception_value': value,})))
         else:
            output = do_reset(crypted_data, form.cleaned_data['confirmpassword'])
            if 'success' in output:
               value = str(output)
               return HttpResponseServerError(loader.get_template('success.html').render(Context({'exception_value': value,})))
            else:
               value = str(output)
               return HttpResponseServerError(template.render(Context({'exception_value': value,})))
      else:
         value = "Your new password does not comply with password policy. Please go back and try again."
         return HttpResponseServerError(template.render(Context({'exception_value': value,})))
   return render(request, 'resetpass.html', {'form': passreset(initial=prim_key)})
error_500.py 文件源码 项目:Sentry 作者: NetEaseGame 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def dispatch(self, request):
        """
        500 error handler.

        Templates: `500.html`
        Context: None
        """
        context = {
            'request': request,
        }

        embed_config = self.get_embed_config(request)
        if embed_config:
            context['embed_config'] = mark_safe(json.dumps(embed_config))

        t = loader.get_template('sentry/500.html')
        return HttpResponseServerError(t.render(Context(context)))
views.py 文件源码 项目:ISeeNN 作者: sunshaoyan 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def get_image(request, id):
    try:
        db_image = DBImage.objects.get(id=id)
        try:
            server = ImageServer.objects.get(id=db_image.server)
            if server.server_name != settings.SERVER_NAME:
                return HttpResponseBadRequest("Image Not On This Server")
        except ImageServer.DoesNotExist:
            return HttpResponseServerError("Image Server Does Not Exist!")
        image_data = open(db_image.path, 'rb').read()
        mime_type = db_image.mime_type
        return HttpResponse(image_data, content_type=mime_type)
    except DBImage.DoesNotExist:
        raise Http404("Image Not Found")
    except IOError:
        return HttpResponseGone("Image Moved")
views.py 文件源码 项目:ISeeNN 作者: sunshaoyan 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get_image(request, id):
    try:
        db_image = DBImage.objects.get(id=id)
        mime_type = db_image.mime_type
        try:
            server = ImageServer.objects.get(id=db_image.server)
            ip = server.server_ip
            port = request.META['SERVER_PORT']
            url_ext = reverse('image_server:get_image', args=(str(id) ,))
            remote_url = 'http://' + ip + ':' + str(port) + url_ext
            image_data = urllib.request.urlopen(remote_url).read()
            return HttpResponse(image_data, content_type=mime_type)
        except ImageServer.DoesNotExist:
            return HttpResponseServerError("Image Server Does Not Exist!")
    except DBImage.DoesNotExist:
        raise Http404("Image Not Found")
    except:
        return HttpResponseGone("Image Moved")
views.py 文件源码 项目:ISeeNN 作者: sunshaoyan 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get_thumbnail(request, id):
    try:
        db_image = DBImage.objects.get(id=id)
        mime_type = db_image.mime_type
        try:
            server = ImageServer.objects.get(id=db_image.server)
            ip = server.server_ip
            port = request.META['SERVER_PORT']
            url_ext = reverse('image_server:get_thumbnail', args=(str(id) ,))
            remote_url = 'http://' + ip + ':' + str(port) + url_ext
            print(remote_url)
            image_data = urllib.request.urlopen(remote_url).read()
            return HttpResponse(image_data, content_type=mime_type)
        except ImageServer.DoesNotExist:
            return HttpResponseServerError("Image Server Does Not Exist!")
    except DBImage.DoesNotExist:
        raise Http404("Image Not Found")
    except Exception as e:
        print(e)
        return HttpResponseGone("Image Moved")
views.py 文件源码 项目:OAuth2PythonPaymentSampleApp 作者: IntuitDeveloper 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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 payment scope was passed!')

    refresh_token = request.session['refreshToken']
    create_charge_response, status_code = createCharge(access_token)
    print(create_charge_response)
    print(status_code)

    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)
        create_charge_response, status_code = createCharge(bearer.accessToken)
        if status_code >= 400:
            return HttpResponseServerError()
    return HttpResponse('Charge create response: '+str(create_charge_response))
views.py 文件源码 项目:taiga-contrib-saml-auth 作者: jgiannuzzi 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def metadata(request):
    saml_settings = OneLogin_Saml2_Settings(get_saml_settings(), sp_validation_only=True)
    metadata = saml_settings.get_sp_metadata()
    errors = saml_settings.validate_metadata(metadata)

    if errors:
        return HttpResponseServerError(content=', '.join(errors))

    return HttpResponse(content=metadata, content_type='text/xml')
views.py 文件源码 项目:TeleGiphy 作者: JessicaNgo 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def custom_error_page(request):
    return HttpResponseServerError(
        render_to_string('500.html', request=request))
views.py 文件源码 项目:webtzite 作者: materialsproject 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def dashboard(request):
    from .models import RegisteredUser
    u = RegisteredUser.objects.get(username=request.user.username)
    if request.method == 'POST' or not u.api_key:
        api_key = request.POST.get('apikey')
        if api_key == 'None': api_key = None
        try:
            u.api_key = api_key if api_key else generate_key(16)
            u.save()
        except Exception, e:
            return HttpResponseServerError(str(e))
    ctx = RequestContext(request)
    return render_to_response("dashboard.html", locals(), ctx)
test_django.py 文件源码 项目:Tinychat-Bot--Discontinued 作者: Tinychat 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_really_bad_decode(self):
        self.old_method = remoting.decode
        remoting.decode = lambda *args, **kwargs: self._raiseException(
            Exception, *args, **kwargs
        )

        http_request = make_http_request('POST', '')

        gw = django.DjangoGateway()

        try:
            http_response = gw(http_request)
        except:
            remoting.decode = self.old_method

            raise

        remoting.decode = self.old_method

        self.assertTrue(
            isinstance(http_response, http.HttpResponseServerError)
        )
        self.assertEqual(http_response.status_code, 500)
        self.assertEqual(
            http_response.content,
            '500 Internal Server Error\n\nAn unexpected error occurred.'
        )
views.py 文件源码 项目:challenge-legi 作者: jshacks 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def submit(request):
    """Endpoint for submitting new crawls.
    Expects POST['data'] to be populated with data for a single document group."""

    # TODO authentication? Secret keys?
    # TODO stop processing the documents when submitted; use processing queues

    input_raw = request.POST.get('data')
    if not input_raw:
        return HttpResponseBadRequest('POST["data"] is not set!')
    try:
        input = json.loads(input_raw)
    except json.JSONDecodeError:
        return HttpResponseBadRequest('POST["data"] is not valid json')

    input_hash = hash.dict_sha1(input)

    submitted, created = models.SubmittedData.objects.update_or_create(
        sha1=input_hash,
        data=input
    )

    try:
        doc, new = process(submitted)
        index_data(doc)
    except ProcessingInputError as e:
        print(e)
        return HttpResponseServerError('error: ' + str(e))

    response = {
        'status': 'ok',
        'new': new,
    }

    return JsonResponse(response)
defaults.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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())
errorpages.py 文件源码 项目:zing 作者: evernote 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def handle_exception(request, exception, template_name):
    # XXX: remove this? exceptions are already displayed in debug mode
    tb = traceback.format_exc()
    print >> sys.stderr, tb

    if settings.DEBUG:
        return None

    try:
        log_exception(request, exception, tb)

        msg = force_unicode(exception)

        if request.is_ajax():
            return JsonResponseServerError({'msg': msg})

        ctx = {
            'exception': msg,
        }
        if hasattr(exception, 'filename'):
            msg_args = {
                'filename': exception.filename,
                'errormsg': exception.strerror,
            }
            msg = _('Error accessing %(filename)s, Filesystem '
                    'sent error: %(errormsg)s', msg_args)
            ctx['fserror'] = msg

        return HttpResponseServerError(
            render_to_string(template_name, context=ctx, request=request)
        )
    except:
        # Let's not confuse things by throwing an exception here
        pass
views.py 文件源码 项目:OAuth2PythonSampleApp 作者: IntuitDeveloper 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def connected(request):
    access_token = request.session.get('accessToken',None)
    if access_token is None:
        return HttpResponse('Your Bearer token has expired, please initiate Sign In With Intuit flow again')

    refresh_token = request.session.get('refreshToken',None)
    realmId = request.session['realmId']
    if realmId is None:
        user_profile_response, status_code = getUserProfile(access_token)

        if status_code >= 400:
        # if call to User Profile Service doesn't succeed then get a new bearer token from refresh token and try again
            bearer = getBearerTokenFromRefreshToken(refresh_token)
            user_profile_response, status_code = getUserProfile(bearer.accessToken)
            updateSession(request,bearer.accessToken,bearer.refreshToken,request.session.get('realmId',None),name=user_profile_response.get('givenName',None))

            if status_code >= 400:
                return HttpResponseServerError()
        c = {
            'first_name': user_profile_response.get('givenName',' '),
        }
    else:
        if request.session.get('name') is None:
            name = ''
        else:
            name = request.session.get('name')
        c = {
        'first_name': name,
        }

    return render(request, 'connected.html', context=c)
views.py 文件源码 项目:PonyConf 作者: PonyConf 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)
views.py 文件源码 项目:PonyConf 作者: PonyConf 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)
views.py 文件源码 项目:PonyConf 作者: PonyConf 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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)


问题


面经


文章

微信
公众号

扫码关注公众号