示例#1
0
    def forgot_password(self, request, **kwargs):

        self.method_check(request, allowed=['post'])
        #self.is_authenticated(request)
        #self.throttle_check(request)

        data = self.deserialize(request, request.body)

        UserModel = get_user_model()

        try:
            user = UserModel.objects.get(email=data['email'])
        except User.DoesNotExist:
            data = {
                "error":
                sanitize({'email': 'อีเมลที่คุณกรอก ยังไม่มีอยู๋ในระบบ'})
            }
            return self.error_response(request,
                                       data,
                                       response_class=HttpForbidden)

        user.send_email_confirm()

        bundle = self.build_bundle(obj=user, request=request)
        bundle = self.full_dehydrate(bundle)

        #self.log_throttled_access(request)
        return self.create_response(request, bundle)
示例#2
0
        def wrapper(request, *args, **kwargs):
            try:
                callback = getattr(self, view)
                response = callback(request, *args, **kwargs)

                varies = getattr(self._meta.cache, "varies", [])

                if varies:
                    patch_vary_headers(response, varies)

                if self._meta.cache.cacheable(request, response):
                    if self._meta.cache.cache_control():
                        patch_cache_control(response, **self._meta.cache.cache_control())

                if request.is_ajax() and not response.has_header("Cache-Control"):
                    patch_cache_control(response, no_cache=True)
                return response

            except IntegrityError as e:
                return FailedResult(msg=str(e))
            # =========except custome exception=========
            except DataFormatError as e:
                return FailedResult(msg=e.msg)
            # ==========================================
            except (BadRequest, fields.ApiFieldError) as e:
                # data = {"error": sanitize(e.args[0]) if getattr(e, 'args') else ''}
                # =========except custome exception=========
                return FailedResult(msg=sanitize(e.args[0]) if getattr(e, 'args') else '')
                # return self.error_response(request, data, response_class=http.HttpBadRequest)
                # ==========================================
            except ValidationError as e:
                # data = {"error": sanitize(e.messages)}
                # =========except custome exception=========
                return FailedResult(msg=sanitize(e.messages))
                # return self.error_response(request, data, response_class=http.HttpBadRequest)
                # ==========================================
            except Exception as e:
                if hasattr(e, 'response') and isinstance(e.response, HttpResponse):
                    # =========except custome exception=========
                    return e.response
                # ==========================================

                if settings.DEBUG and getattr(settings, 'TASTYPIE_FULL_DEBUG', False):
                    raise
                if request.META.get('SERVER_NAME') == 'testserver':
                    raise
                return self._handle_500(request, e)
示例#3
0
 def _handle_500(self, request, exception, *args, **kwargs):
     log_traceback(log=log)
     if isinstance(exception, (NotFound, ObjectDoesNotExist, Http404, UnsupportedFormat)):
         return super(ResourceMixin, self)._handle_500(request, exception, *args, **kwargs)
     else:
         the_trace = '\n'.join(traceback.format_exception(*(sys.exc_info())))
         data = {
             "error_message": sanitize(six.text_type(exception)),
             "traceback": the_trace,
         }
         return self.error_response(request, data, response_class=http.HttpApplicationError)
示例#4
0
    def _handle_500(self, request, exception):
        import traceback
        import sys
        the_trace = '\n'.join(traceback.format_exception(*(sys.exc_info())))
        if settings.DEBUG:
            response_class = TracebackApplicationJsonError
        else:
            response_class = ApplicationJsonError
        response_code = 500

        NOT_FOUND_EXCEPTIONS = (NotFound, ObjectDoesNotExist, Http404)

        if isinstance(exception, NOT_FOUND_EXCEPTIONS):
            if settings.DEBUG:
                response_class = TracebackNotFoundJsonError
            else:
                response_class = NotFoundJsonError
            response_code = 404

        if settings.DEBUG:
            data = {
                "developer_message": sanitize(six.text_type(exception)),
                "traceback": the_trace,
            }
            return self.error_response(request,
                                       None,
                                       response_class=response_class,
                                       **data)

        # When DEBUG is False, send an error message to the admins (unless it's
        # a 404, in which case we check the setting).
        send_broken_links = getattr(settings, 'SEND_BROKEN_LINK_EMAILS', False)

        if not response_code == 404 or send_broken_links:
            log = logging.getLogger('django.request.tastypie')
            log.error('Internal Server Error: %s' % request.path,
                      exc_info=True,
                      extra={
                          'status_code': response_code,
                          'request': request
                      })

        # Send the signal so other apps are aware of the exception.
        got_request_exception.send(self.__class__, request=request)

        return self.error_response(request,
                                   None,
                                   response_class=response_class)
