Exemplo n.º 1
0
    def _build_request(self, method, params):
        # For Django QuerySet and SQLGen
        if hasattr(params[0], "query"):
            params = (str(params[0].query), ) + params[1:]

        self._cached_request_args = (method, params)  # backup for retry
        if self._use_cache and rcache.the_rcache:
            self._cached_result = rcache.the_rcache.get(
                self._get_ident(), self._use_cache)
            if self._cached_result is not None:
                self._callback and tuple_cb(self._cached_result,
                                            self._callback)
                return

        while self._avails():
            asyncon = self._get_connection(None)
            rs = Dispatcher(self._cv,
                            asyncon.address,
                            ident=not self._mapreduce and self._get_ident()
                            or None,
                            filterfunc=self._filter,
                            callback=self._collect)
            self._requests[rs] = asyncon

            req = request.Request(self.dbtype, self.server, self.dbname,
                                  self.auth, method, params, rs.handle_result,
                                  self._meta)
            asyncon.execute(req)

        self._request = req  # sample for unitest
        trigger.wakeup()
        return self
Exemplo n.º 2
0
    def exec_app(self):
        # this is not just for atila,
        # Corequest need request and response
        was = the_was._get()
        was.apps = self.apps
        was.request = self.request
        was.response = self.request.response
        was.env = self.args[0]
        was.env["skitai.was"] = was

        response = self.request.response
        try:
            content = self.apph(*self.args)
            will_be_push = make_pushables(response, content)
        except MemoryError:
            raise
        except:
            was.traceback()
            trigger.wakeup(
                lambda p=response, d=self.apph.debug and sys.exc_info() or
                None: (p.error(500, "Internal Server Error", d), p.done()))
        else:
            if will_be_push is None:  # not responsible or futures
                return
            for part in will_be_push:
                if len(will_be_push) == 1 and type(part) is bytes and len(
                        response) == 0:
                    response.update("Content-Length", len(part))
                response.push(part)
            trigger.wakeup(lambda p=response: (p.done(), ))
Exemplo n.º 3
0
 def _send(self, msg):
     if self.channel:
         if hasattr(self.wasc, 'threads'):
             trigger.wakeup(lambda p=self.channel, d=msg: (p.push(d), ))
         else:
             self.channel.push(msg)
Exemplo n.º 4
0
 def send(self, data):
     if self._done:
         return
     self._data.append(self.encode(data))
     if self.was.env['wsgi.multithread']:
         trigger.wakeup()
Exemplo n.º 5
0
    def _build_request(self, method, params):
        self._cached_request_args = (method, params)  # backup for retry
        if self._use_cache and rcache.the_rcache:
            self._cached_result = rcache.the_rcache.get(
                self._get_ident(), self._use_cache)
            if self._cached_result is not None:
                self._cached_result.meta = self._meta
                self._callback and tuple_cb(self._cached_result,
                                            self._callback)
                return
            else:
                self._use_cache = False

        requests = 0
        while self._avails():
            if self._cluster.get_name() != "__socketpool__":
                asyncon = self._get_connection(None)
            else:
                asyncon = self._get_connection(self._uri)

            self._auth = self._auth or asyncon.get_auth()
            _reqtype = self._reqtype.lower()
            rs = Dispatcher(self._cv,
                            asyncon.address,
                            ident=not self._mapreduce and self._get_ident()
                            or None,
                            filterfunc=self._filter,
                            cachefs=self._cachefs,
                            callback=self._collect)
            self._requests[rs] = asyncon
            args = (params, self._headers, self._auth, self._logger,
                    self._meta)
            try:
                if _reqtype in ("ws", "wss"):
                    handler = ws_request_handler.RequestHandler
                    request = ws_request.Request(self._uri, *args)
                else:
                    if not self._use_cache:
                        self._add_header("Cache-Control", "no-cache")
                    handler = http_request_handler.RequestHandler
                    try:
                        class_ = self.proto_map[_reqtype]
                    except KeyError:
                        if _reqtype == "upload":
                            request = http_request.HTTPMultipartRequest(
                                self._uri, _reqtype, *args)
                        else:
                            request = http_request.HTTPRequest(
                                self._uri, _reqtype, *args)
                    else:
                        request = class_(self._uri, method, *args)
                requests += self._handle_request(request, rs, asyncon, handler)

            except:
                self._logger("Request Creating Failed", "fail")
                self._logger.trace()
                rs.request_failed()
                asyncon.set_active(False)
                continue

        if requests:
            self._request = request  # sample for unitest
            trigger.wakeup()

        if _reqtype[-3:] == "rpc":
            return self
Exemplo n.º 6
0
def make_pushables(response, content):
    from .wastuff import futures
    from .wastuff.api import API

    if not response.is_responsable():
        # already called response.done () or diconnected channel
        return

    if content is None:  # Possibly no return mistake
        raise AssertionError("Content or part should not be None")

    if not content:  # explicit empty not content
        trigger.wakeup(lambda p=response: (p.done(), ))
        return

    if type(content) not in (list, tuple):
        content = (content, )  # make iterable

    if isinstance(content[0], futures.Futures):
        return

    if response["content-type"] is None:
        response["Content-Type"] = "text/html"

    will_be_push = []
    if len(response) == 0:
        content_length = 0
    else:
        content_length = None

    for part in content:
        # like Django response
        try:
            part = part.content
        except AttributeError:
            pass

        type_of_part = type(part)

        if isinstance(part, API):
            response.update("Content-Type", part.get_content_type())
            part = part.to_string().encode("utf8")
            will_be_push.append(part)

        elif type_of_part in (bytes, str):
            if len(part) == 0:
                continue
            if type_of_part is not bytes:
                try:
                    part = part.encode("utf8")
                except AttributeError:
                    raise AssertionError("%s is not supportable content type" %
                                         str(type(part)).replace(
                                             "<", "&lt;").replace(">", "&gt;"))
                type_of_part = bytes

            if type_of_part is bytes:
                if content_length is not None:
                    content_length += len(part)
                will_be_push.append(part)

        else:
            if hasattr(part, "read"):
                part = producers.closing_stream_producer(part)
            elif type(part) is list:
                part = producers.list_producer(part)
            elif isinstance(part, Iterator):  # flask etc.
                part = producers.iter_producer(part)

            if hasattr(part, "more"):
                # producer
                content_length = None
                # automatic close    when channel suddenly closed
                hasattr(part, "close") and response.die_with(part)
                # streaming obj
                hasattr(part, "ready") and response.set_streaming()
                will_be_push.append(part)

            else:
                raise AssertionError("Unsupoorted response object")

    if content_length is not None:
        response["Content-Length"] = content_length

    return will_be_push