aiohttp.Response

Here are the examples of the python api aiohttp.Response taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

21 Examples 7

Example 1

Project: aiorest
License: View license
Source File: handler.py
    def handle_error(self, status=500, message=None, payload=None,
                     exc=None, headers=None):
        now = time.time()
        if isinstance(exc, errors.RESTError):
            if status == 500:
                self.log_exception("Error handling request")
            resp_impl = aiohttp.Response(self.writer, status, close=True)
            resp_impl.add_header('Host', self.hostname)
            yield from exc.write_response(resp_impl)
            self.log_access(message, None, resp_impl, time.time() - now)
            self.keep_alive(False)
        else:
            super().handle_error(status, message, payload,
                                 exc=exc, headers=headers)

Example 2

Project: luvs
License: View license
Source File: unifi_stream_server.py
    @asyncio.coroutine
    def handle_request(self, message, payload):
        self._log.debug('GET %s' % message.path)

        path_elements = message.path.split('/')
        self._log.debug('Path: %s' % path_elements)
        if len(path_elements) == 4 and path_elements[1] == 'stream':
            camera_mac = path_elements[2]
            stream = path_elements[3]
            self._log.debug('Requested stream %s for %s' % (stream,
                                                            camera_mac))
            yield from self._do_stream(message, payload, camera_mac, stream)
        else:
            response = aiohttp.Response(self.writer, 403)
            response.send_headers()
            response.write_eof()

Example 3

Project: openwepro
License: View license
Source File: weproserver.py
    @asyncio.coroutine
    def send_homepage(self, message, payload):
        response = aiohttp.Response(self.writer, 200, http_version=message.version)
        response.add_header('Content-Type', 'text/html; charset=utf-8')
        response.add_header('Content-Length', str(len(self.clienthtml)))
        response.send_headers()
        response.write(self.clienthtml)
        yield from response.write_eof()

Example 4

Project: openwepro
License: View license
Source File: weproserver.py
    @asyncio.coroutine
    def send_js(self, message, payload):
        response = aiohttp.Response(self.writer, 200, http_version=message.version)
        response.add_header('Cache-Control', 'max-age=600')
        response.add_header('Content-Type', 'application/javascript; charset=utf-8')
        response.add_header('Content-Length', str(len(self.clientjs)))
        response.send_headers()
        response.write(self.clientjs)
        yield from response.write_eof()

Example 5

Project: openwepro
License: View license
Source File: weproserver.py
    @asyncio.coroutine
    def send_empty_js(self, message, payload):
        response = aiohttp.Response(self.writer, 200, http_version=message.version)
        response.add_header('Cache-Control', 'max-age=604800')
        response.add_header('Content-Type', 'application/javascript; charset=utf-8')
        response.add_header('Content-Length', '6')
        response.send_headers()
        response.write(b'void 0')
        yield from response.write_eof()

Example 6

Project: openwepro
License: View license
Source File: weproserver.py
    @asyncio.coroutine
    def send_404(self, message, payload, url):
        responseHtml = b'<h1>Error 404: Not Found</h1>'
        response = aiohttp.Response(self.writer, 404, http_version=message.version)
        response.add_header('Content-Type', 'text/html; charset=utf-8')
        response.add_header('Content-Length', str(len(responseHtml)))
        response.send_headers()
        response.write(responseHtml)
        yield from response.write_eof()

Example 7

Project: luvs
License: View license
Source File: unifi_stream_server.py
    def _do_stream(self, message, payload, camera_mac, stream):
        response = aiohttp.Response(self.writer, 200,
                                    http_version=message.version)
        try:
            self._context = yield from controller.stream_camera(camera_mac,
                                                                stream,
                                                                response)
        except NoSuchCamera:
            response = aiohttp.Response(self.writer, 404)
            response.send_headers()
            response.write_eof()
            return
        except CameraInUse:
            response = aiohttp.Response(self.writer, 409)
            response.send_headers()
            response.write_eof()
            return

        while (self._context.streaming
                   and controller.ws_server.is_camera_managed(camera_mac)):
            yield from asyncio.sleep(1)

        self._log.debug('Closing HTTP streaming connection for %s' % camera_mac)
        response.write_eof()
        self._context.controller.streaming_stopped(self._context)

Example 8