示例#5
0
    def _handle_500(self, request, exception):
        ''' Override Tastypie for serialization'''
        import traceback
        import sys
        the_trace = '\n'.join(traceback.format_exception(*(sys.exc_info())))
        response_class = HttpApplicationError
        response_code = 500

        NOT_FOUND_EXCEPTIONS = (NotFound, ObjectDoesNotExist, Http404)

        if isinstance(exception, NOT_FOUND_EXCEPTIONS):
            response_class = HttpResponseNotFound
            response_code = 404

        if settings.DEBUG:
            data = {
                "error_message": sanitize(six.text_type(exception)),
                "traceback": the_trace,
            }
            return self.build_error_response(request, data, response_class=response_class)

        # When DEBUG is False, send an error message to the admins (unless it's
        # a 404, in which case we check the setting).
        send_broken_links = getattr(settings, 'SEND_BROKEN_LINK_EMAILS', False)

        if not response_code == 404 or send_broken_links:
            log = logging.getLogger('django.request.tastypie')
            log.error('Internal Server Error: %s' % request.path, exc_info=True,
                      extra={'status_code': response_code, 'request': request})

        # Send the signal so other apps are aware of the exception.
        got_request_exception.send(self.__class__, request=request)

        # Prep the data going out.
        data = {
            "error_message": getattr(
                settings, 
                'TASTYPIE_CANNED_ERROR', 
                "Sorry, this request could not be processed. Please try again later."),
        }
        return self.build_error_response(request, data, response_class=response_class)
示例#6
0
    def change_password(self, request, **kwargs):
        self.method_check(request, allowed=['post'])
        self.is_authenticated(request)
        self.throttle_check(request)

        if not request.user:
            return self.create_response(
                request,
                {
                    'error': 'You are anonymous user',
                },
                HttpForbidden,
            )

        data = self.deserialize(request, request.body)
        if data.get('token') and default_token_generator.check_token(
                request.user, data['token']):
            pass
        elif not request.user.check_password(data['old_password']):
            data = {
                "error":
                sanitize({'old_password': '******'})
            }
            return self.error_response(request,
                                       data,
                                       response_class=HttpForbidden)

        request.user.set_password(data['new_password'])
        request.user.save()

        bundle = self.build_bundle(obj=request.user, request=request)
        bundle = self.full_dehydrate(bundle)

        self.log_throttled_access(request)

        return self.create_response(request, bundle)
