示例#1
0
文件: views.py 项目: scsa3/mysite
def temp(request: WSGIRequest) -> HttpResponse:
    print(request.get_full_path())
    # return redirect(request.get_full_path)
    # import threading
    # t = threading.Thread(target=play_movie)
    # t.start()
    return render(request, 'my_av/temp.html')
示例#2
0
    def _build_messages(self, request: WSGIRequest,
                        response: Response) -> Tuple[str, str]:
        request_msg_parts = [request.method, request.get_full_path()]
        if hasattr(request, '_saved_body'):
            request_msg_parts.append(request._saved_body)
        request_msg = 'Request: ' + ' '.join(request_msg_parts)

        response_msg_parts = [str(response.status_code)]
        if response.data:
            response_msg_parts.append(str(response.data))
        response_msg = 'Response: ' + ' '.join(response_msg_parts)

        return request_msg, response_msg
示例#3
0
    def __call__(self, request: WSGIRequest) -> HttpResponseBase:
        #         if settings.DEBUG:
        #             return self.get_response(request)

        request_uri = request.build_absolute_uri(request.get_full_path())
        if '/users/' in request.path_info:
            if not request.is_secure():
                new_url = request_uri.replace('http:', 'https:')
                return redirect(new_url, permanent=False)
            return self.get_response(request)
        elif request.is_secure():
            new_url = request_uri.replace('https:', 'http:')
            return redirect(new_url, permanent=False)

        return self.get_response(request)
示例#4
0
    def session_set_pages(request: WSGIRequest):

        if not isinstance(request, WSGIRequest):
            raise TypeError("Parameter 1 invalid type")

        if not ("pages" in request.session): request.session['pages'] = []

        FULL_URL_WITH_QUERY_STRING = request.build_absolute_uri()
        FULL_URL = request.build_absolute_uri('?')
        ABSOLUTE_ROOT = request.build_absolute_uri('/')[:-1].strip("/")
        ABSOLUTE_ROOT_URL = request.build_absolute_uri('/').strip("/")
        REQUEST_PATH = request.get_full_path()

        if len(request.session['pages']) > 0 \
                and (request.session['pages'][0] == REQUEST_PATH):
            return

        request.session['pages'].append(REQUEST_PATH)
        request.session['pages'].reverse()

        # request.session['pages'] = list(set(request.session['pages']));

        pass
示例#5
0
    def process_response(self, request: WSGIRequest,
                         response: Response) -> Response:
        if type(response) == Response:
            if 200 <= response.status_code <= 399:
                level = logging.INFO
            elif 400 <= response.status_code <= 499:
                level = logging.WARN
            else:
                level = logging.ERROR

            _request_logger = request_logger
            _response_logger = response_logger
            # filter swagger-related messages in the separate loggers
            if request.get_full_path().strip('/').startswith(
                    settings.SWAGGER_ROOT_FOLDER):
                _request_logger = swagger_request_logger
            if response.data and 'swaggerVersion' in response.data:
                _response_logger = swagger_response_logger

            request_msg, response_msg = self._build_messages(request, response)
            _request_logger.log(level, request_msg)
            _response_logger.log(level, response_msg)

        return response
示例#6
0
    def __call__(self, request: WSGIRequest):
        from avishan.utils import discard_monitor, find_token, decode_token, add_token_to_response, find_and_check_user
        from avishan.exceptions import AvishanException
        from avishan.exceptions import save_traceback
        from avishan.configure import get_avishan_config

        request.avishan = AvishanRequestStorage(request)
        request.avishan.project = self.project
        """Checks for avoid-touch requests"""
        if discard_monitor(request.get_full_path()):
            print(f"NOT_MONITORED: {request.get_full_path()}")
            response = self.get_response(request)
            if 'token' in request.COOKIES.keys():
                response.set_cookie('token', request.COOKIES['token'])
            del request.avishan
            return response
        """Find token and parse it"""
        """
        Bara inke yadam nare. tooye sathe middleware vaghti error midim, chon nemidoonim api e ya template, error ro 
        zakhire mikonim mirim decorator, baad oonja k set shod in meghdar, check mikonim chon error hast, barmigarde 
        inja 
        """
        try:
            if find_token():
                decode_token()
                find_and_check_user()
        except AvishanException:
            pass
        except Exception as e:
            save_traceback()
            AvishanException(e)

        get_avishan_config().on_request(request)

        # todo 0.2.2 check for 'avishan_' in request bodies
        """Send request object to the next layer and wait for response"""
        try:
            response = self.get_response(request)
            if not request.avishan.can_touch_response:
                del request.avishan
                return response
        except AvishanException:
            pass
        except Exception as e:
            save_traceback()
            AvishanException(e)

        remove_from_crum = False
        if get_current_request() is None:
            remove_from_crum = True
            set_current_request(request)
        """messages"""
        if request.avishan.have_message():
            # todo 0.2.3: check for debug=True

            if request.avishan.is_api:
                request.avishan.response['messages'] = request.avishan.messages
            else:
                # noinspection PyTypeChecker
                self.fill_messages_framework(request)
                if request.avishan.on_error_view_class and response.status_code == 500:
                    response = request.avishan.on_error_view_class.render()
                # todo fix problem on template: not showing thrown exception message

        add_token_to_response(response)
        status_code = request.avishan.status_code
        is_api = request.avishan.is_api
        json_safe = not request.avishan.json_unsafe
        if is_api:
            response = request.avishan.response.copy()

        if request.avishan.is_tracked or request.avishan.exception is not None:
            self.save_request_track(request)

        del request.avishan
        if remove_from_crum:
            set_current_request(None)

        if is_api:
            return JsonResponse(response, status=status_code, safe=json_safe)
        """Do not change redirection status codes"""
        if response.status_code // 100 != 3:
            response.status_code = status_code
        return response
