Dispatches the request

        :param request: Request bean
        :param response: Response bean
168934
def _rest_dispatch(self, request, response):
        # type: (AbstractHTTPServletRequest, AbstractHTTPServletResponse) -> None
        
        # Extract request information
        http_verb = request.get_command()
        sub_path = request.get_sub_path()

        # Find the best matching method, according to the number of
        # readable arguments
        max_valid_args = -1
        best_method = None
        best_args = None
        best_match = None

        for route, method in self.__routes.get(http_verb, {}).items():
            # Parse the request path
            match = route.match(sub_path)
            if not match:
                continue

            # Count the number of valid arguments
            method_args = self.__methods_args[method]
            nb_valid_args = 0
            for name in method_args:
                try:
                    match.group(name)
                    nb_valid_args += 1
                except IndexError:
                    # Argument not found
                    pass

            if nb_valid_args > max_valid_args:
                # Found a better match
                max_valid_args = nb_valid_args
                best_method = method
                best_args = method_args
                best_match = match

        if best_method is None:
            # No match: return a 404 plain text error
            response.send_content(
                404,
                "No method to handle path {0}".format(sub_path),
                "text/plain",
            )
        else:
            # Found a method
            # ... convert arguments
            kwargs = {}
            if best_args:
                for name, converter in best_args.items():
                    try:
                        str_value = best_match.group(name)
                    except IndexError:
                        # Argument is missing: do nothing
                        pass
                    else:
                        if str_value:
                            # Keep the default value when an argument is
                            # missing, i.e. don't give it in kwargs
                            if converter is not None:
                                # Convert the argument
                                kwargs[name] = converter(str_value)
                            else:
                                # Use the string value as is
                                kwargs[name] = str_value

            # Prepare positional arguments
            extra_pos_args = []
            if kwargs:
                # Ignore the first two parameters (request and response)
                method_args = get_method_arguments(best_method).args[:2]
                for pos_arg in method_args:
                    try:
                        extra_pos_args.append(kwargs.pop(pos_arg))
                    except KeyError:
                        pass

            # ... call the method (exceptions will be handled by the server)
            best_method(request, response, *extra_pos_args, **kwargs)
589890
def dispatch(request)
      request.each_network do |network, channels|
        connection = connection_to(network)
        next if connection.nil?

        channels.each do |channel|
          message = request.to_message_for channel
          connection.enqueue message
        end
      end
    end
54124
def dispatch(self, request):
        
        login_done_url = reverse(self.adapter.provider_id + "_callback")
        client = self._get_client(request, login_done_url)
        if not client.is_valid():
            if 'denied' in request.GET:
                error = AuthError.CANCELLED
            else:
                error = AuthError.UNKNOWN
            extra_context = dict(oauth_client=client)
            return render_authentication_error(
                request,
                self.adapter.provider_id,
                error=error,
                extra_context=extra_context)
        app = self.adapter.get_provider().get_app(request)
        try:
            access_token = client.get_access_token()
            token = SocialToken(
                app=app,
                token=access_token['oauth_token'],
                # .get() -- e.g. Evernote does not feature a secret
                token_secret=access_token.get('oauth_token_secret', ''))
            login = self.adapter.complete_login(request,
                                                app,
                                                token,
                                                response=access_token)
            login.token = token
            login.state = SocialLogin.unstash_state(request)
            return complete_social_login(request, login)
        except OAuthError as e:
            return render_authentication_error(
                request,
                self.adapter.provider_id,
                exception=e)
41014
def _handle(self, request: Request, response: Response) -> TypeGenerator[Any, None, None]:
        
        # request.start_time = datetime.now().timestamp()
        # 创建一个新的会话上下文
        ctx = self._context(
            cast(asyncio.AbstractEventLoop, self._loop),
            request,
            response,
            self,
        )
        request.app = self
        response.app = self
        request.ctx = ctx
        response.ctx = ctx
        request.response = response
        response.request = request

        # 把当前注册的中间件转为迭代器
        middleware_iter = iter(self._middleware)
        # 通过迭代器的模式生成一个执行下一个中间的调用方法
        next_call = self._next_middleware(middleware_iter, ctx)
        # 顺序执行中间件
        yield from self._middleware_call(middleware_iter, ctx, next_call)
        # 设置 cookies
        cookies_headers = ctx.cookies.headers()
        if cookies_headers is not None:
            ctx.response.set("Set-Cookie", cookies_headers)
        # 写出 headers
        ctx.response.flush_headers()
        # 写出 body
        ctx.response.flush_body()