示例#7
0
        def wrapper(request, *args, **kwargs):
            DEBUG_WRAPPER = True
            try:
                callback = getattr(self, view)
                if DEBUG_WRAPPER:
                    msg = ()
                    if kwargs:
                        msg = [ (key,kwargs[key]) for key in kwargs.keys() 
                            if len(str(kwargs[key]))<100]
                    logger.info('callback: %r, %r', view, msg)
                    logger.info('request: %r', request)
                else:
                    logger.info('callback: %r, %r', callback, view)
                
                self.is_authenticated(request)
        
                response = callback(request, *args, **kwargs)
                # Our response can vary based on a number of factors, use
                # the cache class to determine what we should ``Vary`` on so
                # caches won't return the wrong (cached) version.
                varies = getattr(self._meta.cache, "varies", [])

                if varies:
                    patch_vary_headers(response, varies)

                if self._meta.cache.cacheable(request, response):
                    if self._meta.cache.cache_control():
                        # If the request is cacheable and we have a
                        # ``Cache-Control`` available then patch the header.
                        patch_cache_control(response, **self._meta.cache.cache_control())

                if request.is_ajax() and not response.has_header("Cache-Control"):
                    # IE excessively caches XMLHttpRequests, so we're disabling
                    # the browser cache here.
                    # See http://www.enhanceie.com/ie/bugs.asp for details.
                    patch_cache_control(response, no_cache=True)

                return response
            except BadRequest as e:
                # The message is the first/only arg
                logger.exception('Bad request exception: %r', e)
                data = {"error": sanitize(e.args[0]) if getattr(e, 'args') else ''}
                return self.build_error_response(request, data, **kwargs)
            except InformationError as e:
                logger.exception('Information error: %r', e)
                response = self.build_error_response(
                    request, { 'Messages': e.errors }, **kwargs)
                if 'xls' in response['Content-Type']:
                    response['Content-Disposition'] = \
                        'attachment; filename=%s.xlsx' % 'errors'
                    downloadID = request.GET.get('downloadID', None)
                    if downloadID:
                        logger.info('set cookie "downloadID" %r', downloadID )
                        response.set_cookie('downloadID', downloadID)
                    else:
                        logger.debug('no downloadID: %s' % request.GET )
                return response
            
            except ValidationError as e:
                logger.exception('Validation error: %r', e)
                response = self.build_error_response(
                    request, { 'errors': e.errors }, **kwargs)
                if 'xls' in response['Content-Type']:
                    response['Content-Disposition'] = \
                        'attachment; filename=%s.xlsx' % 'errors'
                    downloadID = request.GET.get('downloadID', None)
                    if downloadID:
                        logger.info('set cookie "downloadID" %r', downloadID )
                        response.set_cookie('downloadID', downloadID)
                    else:
                        logger.debug('no downloadID: %s' % request.GET )
                return response
            except django.core.exceptions.ValidationError as e:
                logger.exception('Django validation error: %s', e)
                response = self.build_error_response(
                    request, { 'errors': e.message_dict }, **kwargs)
                if 'xls' in response['Content-Type']:
                    response['Content-Disposition'] = \
                        'attachment; filename=%s.xlsx' % 'errors'
                    downloadID = request.GET.get('downloadID', None)
                    if downloadID:
                        logger.info('set cookie "downloadID" %r', downloadID )
                        response.set_cookie('downloadID', downloadID)
                    else:
                        logger.debug('no downloadID: %s' % request.GET )
                return response
                
            except Exception as e:
                logger.exception('Unhandled exception: %r', e)
                if hasattr(e, 'response'):
                    # A specific response was specified
                    return e.response

                logger.exception('Unhandled exception: %r', e)

                # A real, non-expected exception.
                # Handle the case where the full traceback is more helpful
                # than the serialized error.
                if settings.DEBUG and getattr(settings, 'TASTYPIE_FULL_DEBUG', False):
                    logger.warn('raise tastypie full exception for %r', e)
                    raise

                # Rather than re-raising, we're going to things similar to
                # what Django does. The difference is returning a serialized
                # error message.
                logger.exception('handle 500 error %r...', str(e))
                return self._handle_500(request, e)
示例#8
0
文件: api_custom.py 项目: zjwang6/TS
        def wrapper(request, *args, **kwargs):
            try:
                callback = getattr(self, view)
                response = callback(request, *args, **kwargs)

                # Our response can vary based on a number of factors, use
                # the cache class to determine what we should ``Vary`` on so
                # caches won't return the wrong (cached) version.
                varies = getattr(self._meta.cache, "varies", [])

                if varies:
                    patch_vary_headers(response, varies)

                if self._meta.cache.cacheable(request, response):
                    if self._meta.cache.cache_control():
                        # If the request is cacheable and we have a
                        # ``Cache-Control`` available then patch the header.
                        patch_cache_control(
                            response, **self._meta.cache.cache_control()
                        )

                if request.is_ajax() and not response.has_header("Cache-Control"):
                    # IE excessively caches XMLHttpRequests, so we're disabling
                    # the browser cache here.
                    # See http://www.enhanceie.com/ie/bugs.asp for details.
                    patch_cache_control(response, no_cache=True)

                return response
            except SDKValidationError as e:
                data = {"error": e.errors()}
                return self.error_response(
                    request, data, response_class=http.HttpBadRequest
                )
            except (BadRequest, fields.ApiFieldError) as e:
                data = {"error": sanitize(e.args[0]) if getattr(e, "args") else ""}
                return self.error_response(
                    request, data, response_class=http.HttpBadRequest
                )
            except SDKValidationError as e:
                data = {"error": sanitize(e.messages)}
                return self.error_response(
                    request, data, response_class=http.HttpBadRequest
                )
            except Exception as e:
                if hasattr(e, "response"):
                    return e.response

                # A real, non-expected exception.
                # Handle the case where the full traceback is more helpful
                # than the serialized error.
                if settings.DEBUG and getattr(settings, "TASTYPIE_FULL_DEBUG", False):
                    raise

                # Re-raise the error to get a proper traceback when the error
                # happend during a test case
                if request.META.get("SERVER_NAME") == "testserver":
                    raise

                # Rather than re-raising, we're going to things similar to
                # what Django does. The difference is returning a serialized
                # error message.
                return self._handle_500(request, e)