Project: pycon2014
License: View license
Source File: e11asyncmultitenant.py
    @asyncio.coroutine
    def handle_request(self, message, payload):
        response = Response(self.writer, 200)
        response.add_header('Content-Type', 'text/html')
        response.send_headers()

        if message.method == 'GET':
            response.write(MY_FORM.encode('utf-8'))
        elif message.method == 'POST':
            data = yield from payload.read()
            data = data.decode('utf-8')
            url = dict(parse_qsl(data)).get('url')
            result = yield from crawl_async(url, 1, 1)
            response.write(b'<pre>')
            top_words = get_global_words(result)
            message = get_top_words_message(top_words)
            response.write(escape(message).encode('utf-8'))
            response.write(b'</pre>')
        else:
            response.write('Bad method')

        response.write_eof()

Example 9

Project: aiorest
License: View license
Source File: handler.py
    @asyncio.coroutine
    def handle_request(self, message, payload):
        now = time.time()
        # self.log.debug("Start handle request %r at %d", message, now)

        try:
            if payload is not None:
                req_body = bytearray()
                while True:
                    chunk = yield from payload.readany()
                    req_body.extend(chunk)
                    if chunk is EOF_MARKER:
                        break
            else:
                req_body = None

            request = Request(self.hostname, message, req_body,
                              session_factory=self.session_factory,
                              loop=self._loop,
                              identity_policy=self._identity_policy,
                              auth_policy=self._auth_policy)

            body = yield from self.server.dispatch(request)
            bbody = body.encode('utf-8')
            resp_impl = aiohttp.Response(
                self.writer, request.response.status_code,
                http_version=message.version)

            yield from request._call_response_callbacks()

            resp_impl.add_header('Host', self.hostname)
            resp_impl.add_header('Content-Type', 'application/json')

            # content encoding
            accept_encoding = message.headers.get('ACCEPT-ENCODING',
                                                  '').lower()
            accept_encoding = set(map(str.strip, accept_encoding.split(',')))
            if 'deflate' in accept_encoding:
                resp_impl.add_header('Transfer-Encoding', 'chunked')
                resp_impl.add_header('Content-Encoding', 'deflate')
                resp_impl.add_compression_filter('deflate')
                resp_impl.add_chunking_filter(1025)
            elif 'gzip' in accept_encoding:
                resp_impl.add_header('Transfer-Encoding', 'chunked')
                resp_impl.add_header('Content-Encoding', 'gzip')
                resp_impl.add_compression_filter('gzip')
                resp_impl.add_chunking_filter(1025)
            else:
                resp_impl.add_header('Content-Length', str(len(bbody)))

            headers = request.response.headers.items()
            for key, val in headers:
                resp_impl.add_header(key, val)

            resp_impl.send_headers()
            resp_impl.write(bbody)
            yield from resp_impl.write_eof()
            if resp_impl.keep_alive():
                self.keep_alive(True)

            # self.log.debug("Fihish handle request %r at %d -> %s",
            #               message, time.time(), body)
            self.log_access(message, None, resp_impl, time.time() - now)
        except Exception:
            # self.log.exception("Cannot handle request %r", message)
            raise

Example 10

Project: elasticsearch-py-async
License: View license
Source File: conftest.py
    @asyncio.coroutine
    def handle_request(self, message, payload):
        url = urlparse(message.path)

        params = dict(parse_qsl(url.query))
        body = yield from payload.read()
        body = json.loads(body.decode('utf-8')) if body else ''

        self.calls.append((message.method, url.path, body, params))

        if url.path in self._responses:
            status, body = self._responses.pop(url.path)
            if asyncio.iscoroutine(body):
                body = yield from body
        else:
            status = 200
            body = {
                'method': message.method,
                'params': params,
                'path': url.path,
                'body': body
            }

        out = json.dumps(body).encode('utf-8')

        response = Response(self.writer, status)
        response.send_headers()
        response.write(out)
        yield from response.write_eof()

Example 11

Project: aiohttp
License: View license
Source File: server.py
    def handle_error(self, status=500, message=None,
                     payload=None, exc=None, headers=None, reason=None):
        """Handle errors.

        Returns HTTP response with specific status code. Logs additional
        information. It always closes current connection."""
        now = self._loop.time()
        try:
            if self.transport is None:
                # client has been disconnected during writing.
                return ()

            if status == 500:
                self.log_exception("Error handling request")

            try:
                if reason is None or reason == '':
                    reason, msg = RESPONSES[status]
                else:
                    msg = reason
            except KeyError:
                status = 500
                reason, msg = '???', ''

            if self.debug and exc is not None:
                try:
                    tb = traceback.format_exc()
                    tb = html_escape(tb)
                    msg += '<br><h2>Traceback:</h2>\n<pre>{}</pre>'.format(tb)
                except:
                    pass

            html = DEFAULT_ERROR_MESSAGE.format(
                status=status, reason=reason, message=msg).encode('utf-8')

            response = aiohttp.Response(self.writer, status, close=True)
            response.add_header(hdrs.CONTENT_TYPE, 'text/html; charset=utf-8')
            response.add_header(hdrs.CONTENT_LENGTH, str(len(html)))
            if headers is not None:
                for name, value in headers:
                    response.add_header(name, value)
            response.send_headers()

            response.write(html)
            # disable CORK, enable NODELAY if needed
            self.writer.set_tcp_nodelay(True)
            drain = response.write_eof()

            self.log_access(message, None, response, self._loop.time() - now)
            return drain
        finally:
            self.keep_alive(False)