983409
def dispatch_request(self, *args, **kwargs):
        
        if self.validation:
            specs = {}
            attrs = flasgger.constants.OPTIONAL_FIELDS + [
                'parameters', 'definitions', 'responses',
                'summary', 'description'
            ]
            for attr in attrs:
                specs[attr] = getattr(self, attr)
            definitions = {}
            specs.update(convert_schemas(specs, definitions))
            specs['definitions'] = definitions
            flasgger.utils.validate(
                specs=specs, validation_function=self.validation_function)
        return super(SwaggerView, self).dispatch_request(*args, **kwargs)
1151817
def dispatch(self, method, url, auth=None, params=None, **kwargs):
        
        r = Request(
            method=method,
            url=url,
            auth=auth,
            params=params,
            data=kwargs)
        s = Session()
        resp = s.send(r.prepare())
        status = resp.status_code
        text = resp.text
        error = resp.reason
        if status >= 200 and status < 300:
            if text:
                try:
                    return (True, json.loads(text))
                except TypeError:
                    pass
                except ValueError:
                    pass
            return (True, text)
        elif status >= 300 and status < 400:
            return (
                False,
                'Unauthorized access, '
                'please check your credentials.')
        elif status >= 400 and status < 500:
            return (False, 'Service not found.')
        elif status >= 500 and status < 600:
                return (False, 'Server error.')
        else:
            return (False, error)
188819
def dispatch(self, operation, request, **path_args):
        
        # Add current operation to the request (for convenience in middleware methods)
        request.current_operation = operation

        try:
            for middleware in self.middleware.pre_request:
                response = middleware(request, path_args)
                # Return HttpResponse if one is returned.
                if isinstance(response, HttpResponse):
                    return response

            response = self._dispatch(operation, request, path_args)

            for middleware in self.middleware.post_request:
                response = middleware(request, response)

        except Exception as ex:
            if self.debug_enabled:
                # If debug is enabled then fallback to the frameworks default
                # error processing, this often provides convenience features
                # to aid in the debugging process.
                raise
            self.handle_500(request, ex)
            return HttpResponse("Error processing response.", HTTPStatus.INTERNAL_SERVER_ERROR)

        else:
            return response
285240
def request_method(request)
      return request.request_method           if request.request_method != 'POST'
      return request.params['_method'].upcase if request.params['_method']
      request.request_method
    end
1169329
def dispatch_request(self, req):
        
        log.debug("Dispatching request: {}".format(str(req)))

        # make sure it's valid
        res = None
        try:
            req.validate()
        except MissingFieldError as e:
            res = APIMissingFieldErrorResponse(str(e))

        # dispatch the request
        if not res:
            try:
                res = req.dispatch()
            except Exception as e:
                msg = "Exception raised while dispatching request: {}".format(repr(e))
                log.exception(msg)
                res = APIGenericErrorResponse(msg)

        log.debug("Response: {}".format(str(res)))

        return res
462983
async def dispatch(self, request, view=None, **kwargs):
        """"""
        # Authorization endpoint
        self.auth = await self.authorize(request, **kwargs)  # noqa

        # Load collection
        self.collection = await self.get_many(request, **kwargs)

        if request.method == 'POST' and view is None:
            return await super(RESTHandler, self).dispatch(request, **kwargs)

        # Load resource
        resource = await self.get_one(request, **kwargs)

        headers = {}

        if request.method == 'GET' and resource is None:

            # Filter resources
            if VAR_WHERE in request.query:
                self.collection = await self.filter(request, **kwargs)

            # Sort resources
            if VAR_SORT in request.query:
                sorting = [(name.strip('-'), name.startswith('-'))
                           for name in request.query[VAR_SORT].split(',')]
                self.collection = await self.sort(*sorting, **kwargs)

            # Paginate resources
            per_page = request.query.get(VAR_PER_PAGE, self.meta.per_page)
            if per_page:
                try:
                    per_page = int(per_page)
                    if per_page:
                        page = int(request.query.get(VAR_PAGE, 0))
                        offset = page * per_page
                        self.collection, total = await self.paginate(request, offset, per_page)
                        headers = make_pagination_headers(
                            request, per_page, page, total, self.meta.page_links)
                except ValueError:
                    raise RESTBadRequest(reason='Pagination params are invalid.')

        response = await super(RESTHandler, self).dispatch(
            request, resource=resource, view=view, **kwargs)
        response.headers.update(headers)
        return response
