def _precondition_failed(request): response = HttpResponse(status=412) log_response("Precondition Failed: %s", request.path, response=response, request=request) return response
def get_response(self, request): """Return an HttpResponse object for the given HttpRequest.""" # Setup default url resolver for this thread set_urlconf(settings.ROOT_URLCONF) response = self._middleware_chain(request) response._closable_objects.append(request) # If the exception handler returns a TemplateResponse that has not # been rendered, force it to be rendered. if not getattr(response, 'is_rendered', True) and callable( getattr(response, 'render', None)): response = response.render() if response.status_code >= 400: log_response( '%s: %s', response.reason_phrase, request.path, response=response, request=request, ) return response
def get_help_tip(request): try: guid = request.GET.get('guid') except MultiValueDictKeyError: response = HttpResponseAjaxError(code=302, message='no request GET guid') log_response( '%s : no request GET guid', request.path, response=response, request=request, ) return response product = get_object_or_404(Product, guid=guid) user = request.user if not user: response = HttpResponseAjaxError(code=303, message='you are not authenticated') log_response( '%s : you are not authenticated', request.path, response=response, request=request, ) return HttpResponseAjax( help_tip=render_to_string('goods/help_tip.html', {'ob_goods': product, 'inventories': product.inventories_user(user)}) )
def response_for_exception(request, exc): '''simplified from Django 1.11 source. The difference is that we use the exception that was passed in, rather than referencing sys.exc_info(), which gives us the ResponseForException the original exception was wrapped in, which we don't want to show to users. ''' if isinstance(exc, UNHANDLED_EXCEPTIONS): '''copied from Django source, but i don't think these exceptions will actually occur.''' raise exc signals.got_request_exception.send(sender=None, request=request) exc_info = (type(exc), exc, exc.__traceback__) response = handle_uncaught_exception(request, get_resolver(get_urlconf()), exc_info) log_response( '%s: %s', response.reason_phrase, request.path, response=response, request=request, exc_info=exc, ) if settings.DEBUG: response_content = response.content.split(b'<div id="requestinfo">')[0] response_content += TECHNICAL_500_AUTORELOAD_JS response.content = response_content # Force a TemplateResponse to be rendered. if not getattr(response, 'is_rendered', True) and callable( getattr(response, 'render', None) ): response = response.render() return response
def cart_reduce_quantity(request): try: guid = request.GET.get('guid') except MultiValueDictKeyError: response = HttpResponseAjaxError(code=302, message='no request GET guid') log_response( '%s : no request GET guid', request.path, response=response, request=request, ) return response cart = Cart(request) product = get_object_or_404(Product, guid=guid) cart.add(product=product, quantity=-1) elem_cart = cart.get_tr_cart(guid) delete_row = elem_cart['quantity'] <= 0 if delete_row: cart.remove(product) return HttpResponseAjax( delete=delete_row, td_cart_quantity=render_to_string('cart/td_cart_quantity.html', {'goods': elem_cart}), td_cart_total_price=render_to_string('cart/td_cart_total_price.html', {'goods': elem_cart}), td_cart_total_price_ruble=render_to_string('cart/td_cart_total_price_ruble.html', {'goods': elem_cart}), header_cart=render_to_string('cart/header_cart.html', {'cart': cart, 'user': request.user}), user_cart=render_to_string('header/user_tools_cart.html', {'cart': cart, 'user': request.user}) )
def cart_add_quantity(request): try: guid = request.GET.get('guid') except MultiValueDictKeyError: response = HttpResponseAjaxError(code=302, message='no request GET guid') log_response( '%s : no request GET guid', request.path, response=response, request=request, ) return response cart = Cart(request) product = get_object_or_404(Product, guid=guid) quantity = 1 inventory = max(product.get_inventory(cart), 0) inventory = 999999 if inventory > 10 else inventory quantity = min(quantity, inventory) cart.add(product=product, quantity=quantity) elem_cart = cart.get_tr_cart(guid) return HttpResponseAjax( td_cart_quantity=render_to_string('cart/td_cart_quantity.html', {'goods': elem_cart}), td_cart_total_price=render_to_string('cart/td_cart_total_price.html', {'goods': elem_cart}), td_cart_total_price_ruble=render_to_string('cart/td_cart_total_price_ruble.html', {'goods': elem_cart}), header_cart=render_to_string('cart/header_cart.html', {'cart': cart, 'user': request.user}), user_cart=render_to_string('header/user_tools_cart.html', {'cart': cart, 'user': request.user}) )
def order_request(request, **kwargs): order_id = kwargs.get('id', 0) try: order_currently = Order.objects.get(id=order_id) except Order.DoesNotExist: raise Http404() customer = get_customer(request.user) if customer == order_currently.person.customer: if settings.CELERY_NO_CREATE_ORDERS: try: order_currently.request_order() except Order.RequestOrderError: pass else: task_order_request.delay(order_id) return render(request, 'orders/order.html', {'order': order_currently}) else: response = HttpResponseForbidden() log_response( 'Order %s Not Allowed (%s): %s', order_id, request.user, request.path, response=response, request=request, ) return response
def _precondition_failed(request): response = HttpResponse(status=412) log_response( 'Precondition Failed: %s', request.path, response=response, request=request, ) return response
def __call__(self, request, *args, **kwargs): response = self.view_func(request, *args, **kwargs) meta = request.META log_response( f"user-agent: {meta['HTTP_USER_AGENT']}; path: {request.path}", response=response, request=request) return response
def _reject(self, request, reason): response = _get_failure_view()(request, reason=reason) log_response( 'Forbidden (%s): %s', reason, request.path, response=response, request=request, logger=logger, ) return response
def _reject(self, request, reason): response = _get_failure_view()(request, reason=reason) log_response( 'Forbidden (%s): %s', reason, request.path, response=response, request=request, logger=logger, ) return response
def inner(request, *args, **kwargs): if request.method not in request_method_list: response = HttpResponseNotAllowed(request_method_list) log_response( 'Method Not Allowed (%s): %s', request.method, request.path, response=response, request=request, ) return response return func(request, *args, **kwargs)
def inner(request, *args, **kwargs): if request.method not in request_method_list: response = HttpResponseNotAllowed(request_method_list) log_response( 'Method Not Allowed (%s): %s', request.method, request.path, response=response, request=request, ) return response return func(request, *args, **kwargs)
def inner(request, *args, **kwargs): if not request.is_ajax(): response = HttpResponseNotAllowed() log_response( 'Not A Ajax Request (%s): %s', request.method, request.path, response=response, request=request, ) return response return func(request, *args, **kwargs)
def inner(request: 'HttpRequest', *args, **kwargs) -> JsonError: if request.method not in allowed_methods: response = JsonError('Method not allowed', 405) response['Allow'] = ', '.join(allowed_methods) log_response( 'Method Not Allowed (%s): %s', request.method, request.path, response=response, request=request, ) return response return func(request, *args, **kwargs)
def get_goods(request): try: guid = request.GET.get('guid') except MultiValueDictKeyError: response = HttpResponseAjaxError(code=302, message='no request GET guid') log_response( '%s : no request GET guid', request.path, response=response, request=request, ) return response try: only_stock_ = str2bool(request.GET.get('only_stock')) except MultiValueDictKeyError: only_stock_ = False try: only_promo_ = str2bool(request.GET.get('only_promo')) except MultiValueDictKeyError: only_promo_ = False try: obj_section = Section.objects.get(id=guid) except Section.DoesNotExist: response = HttpResponseAjaxError(code=302, message='did not find section') log_response( '%s : did not find section : %s', request.path, str(guid), response=response, request=request, ) return response obj_section.add_current_session(request) is_price_rrp = False cart = Cart(request) goods_list, kwargs = obj_section.get_goods_list_section_with_kwargs( user=request.user, only_stock=only_stock_, only_promo=only_promo_, is_price_rrp=is_price_rrp) is_price_rrp = kwargs.get('is_price_rrp', True) return HttpResponseAjax( current_section=obj_section.full_name, products=render_to_string('goods.html', { 'cart': cart, 'is_price_rrp': is_price_rrp, 'goods_list': goods_list, 'user': request.user }) )
def get_response(self, request): """Return an HttpResponse object for the given HttpRequest.""" # Setup default url resolver for this thread set_urlconf(settings.ROOT_URLCONF) response = self._middleware_chain(request) response._resource_closers.append(request.close) if response.status_code >= 400: log_response( '%s: %s', response.reason_phrase, request.path, response=response, request=request, ) return response
def get_response(self, request): """Return an HttpResponse object for the given HttpRequest.""" # Setup default url resolver for this thread set_urlconf(settings.ROOT_URLCONF) response = self._middleware_chain(request) response._closable_objects.append(request) if response.status_code >= 400: log_response( '%s: %s', response.reason_phrase, request.path, response=response, request=request, ) return response
def inner(request, *args, **kwargs): if request.user.is_anonymous or not request.user.is_authenticated: request.get_full_path() resolved_login_url = resolve_url(settings.LOGIN_URL) response = HttpResponseRedirect(resolved_login_url) log_response( 'Page Not Allowed (%s): %s', request.user, request.path, response=response, request=request, ) return response return func(request, *args, **kwargs)
def _reject(self, request, reason): # response = _get_failure_view()(request, reason=reason) response = JsonResponse( ret_format(result=False, messages='CSRF validation error', level='error', code=420)) log_response( 'Forbidden (%s): %s', reason, request.path, response=response, request=request, logger=logger, ) return response
def inner(request, *args, **kwargs): if request.user.is_anonymous or not request.user.is_authenticated: response = HttpResponseAjax(current_section='', products=render( request, 'account/login_div.html', { 'form': LoginForm() }).content.decode()) log_response( 'Page Not Allowed (%s): %s', request.user, request.path, response=response, request=request, ) return response return func(request, *args, **kwargs)
def get_form_images(request): if request.method == 'POST': pass else: try: guid = request.GET.get('guid') except MultiValueDictKeyError: response = HttpResponseAjaxError(code=302, message='no request GET guid') log_response( '%s : no request GET guid', request.path, response=response, request=request, ) return response try: product = Product.objects.get(guid=guid) except Product.DoesNotExist: response = HttpResponseAjaxError(code=303, message='did not find product') log_response( '%s : did not find product : %s', request.path, str(guid), response=response, request=request, ) return response try: height = int(request.GET.get('height')) except TypeError: height = 699 if height > 700: max_width = 1055 max_height = 745 else: max_width = 531 max_height = 521 return HttpResponseAjax( guid=guid, height=max_height, width=max_width, form_images=render_to_string('goods/show_images.html', {'guid': guid, 'image': ('media/' + str(product.image)), 'max_width': max_width, 'max_height': max_height, 'name': str(product.name)}) )
def order(request, **kwargs): order_id = kwargs.get('id', 0) try: order_currently = Order.objects.get(id=order_id) except Order.DoesNotExist: raise Http404() customer = get_customer(request.user) if customer == order_currently.person.customer: return render(request, 'orders/order.html', {'order': order_currently}) else: response = HttpResponseForbidden() log_response( 'Order %s Not Allowed (%s): %s', order_id, request.user, request.path, response=response, request=request, ) return response
def cart_get_form_quantity(request): if request.method == 'POST': pass else: try: guid = request.GET.get('guid') except MultiValueDictKeyError: response = HttpResponseAjaxError(code=302, message='no request GET guid') log_response( '%s : no request GET guid', request.path, response=response, request=request, ) return response try: product = Product.objects.get(guid=guid) except Product.DoesNotExist: response = HttpResponseAjaxError(code=302, message='did not find product') log_response( '%s : did not find product : %s', request.path, str(guid), response=response, request=request, ) return response cart = Cart(request) is_cart = (cart.get_quantity_product(product.guid) > 0) inventory = max(product.get_inventory(cart), 0) inventory = 999999 if inventory > 10 else inventory if not is_cart and inventory > 0: form = EnterQuantity(initial={'quantity': 1}, max_value=inventory) else: form = EnterQuantityError() return HttpResponseAjax( guid=guid, inventory=inventory, form_enter_quantity=render_to_string('goods/enter_quantity.html', {'form': form, 'guid': guid, 'inventory': inventory, 'is_cart': is_cart}) )
def process_view(self, request, callback, callback_args, callback_kwargs): if getattr(callback, 'origin_poikkeus', False): return None elif 'HTTP_ORIGIN' not in request.META: return None origin = split_domain_port( urlparse(request.META['HTTP_ORIGIN']).netloc.lower())[0] if not validate_host(origin, settings.ALLOWED_HOSTS): virhe = 'Websocket: Origin=%r ei vastaa ALLOWED_HOSTS-asetusta.' % origin response = HttpResponseForbidden(virhe) log_response( virhe, request=request, response=response, logger=logger, ) return response # if not validate_host return None
def process_response(self, request, response): """ 记录请求日志 """ duration = datetime_to_timestamp() - self.req_start log_kwargs = {'response': response, 'request': request} exc = getattr(response, 'with_exception', None) if exc: message = f'"{request.method} {request.get_full_path()}" "{exc.status_code} {exc.__class__.__name__}"' \ f' {len(response.getvalue())} {duration}' log_kwargs.update(level='error') else: message = f'"{request.method} {request.get_full_path()}" "{response.status_code} {response.reason_phrase}"' \ f' {len(response.getvalue())} {duration}' log_response(message, **log_kwargs) return response
def cart_delete_row(request): try: guid = request.GET.get('guid') except MultiValueDictKeyError: response = HttpResponseAjaxError(code=302, message='no request GET guid') log_response( '%s : no request GET guid', request.path, response=response, request=request, ) return response cart = Cart(request) product = get_object_or_404(Product, guid=guid) cart.remove(product) return HttpResponseAjax( header_cart=render_to_string('cart/header_cart.html', {'cart': cart, 'user': request.user}), user_cart=render_to_string('header/user_tools_cart.html', {'cart': cart, 'user': request.user}) )
def get_orders_list(request): try: begin_date_str = request.GET.get('begin_date') except MultiValueDictKeyError: response = HttpResponseAjaxError(code=302, message='no request GET begin_date') log_response( '%s : no request GET begin_date', request.path, response=response, request=request, ) return response try: end_date_str = request.GET.get('end_date') except MultiValueDictKeyError: response = HttpResponseAjaxError(code=302, message='no request GET end_date') log_response( '%s : no request GET end_date', request.path, response=response, request=request, ) return response try: begin_date = datetime.datetime.strptime(begin_date_str, "%d.%m.%Y") except ValueError: begin_date = datetime.datetime.strptime(begin_date_str, "%m/%d/%Y") try: end_date = datetime.datetime.strptime(end_date_str, "%d.%m.%Y") except ValueError: end_date = datetime.datetime.strptime(end_date_str, "%m/%d/%Y") Order.add_current_session(request, begin_date, end_date) orders_list = Order.get_orders_list(request.user, begin_date, end_date) return HttpResponseAjax( list_orders=render_to_string('orders/list_orders_table.html', { 'orders_list': orders_list }) )
def get_response(self, request): """Return an HttpResponse object for the given HttpRequest.""" # Setup default url resolver for this thread set_urlconf(settings.ROOT_URLCONF) response = self._middleware_chain(request) response._closable_objects.append(request) # If the exception handler returns a TemplateResponse that has not # been rendered, force it to be rendered. if not getattr(response, 'is_rendered', True) and callable(getattr(response, 'render', None)): response = response.render() if response.status_code >= 400: log_response( '%s: %s', response.reason_phrase, request.path, response=response, request=request, ) return response
def get_response(self, request): # Setup default url resolver for this thread set_urlconf(settings.ROOT_URLCONF) response = self._middleware_chain(request) response._resource_closers.append(request.close) if getattr(request, "user", None): # Django app – do not change, use default level level = None else: # Whitenoise (staticfiles) or something else before auth middleware level = "debug" log_response( "%s: %s", response.reason_phrase, request.path, level=level, response=response, request=request, ) return response
def get_response(self, request): # self 是「应用对象」,此方法利用「请求对象」创建「响应对象」并返回 # 参数 request 是「请求对象」,它是 django.core.handlers.wsgi.WSGIRequest 类的实例 set_urlconf(settings.ROOT_URLCONF) # self._middleware_chain 属性值是一个中间件类的实例 # 此处调用中间件对象,也就是调用中间件对象的 __call__ 方法 # 所有的中间件对象的 __call__ 方法都是 django.utils.deprecation.MiddlewareMixin.__call__ # 在 __call__ 内部会调用中间件对象的 get_response 方法 # 此方法本身就是另一个中间件对象,然后继续调用它的 __call__ 方法,链式调用 # 最终,调用在当前类中定义的 self._get_response 方法返回响应对象 # 然后链式返回,最后下面这个方法返回响应对象 response = self._middleware_chain(request) response._resource_closers.append(request.close) if response.status_code >= 400: log_response( '%s: %s', response.reason_phrase, request.path, response=response, request=request, ) return response
def cart_add(request): try: guid = request.GET.get('guid') except MultiValueDictKeyError: response = HttpResponseAjaxError(code=302, message='no request GET guid') log_response( '%s : no request GET guid', request.path, response=response, request=request, ) return response try: quantity = request.GET.get('quantity') except MultiValueDictKeyError: response = HttpResponseAjaxError(code=302, message='no request GET quantity') log_response( '%s : no request GET quantity', request.path, response=response, request=request, ) return response try: quantity = int(quantity) except TypeError: response = HttpResponseAjaxError(code=302, message='no quantity int') log_response( '%s : no quantity int : %s', request.path, str(quantity), response=response, request=request, ) return response cart = Cart(request) product = get_object_or_404(Product, guid=guid) inventory = max(product.get_inventory(cart), 0) inventory = 999999 if inventory > 10 else inventory quantity = min(quantity, inventory) if quantity > 0: cart.add(product=product, quantity=quantity) return HttpResponseAjax( cart=render_to_string('cart/cart.html', {'cart': cart}), user_cart=render_to_string('header/user_tools_cart.html', {'cart': cart, 'user': request.user}) )
def response_for_exception(request, exc): if isinstance(exc, Http404): if settings.DEBUG: response = debug.technical_404_response(request, exc) else: response = get_exception_response(request, get_resolver(get_urlconf()), 404, exc) elif isinstance(exc, PermissionDenied): response = get_exception_response(request, get_resolver(get_urlconf()), 403, exc) log_response( "Forbidden (Permission denied): %s", request.path, response=response, request=request, exc_info=sys.exc_info(), ) elif isinstance(exc, MultiPartParserError): response = get_exception_response(request, get_resolver(get_urlconf()), 400, exc) log_response( "Bad request (Unable to parse request body): %s", request.path, response=response, request=request, exc_info=sys.exc_info(), ) elif isinstance(exc, SuspiciousOperation): if isinstance(exc, (RequestDataTooBig, TooManyFieldsSent)): # POST data can't be accessed again, otherwise the original # exception would be raised. request._mark_post_parse_error() # The request logger receives events for any problematic request # The security logger receives events for all SuspiciousOperations security_logger = logging.getLogger("django.security.%s" % exc.__class__.__name__) security_logger.error( str(exc), extra={ "status_code": 400, "request": request }, ) if settings.DEBUG: response = debug.technical_500_response(request, *sys.exc_info(), status_code=400) else: response = get_exception_response(request, get_resolver(get_urlconf()), 400, exc) elif isinstance(exc, SystemExit): # Allow sys.exit() to actually exit. See tickets #1023 and #4701 raise else: signals.got_request_exception.send(sender=None, request=request) response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) log_response( "%s: %s", response.reason_phrase, request.path, response=response, request=request, exc_info=sys.exc_info(), ) # Force a TemplateResponse to be rendered. if not getattr(response, "is_rendered", True) and callable( getattr(response, "render", None)): response = response.render() return response
def execute_graphql_request(self, request, data, query, variables, operation_name, show_graphiql=False): # Back to normal GraphQL processing? if (request != None) or (query == None): return super().execute_graphql_request(request, data, query, variables, operation_name, show_graphiql) # Handle the REST-style request by our data processing lib try: params = loads(query.replace('\'', "\"")) try: # +++ # # Integrate the real data! # # Where to take it from and in which format: srcName = 'av' # this one can be anything - just a sub-folder name in the server config ifaceName = 'av' # support XYZ client lib if not self.dataSrv.validateApiKey(params['apikey'], srcName=srcName, ifaceName=ifaceName): raise Exception('Bad apikey') # This one is special (backward-compatible + arbitrary time period (seconds) is supported) period = params['function'] if ifaceName == 'av': if period == 'TIME_SERIES_DAILY': period = 24 * 3600 period = int(period) res = self.dataSrv.integrateDataOnDemand(params['symbol'], period, params['start'], params['end'], srcName=srcName, ifaceName=ifaceName) # --- res = res.encode('utf-8') except Exception as e: log_response( 'GraphQL-REST dispatch execute_graphql_request: ', response=HttpResponse(status=402), exc_info=sys.exc_info(), ) return ExecutionResult(errors=[e], invalid=True) # Be silent in pure pass-through (invalid json etc.) letting graphene handle it except Exception as e: return ExecutionResult(errors=[e], invalid=True) return ExecutionResult(data=res, invalid=False)
def response_for_exception(request, exc): if isinstance(exc, Http404): if settings.DEBUG: response = debug.technical_404_response(request, exc) else: response = get_exception_response(request, get_resolver(get_urlconf()), 404, exc) elif isinstance(exc, PermissionDenied): response = get_exception_response(request, get_resolver(get_urlconf()), 403, exc) log_response( 'Forbidden (Permission denied): %s', request.path, response=response, request=request, exc_info=sys.exc_info(), ) elif isinstance(exc, MultiPartParserError): response = get_exception_response(request, get_resolver(get_urlconf()), 400, exc) log_response( 'Bad request (Unable to parse request body): %s', request.path, response=response, request=request, exc_info=sys.exc_info(), ) elif isinstance(exc, SuspiciousOperation): if isinstance(exc, (RequestDataTooBig, TooManyFieldsSent)): # POST data can't be accessed again, otherwise the original # exception would be raised. request._mark_post_parse_error() # The request logger receives events for any problematic request # The security logger receives events for all SuspiciousOperations security_logger = logging.getLogger('django.security.%s' % exc.__class__.__name__) security_logger.error( str(exc), extra={'status_code': 400, 'request': request}, ) if settings.DEBUG: response = debug.technical_500_response(request, *sys.exc_info(), status_code=400) else: response = get_exception_response(request, get_resolver(get_urlconf()), 400, exc) elif isinstance(exc, SystemExit): # Allow sys.exit() to actually exit. See tickets #1023 and #4701 raise else: signals.got_request_exception.send(sender=None, request=request) response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) log_response( '%s: %s', response.reason_phrase, request.path, response=response, request=request, exc_info=sys.exc_info(), ) # Force a TemplateResponse to be rendered. if not getattr(response, 'is_rendered', True) and callable(getattr(response, 'render', None)): response = response.render() return response
def log(title, response): log_response( f'{title} ({request.method}): {request.path}', response=response, request=request, )