Example 12

Project: aiohttp
License: View license
Source File: server.py
    def handle_request(self, message, payload):
        """Handle a single HTTP request.

        Subclass should override this method. By default it always
        returns 404 response.

        :param message: Request headers
        :type message: aiohttp.protocol.HttpRequestParser
        :param payload: Request payload
        :type payload: aiohttp.streams.FlowControlStreamReader
        """
        now = self._loop.time()
        response = aiohttp.Response(
            self.writer, 404, http_version=message.version, close=True)

        body = b'Page Not Found!'

        response.add_header(hdrs.CONTENT_TYPE, 'text/plain')
        response.add_header(hdrs.CONTENT_LENGTH, str(len(body)))
        response.send_headers()
        response.write(body)
        drain = response.write_eof()

        self.keep_alive(False)
        self.log_access(message, None, response, self._loop.time() - now)

        return drain

Example 13

Project: aiohttp
License: View license
Source File: wsgi.py
    def start_response(self, status, headers, exc_info=None):
        if exc_info:
            try:
                if self.status:
                    raise exc_info[1]
            finally:
                exc_info = None

        status_code = int(status.split(' ', 1)[0])

        self.status = status
        resp = self.response = aiohttp.Response(
            self.writer, status_code,
            self.message.version, self.message.should_close)
        resp.HOP_HEADERS = self.HOP_HEADERS
        for name, value in headers:
            resp.add_header(name, value)

        if resp.has_chunked_hdr:
            resp.enable_chunked_encoding()

        # send headers immediately for websocket connection
        if status_code == 101 and resp.upgrade and resp.websocket:
            resp.send_headers()
        else:
            resp._send_headers = True
        return self.response.write

Example 14

Project: aiohttp
License: View license
Source File: basic_srv.py
    @asyncio.coroutine
    def handle_request(self, message, payload):
        response = aiohttp.Response(
            self.writer, 200, http_version=message.version)
        get_params = MultiDict(parse_qsl(urlparse(message.path).query))
        if message.method == 'POST':
            post_params = yield from payload.read()
        else:
            post_params = None
        content = "<h1>It Works!</h1>"
        if get_params:
            content += "<h2>Get params</h2><p>" + str(get_params) + "</p>"
        if post_params:
            content += "<h2>Post params</h2><p>" + str(post_params) + "</p>"
        bcontent = content.encode('utf-8')
        response.add_header('Content-Type', 'text/html; charset=UTF-8')
        response.add_header('Content-Length', str(len(bcontent)))
        response.send_headers()
        response.write(bcontent)
        yield from response.write_eof()

Example 15

    def _start_response(self, code):
        return aiohttp.Response(self._srv.writer, code)

Example 16

Project: openwepro
License: View license
Source File: weproserver.py
    @asyncio.coroutine
    def handle_request(self, message, payload):
        if self.auth_passwd:
            auth_secret = message.headers.get('AUTHORIZATION')
            if not auth_secret or auth_secret[:6].upper() != 'BASIC ' or auth_secret[6:] not in self.auth_passwd:
                response = aiohttp.Response(self.writer, 401, http_version=message.version)
                response.SERVER_SOFTWARE = 'HTTPd'
                response.add_header('WWW-Authenticate', 'Basic realm="%s"' % self.auth_realm)
                response.add_header('Content-Length', '0')
                response.send_headers()
                yield from response.write_eof()
                return
        url = message.path
        if url.startswith(self.path_prefix):
            url = url[len(self.path_prefix):]
        else:
            return (yield from self.send_404(message, payload, url))
        if not url or url == '/':
            return (yield from self.send_homepage(message, payload))
        elif url == '/about/empty.js':
            return (yield from self.send_empty_js(message, payload))
        elif url.startswith('/about/openwepro.js?'):
            return (yield from self.send_js(message, payload))
        target_url = self.parse_url(url, False)
        if target_url is None:
            return (yield from self.send_404(message, payload, url))
        else:
            return (yield from self.do_http_proxy(message, payload, target_url))
        return (yield from self.send_404(message, payload, url))