663943
public void setDispatch(Dispatcher.DispatcherRequest request, Dispatcher.DispatcherResponse response)
    {
        ThreadState state=state();
        state.dispatchRequest=request;
        state.dispatchResponse=response;
    }
294749
def dispatch(self, request, **kwargs):
        '''
        
        '''

        # Check if this is a REST query to pusth the answer to responde in JSON
        if bool(self.request.META.get('HTTP_X_REST', False)):
            self.json = True

        # Check if this is a REST query to add an element
        if self.request.method in ['PUT', 'DELETE']:
            if self.request.method == 'PUT':
                action = 'edit'
            else:
                action = 'delete'

            # Set new method
            self.request.method == 'POST'

            # Find the URL
            target = get_class(resolve("{}/{}".format(self.request.META.get("REQUEST_URI"), action)).func)

            # Make sure we will answer as an API
            target.json = True

            # Lets go for it
            return target.as_view()(self.request, pk=kwargs.get('pk'))

        # Detect if we have to answer in json
        self.__authtoken = (bool(getattr(self.request, "authtoken", False)))
        self.json_worker = self.__authtoken or (self.json is True)

        # Check if this is an AJAX request
        if (request.is_ajax() or self.json_worker) and request.body:
            request.POST = json.loads(request.body)

        # Set class internal variables
        self._setup(request)

        # Call the base implementation
        return super(GenDetail, self).dispatch(request, **kwargs)
926155
def dispatch(self, request, *args, **kwargs):
        
        if request.GET.get(self.xeditable_fieldname_param):
            return self.get_ajax_xeditable_choices(request, *args, **kwargs)
        return super(XEditableMixin, self).dispatch(request, *args, **kwargs)
1092666
def process_request(self, request, client_address):
    
    t = threading.Thread(
      target=self.process_request_thread,
      args=(request, client_address),
      name="PailgunRequestThread",
    )
    t.daemon = self.daemon_threads
    t.start()
426997
async def dispatch(self, request, **kwargs):
        """"""
        # Authorize request
        self.auth = await self.authorize(request)

        # Load collection
        self.collection = await self.load_many(request)

        # Load resource
        self.resource = await self.load_one(request)

        if request.method == 'GET' and self.resource is None:

            # Filter collection
            self.collection = await self.filter(request)

            # Sort collection
            self.columns_sort = request.query.get('ap-sort', self.columns_sort)
            if self.columns_sort:
                reverse = self.columns_sort.startswith('-')
                self.columns_sort = self.columns_sort.lstrip('+-')
                self.collection = await self.sort(request, reverse=reverse)

            # Paginate collection
            try:
                self.offset = int(request.query.get('ap-offset', 0))
                if self.limit:
                    self.count = await self.count(request)
                    self.collection = await self.paginate(request)
            except ValueError:
                pass

        return await super(AdminHandler, self).dispatch(request, **kwargs)
1102874
def dispatch(self):
        """"""
        method_name = 'on_' + self.environ['REQUEST_METHOD'].lower()
        method = getattr(self, method_name, None)
        if method:
            return method()
        else:
            return self.on_bad_method()
1004525
async def send(self, request: Request, **kwargs) -> Response:
        
        if request.context is None:  # Should not happen, but make mypy happy and does not hurt
            request.context = self.build_context()

        if request.context.session is not self.driver.session:
            kwargs['session'] = request.context.session

        return Response(
            request,
            await self.driver.send(request.http_request, **kwargs)
        )