示例#7
0
    def save_request_track(request: WSGIRequest):
        from avishan.configure import get_avishan_config
        # noinspection PyTypeHints
        request.avishan: AvishanRequestStorage
        from avishan.models import RequestTrackException
        for ignore in get_avishan_config().IGNORE_TRACKING_STARTS:
            if request.get_full_path().startswith(ignore) and \
                    request.avishan.request_track_object:
                request.avishan.request_track_object.delete()
                return
        request.avishan.end_time = timezone.now()

        authentication_type_class_title = "NOT_AVAILABLE"
        authentication_type_object_id = 0
        if request.avishan.authentication_object:
            authentication_type_class_title = request.avishan.authentication_object.__class__.__name__
            authentication_type_object_id = request.avishan.authentication_object.id

        request_data = "NOT_AVAILABLE"
        request_data_size = -1
        if request.method in ['POST', 'PUT']:
            try:
                request_data = json.dumps(request.data, indent=2)
                request_data_size = sys.getsizeof(json.dumps(request.data))
            except:
                print("*DEBUG* request parse error")

        request_headers = ""
        for key, value in request.META.items():
            if key.startswith('HTTP_'):
                request_headers += f'{key[5:]}={value}\n'
        for key in request.FILES.keys():
            request_headers += f'FILE({key})\n'

        from avishan.views.class_based import AvishanView
        if request.avishan.view_class:
            view_name = request.avishan.view_class.__class__.__name__ \
                if isinstance(request.avishan.view_class, AvishanView) \
                else request.avishan.view_class.__name__
        else:
            view_name = None

        try:
            response_data = json.dumps(request.avishan.response, indent=2)
        except:
            print("*DEBUG* response parse error:", request.avishan.response)
            response_data = 'NOT_AVAILABLE'

        from avishan.models import UserUserGroup
        if request.avishan.user_user_group:
            try:
                uug = UserUserGroup.objects.get(
                    id=request.avishan.user_user_group.id)
            except UserUserGroup.DoesNotExist:
                uug = None
        else:
            uug = None
        try:
            created = request.avishan.request_track_object.update(
                view_name=view_name,
                url=request.get_full_path(),
                status_code=request.avishan.status_code,
                method=request.method,
                json_unsafe=request.avishan.json_unsafe,
                is_api=request.avishan.is_api,
                add_token=request.avishan.add_token,
                user_user_group=uug,
                request_data=request_data,
                request_data_size=request_data_size,
                request_headers=request_headers,
                response_data=response_data,
                response_data_size=sys.getsizeof(response_data),
                start_time=request.avishan.start_time,
                end_time=request.avishan.end_time,
                total_execution_milliseconds=int(
                    (request.avishan.end_time -
                     request.avishan.start_time).total_seconds() * 1000),
                view_execution_milliseconds=int(
                    (request.avishan.view_end_time -
                     request.avishan.view_start_time).total_seconds() *
                    1000) if request.avishan.view_end_time else 0,
                authentication_type_class_title=authentication_type_class_title,
                authentication_type_object_id=authentication_type_object_id)

            if request.avishan.exception is not None:
                RequestTrackException.objects.create(
                    request_track=created,
                    class_title=request.avishan.exception.__class__.__name__,
                    args=request.avishan.exception.args,
                    traceback=request.avishan.traceback)
        except Exception as e:
            print('save_request_track_error:'.upper(), e)