Example 17

Project: snare
License: View license
Source File: snare.py
    @asyncio.coroutine
    def handle_request(self, request, payload):
        print('Request path: {0}'.format(request.path))
        data = self.create_data(request, 200)
        if request.method == 'POST':
            post_data = yield from payload.read()
            post_data = MultiDict(parse_qsl(post_data.decode('utf-8')))
            print('POST data:')
            for key, val in post_data.items():
                print('\t- {0}: {1}'.format(key, val))
            data['post_data'] = dict(post_data)

        # Submit the event to the TANNER service
        event_result = yield from self.submit_data(data)

        # Log the event to slurp service if enabled
        if self.run_args.slurp_enabled:
            yield from self.submit_slurp(request.path)
        response = aiohttp.Response(
            self.writer, status=200, http_version=request.version
        )
        mimetypes.add_type('text/html', '.php')
        if 'payload' in event_result['response']['message']['detection']:
            payload_content = event_result['response']['message']['detection']['payload']
            if type(payload_content) == dict:
                content_type = mimetypes.guess_type(payload_content['page'])[0]
                content = '<html><body></body></html>'
                base_path = '/'.join(['/opt/snare/pages', self.run_args.page_dir])
                if os.path.exists(base_path + payload_content['page']):
                    with open(base_path + payload_content['page']) as p:
                        content = p.read()
                soup = BeautifulSoup(content, 'html.parser')
                script_tag = soup.new_tag('div')
                script_tag.append(BeautifulSoup(payload_content['value'], 'html.parser'))
                soup.body.append(script_tag)
                content = str(soup).encode()

            else:
                content_type = mimetypes.guess_type(payload_content)[0]
                content = payload_content.encode('utf-8')
        else:
            base_path = '/'.join(['/opt/snare/pages', self.run_args.page_dir])
            query = None
            if request.path == '/':
                parsed_url = self.run_args.index_page
            else:
                parsed_url = urlparse(unquote(request.path))
                if parsed_url.query:
                    query = '?' + parsed_url.query
                parsed_url = parsed_url.path
                if parsed_url.startswith('/'):
                    parsed_url = parsed_url[1:]
            path = '/'.join(
                [base_path, parsed_url]
            )
            content_type = mimetypes.guess_type(path)[0]
            if content_type is None and '.php' in path:
                content_type = 'text/html'
            if query is not None:
                path = os.path.normpath(path + query)
            else:
                path = os.path.normpath(path)
            if os.path.isfile(path) and path.startswith(base_path):
                with open(path, 'rb') as fh:
                    content = fh.read()
                if content_type:
                    if 'text/html' in content_type:
                        content = yield from self.handle_html_content(content)
            else:
                content_type = None
                content = None
                response = aiohttp.Response(
                    self.writer, status=404, http_version=request.version
                )
        if not content_type:
            response.add_header('Content-Type', 'text/plain')
        else:
            response.add_header('Content-Type', content_type)
        if content:
            response.add_header('Content-Length', str(len(content)))
        response.send_headers()
        if content:
            response.write(content)
        yield from response.write_eof()

Example 18

Project: tanner
License: View license
Source File: server.py
    @asyncio.coroutine
    def handle_request(self, message, payload):
        response = aiohttp.Response(
            self.writer, 200, http_version=message.version
        )
        if message.path == '/dorks':
            dorks = yield from self.dorks.choose_dorks(self.redis_client)
            response_msg = json.dumps(
                dict(version=1, response=dict(dorks=dorks)),
                sort_keys=True, indent=2
            ).encode('utf-8')
        elif message.path == '/event':
            data = yield from payload.read()
            response_msg = yield from self.handle_event(data, self.redis_client)
        elif message.path.startswith('/api'):
            data = yield from self.api.handle_api_request(message.path, self.redis_client)
            response_msg = self._make_response(data)
        else:
            response_msg = self._make_response(msg='')

        response.add_header('Content-Type', 'application/json')
        response.add_header('Content-Length', str(len(response_msg)))
        response.send_headers()
        response.write(response_msg)
        yield from response.write_eof()

Example 19

Project: aiosocks
License: View license
Source File: helpers.py
@contextlib.contextmanager
def http_srv(loop, *, listen_addr=('127.0.0.1', 0), use_ssl=False):
    transports = []

    class TestHttpServer(ServerHttpProtocol):

        def connection_made(self, transport):
            transports.append(transport)
            super().connection_made(transport)

        @asyncio.coroutine
        def handle_request(self, message, payload):
            response = aiohttp.Response(self.writer, 200, message.version)

            text = b'Test message'
            response.add_header('Content-type', 'text/plain')
            response.add_header('Content-length', str(len(text)))
            response.send_headers()
            response.write(text)
            response.write_eof()

    if use_ssl:
        here = os.path.join(os.path.dirname(__file__), '..', 'tests')
        keyfile = os.path.join(here, 'sample.key')
        certfile = os.path.join(here, 'sample.crt')
        sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        sslcontext.load_cert_chain(certfile, keyfile)
    else:
        sslcontext = None

    def run(_fut):
        thread_loop = asyncio.new_event_loop()
        asyncio.set_event_loop(thread_loop)

        host, port = listen_addr

        srv_coroutine = thread_loop.create_server(
            lambda: TestHttpServer(), host, port, ssl=sslcontext)
        srv = thread_loop.run_until_complete(srv_coroutine)

        waiter = asyncio.Future(loop=thread_loop)
        loop.call_soon_threadsafe(
            _fut.set_result, (thread_loop, waiter,
                              srv.sockets[0].getsockname()))

        try:
            thread_loop.run_until_complete(waiter)
        finally:
            # close opened transports
            for tr in transports:
                tr.close()

            srv.close()
            thread_loop.stop()
            thread_loop.close()
            gc.collect()

    fut = asyncio.Future(loop=loop)
    srv_thread = threading.Thread(target=run, args=(fut,))
    srv_thread.start()

    _thread_loop, _waiter, _addr = loop.run_until_complete(fut)

    url = '{}://{}:{}'.format(
        'https' if use_ssl else 'http', *_addr)

    yield url
    _thread_loop.call_soon_threadsafe(_waiter.set_result, None)
    srv_thread.join()

Example 20

Project: colorcore
License: View license
Source File: routing.py
    def create_response(self, status, message):
        response = aiohttp.Response(self.writer, status, http_version=message.version)
        response.add_header('Content-Type', 'text/json')
        return response

Example 21

Project: xcat
License: View license
Source File: http.py
    def handle_request(self, message, payload):
        headers = email.message.Message()
        for hdr, val in message.headers.items():
            headers.add_header(hdr, val)

        response = aiohttp.Response(
            self.writer, 200, http_version=message.version
        )
        response.add_header('Transfer-Encoding', 'chunked')

        accept_encoding = headers.get('accept-encoding', '').lower()

        if 'deflate' in accept_encoding:
            response.add_header('Content-Encoding', 'deflate')
            response.add_compression_filter('deflate')

        elif 'gzip' in accept_encoding:
            response.add_header('Content-Encoding', 'gzip')
            response.add_compression_filter('gzip')

        response.add_chunking_filter(1025)
        response.add_header('Content-type', 'text/xml')

        response.send_headers()
        parsed = parse.urlparse(message.path)
        parsed_data = parse.parse_qs(parsed.query)

        if message.path.startswith("/entity/"):
            file_id = message.path.replace("/entity/", "")
            use_comment = False
            if file_id == "test":
                entity_value = '"{}"'.format(self.TEST_RESPONSE)
            elif self.server.expecting_identifier(file_id):
                use_comment, value = self.server.get_entity_value(file_id)
                entity_value = 'SYSTEM "{}"'.format(value)
            else:
                return response.force_close()

            data_value = "&c;"
            if use_comment:
                data_value = "<!-- {} -->".format(data_value)

            response.write(bytes("""<!DOCTYPE stuff [
             <!ELEMENT data ANY>
             <!ENTITY c {}>
             ]>
             <data>{}</data>""".format(entity_value, data_value), "utf-8"))
        elif message.path == "/test":
            response.write(bytes("<test>{}</test>".format(self.TEST_RESPONSE), "utf8"))
        else:
            identifier = parsed.path.lstrip("/")
            if not self.server.expecting_identifier(identifier):
                return response.force_close()
            if "d" not in parsed_data:
                parsed_data["d"] = []

            self.server.got_data(identifier, parsed_data)

            response.write(bytes("<test>{}</test>".format(identifier), "utf-8"))
        #else:
        #    response.write(bytes("Begone!"))

        yield from response.write_eof()
        if response.keep_alive():
            self.keep_alive(True)