예제 #1
0
    async def send(self) -> str:
        async with aiohttp.ClientSession() as client_session:
            async with client_session.post(self.backend, data=self.request) as response:
                if response.status != 200:
                    raise aiohttp.HttpProcessingError(response.status)

                data = await response.read()
                data = data.decode("utf-8")
                return data.replace(data[:16], "")  # remove token
예제 #2
0
def get_flag(base_url, cc):
    url = '{}/{cc}/{cc}.gif'.format(base_url, cc=cc.lower())
    resp = yield from aiohttp.request('GET', url)
    if resp.status == 200:
        image = yield from resp.read()
        return image
    elif resp.status == 404:
        raise web.HTTPNotFound()
    else:
        raise aiohttp.HttpProcessingError(code=resp.status, message=resp.reason, headers=resp.headers)
예제 #3
0
async def get_flag(session, base_url, cc):  # <2>
    url = '{}/{cc}/{cc}.gif'.format(base_url, cc=cc.lower())
    async with session.get(url) as resp:
        if resp.status == 200:
            return await resp.read()
        elif resp.status == 404:
            raise web.HTTPNotFound()
        else:
            raise aiohttp.HttpProcessingError(
                code=resp.status, message=resp.reason,
                headers=resp.headers)
예제 #4
0
async def download():
    filename = pathlib.Path(unidata.URL).name
    spinner = asyncio.ensure_future(spin('downloading ' + filename))
    async with aiohttp.request('GET', unidata.URL) as resp:
        if resp.status != 200:
            raise aiohttp.HttpProcessingError(
                code=resp.status, message=resp.reason,
                headers=resp.headers)
        with open(filename, 'wb') as fd:
            fd.write(await resp.read())
    spinner.cancel()
예제 #5
0
def get_flag(base_url, cc: str):
    url = '{}/{cc}/{cc}.gif'.format(base_url, cc=cc.lower())
    resp = yield from aiohttp.ClientSession().get(url)
    if resp.status == 200:
        image = yield from resp.read()
    elif resp.status == 404:
        raise web.HTTPNotFound()
    else:
        raise aiohttp.HttpProcessingError(code=resp.status,
                                          message=resp.reason,
                                          headers=resp.headers)
async def get_flag(session, base_url, cc):
    url = '{}/{cc}/{cc}.gif'.format(base_url, cc=cc.lower())
    async with session.get(url) as resp:
        if resp.status == 200:
            return await resp.read()
            # 真正执行I/O操作的是最内层的普通的子生成器(通过yield from结构委托给asyncio包或第三方库中的协程)
        elif resp.status == 404:
            raise web.HTTPNotFound()
        else:
            raise aiohttp.HttpProcessingError(code=resp.status,
                                              message=resp.reason,
                                              header=resp.headers)
예제 #7
0
def get_flag(base_url, cc):                     # ➋ get_flag 协程有三种返回结果:返回下载得到的图像;HTTP 响应码为404 时,抛出web.HTTPNotFound 异常;返回其他HTTP 状态码时,抛出aiohttp.HttpProcessingError异常。
    url = '{}/{cc}/{cc}.gif'.format(base_url, cc=cc.lower())
    resp = yield from aiohttp.request('GET', url)
    if resp.status == 200:
        image = yield from resp.read()
        return image
    elif resp.status == 404:
        raise web.HTTPNotFound()
    else:
        raise aiohttp.HttpProcessingError(
            code=resp.status, message=resp.reason,
            headers=resp.headers)
예제 #8
0
async def get_flag(base_url, cc):  # <2>
    url = '{}/{cc}/{cc}.gif'.format(base_url, cc=cc.lower())
    with closing(await aiohttp.request('GET', url)) as resp:
        if resp.status == 200:
            image = await resp.read()
            return image
        elif resp.status == 404:
            raise web.HTTPNotFound()
        else:
            raise aiohttp.HttpProcessingError(code=resp.status,
                                              message=resp.reason,
                                              headers=resp.headers)
예제 #9
0
async def get_flag(cc):
    url = '{}/{cc}/{cc}.gif'.format(BASE_URL, cc=cc.lower())
    resp = await aiohttp.request('GET', url)
    if resp.status == 200:
        image = await resp.read()
        return (image)
    elif resp.status == 404:
        raise web.HTTPNotFound()
    else:
        raise aiohttp.HttpProcessingError(code=resp.status,
                                          message=resp.reason,
                                          header=resp.headers)
def get_flag(cc):
    url='{}/{cc}/{cc}.gif'.format(BASE_URL,cc=cc.lower())
    print("request {}".format(cc))
    resp=yield from aiohttp.request('GET',url)
    if resp.status == 200:
        image=yield from resp.read()
        return image
    elif resp.status == 404:
        raise
    else:
        raise aiohttp.HttpProcessingError(code=resp.status,message=resp.reason,
                                          headers=resp.headers)
예제 #11
0
async def get_flag(base_url, cc):
    url = '{}/{cc}/{cc}.gif'.format(base_url, cc=cc.lower())
    async with aiohttp.ClientSession() as sess:
        resp = await sess.request('GET', url)
        if resp.status == 200:
            image = await resp.content.read()
            return image
        elif resp.status == 404:
            raise web.HTTPNotFound()
        else:
            raise aiohttp.HttpProcessingError(code=resp.status,
                                              message=resp.reason,
                                              headers=resp.headers)
예제 #12
0
def get_flag(base_url, cc):  # <2>
    url = '{}/{cc}/{cc}.gif'.format(base_url, cc=cc.lower())
    resp = yield from aiohttp.ClientSession().get(url)
    with contextlib.closing(resp):
        if resp.status == 200:
            image = yield from resp.read()
            return image
        elif resp.status == 404:
            raise web.HTTPNotFound()
        else:
            raise aiohttp.HttpProcessingError(code=resp.status,
                                              message=resp.reason,
                                              headers=resp.headers)
예제 #13
0
async def get_flag(base_url, cc):  # <2>
    url = '{}/{cc}/{cc}.gif'.format(base_url, cc=cc.lower())
    async with aiohttp.ClientSession() as session:
        with async_timeout.timeout(10):
            async with session.get(url) as resp:
                if resp.status == 200:
                    image = await resp.read()  # <5>
                    return image
                elif resp.status == 404:
                    raise web.HTTPNotFound()
                else:
                    raise aiohttp.HttpProcessingError(code=resp.status,
                                                      message=resp.reason,
                                                      headers=resp.headers)
예제 #14
0
async def download(url):
    """Download file from URL, with activity feedback."""
    spinner = asyncio.ensure_future(spin('downloading'))

    resp = await aiohttp.request('GET', url)
    async with resp:
        if resp.status != 200:
            raise aiohttp.HttpProcessingError(code=resp.status,
                                              message=resp.reason,
                                              headers=resp.headers)

        text = await resp.text()

    spinner.cancel()
    return text
예제 #15
0
def get_flag(base_url, cc):
    """
    get_flag関数はダウンロードした画像のバイト列を返します。
    HTTPステータスコードが404ならweb.HTTPNotFoundを、
    それ以外のコードならaiohttp.HttpProcessingErrorをそれぞれ上げます。
    """
    url = '{}/{cc}/{cc}.gif'.format(BASE_URL, cc=cc.lower())
    resp = yield from aiohttp.request('GET', url)
    if resp.status == 200:
        image = yield from resp.read()
        return image
    elif resp.status == 404:
        raise web.HTTPNotFound()
    else:
        raise aiohttp.HttpProcessingError(code=resp.status,
                                          message=resp.reason,
                                          headers=resp.headers)
예제 #16
0
async def GetFlag(flag):
    """
    下载单面旗帜
    :param flag: 旗帜缩写名
    :return: 旗帜的数据
    """
    downloadUrl = "{base}/{flag}/{flag}.gif".format(base=BASE_URL,
                                                    flag=flag.lower())
    # response = yield from aiohttp.request("GET", downloadUrl)         # 使用aiohttp.request会出现异常
    response = await aiohttp.ClientSession().get(downloadUrl)  # 将阻塞的操作交由协程完成
    if response.status == 200:
        image = await response.read()  # 读取响应也是异步操作
        return image
    elif response.status == 404:
        raise web.HTTPNotFound
    else:
        raise aiohttp.HttpProcessingError(code=response.status,
                                          message=response.reason,
                                          headers=response.headers)
예제 #17
0
    def _request(self, method, url, *args, allow_403=False, **kwargs):
        resp = yield from super()._request(method, url, *args, **kwargs)

        # Check if Cloudflare anti-bot is on
        if resp.status == 503 and resp.headers.get(
                "Server") == "cloudflare-nginx":
            return (yield from self.solve_cf_challenge(resp, **kwargs))

        elif resp.status == 403 and resp.headers.get(
                "Server") == "cloudflare-nginx" and not allow_403:
            resp.close()
            raise aiohttp.HttpProcessingError(
                message=
                'CloudFlare returned HTTP 403. Your IP could be banned on CF '
                'or reCAPTCHA appeared. This error can be disabled with '
                'allow_403=True flag in request parameters e.g. '
                'session.get(url, allow_403=True).',
                headers=resp.headers)

        # Otherwise, no Cloudflare anti-bot detected
        return resp
예제 #18
0
 def raise_for_status(self):
     if 400 <= self.status:
         raise aiohttp.HttpProcessingError(code=self.status,
                                           message=self.reason)
예제 #19
0
 def function1755(self, arg1685, arg2326):
     print('method = {!r}; path = {!r}; version = {!r}'.format(
         arg1685.method, arg1685.var4483, arg1685.version))
     var4483 = arg1685.var4483
     if ((not (var4483.isprintable() and var4483.startswith('/')))
             or ('/.' in var4483)):
         print('bad path', repr(var4483))
         var4483 = None
     else:
         var4483 = ('.' + var4483)
         if (not os.var4483.exists(var4483)):
             print('no file', repr(var4483))
             var4483 = None
         else:
             var3608 = os.var4483.var3608(var4483)
     if (not var4483):
         raise aiohttp.HttpProcessingError(code=404)
     for (var4700, var345) in arg1685.headers.items():
         print(var4700, var345)
     if (isdir and (not var4483.endswith('/'))):
         var4483 = (var4483 + '/')
         raise aiohttp.HttpProcessingError(code=302,
                                           headers=(('URI', var4483),
                                                    ('Location', var4483)))
     var1054 = aiohttp.Response(self.writer,
                                200,
                                http_version=arg1685.version)
     var1054.add_header('Transfer-Encoding', 'chunked')
     var220 = arg1685.headers.get('accept-encoding', '').lower()
     if ('deflate' in var220):
         var1054.add_header('Content-Encoding', 'deflate')
         var1054.add_compression_filter('deflate')
     elif ('gzip' in var220):
         var1054.add_header('Content-Encoding', 'gzip')
         var1054.add_compression_filter('gzip')
     var1054.add_chunking_filter(1025)
     if var3608:
         var1054.add_header('Content-type', 'text/html')
         var1054.send_headers()
         var1054.write(b'<ul>\r\n')
         for var1442 in sorted(os.listdir(var4483)):
             if (var1442.isprintable() and (not var1442.startswith('.'))):
                 try:
                     var4746 = var1442.encode('ascii')
                 except UnicodeError:
                     pass
                 else:
                     if os.var4483.var3608(os.var4483.join(
                             var4483, var1442)):
                         var1054.write(
                             ((((b'<li><a href="' + var4746) + b'/">') +
                               var4746) + b'/</a></li>\r\n'))
                     else:
                         var1054.write(
                             ((((b'<li><a href="' + var4746) + b'">') +
                               var4746) + b'</a></li>\r\n'))
         var1054.write(b'</ul>')
     else:
         var1054.add_header('Content-type', 'text/plain')
         var1054.send_headers()
         try:
             with open(var4483, 'rb') as var4024:
                 var3166 = var4024.read(8192)
                 while chunk:
                     var1054.write(var3166)
                     var3166 = var4024.read(8192)
         except OSError:
             var1054.write(b'Cannot open')
     yield from var1054.write_eof()
     if var1054.keep_alive():
         self.keep_alive(True)
예제 #20
0
    def handle_request(self, message, payload):
        print('method = {!r}; path = {!r}; version = {!r}'.format(
            message.method, message.path, message.version))

        path = message.path

        if (not (path.isprintable() and path.startswith('/')) or '/.' in path):
            print('bad path', repr(path))
            path = None
        else:
            path = '.' + path
            if not os.path.exists(path):
                print('no file', repr(path))
                path = None
            else:
                isdir = os.path.isdir(path)

        if not path:
            raise aiohttp.HttpProcessingError(code=404)

        for hdr, val in message.headers.items():
            print(hdr, val)

        if isdir and not path.endswith('/'):
            path = path + '/'
            raise aiohttp.HttpProcessingError(code=302,
                                              headers=(('URI', path),
                                                       ('Location', path)))

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

        # content encoding
        accept_encoding = message.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)

        if isdir:
            response.add_header('Content-type', 'text/html')
            response.send_headers()

            response.write(b'<ul>\r\n')
            for name in sorted(os.listdir(path)):
                if name.isprintable() and not name.startswith('.'):
                    try:
                        bname = name.encode('ascii')
                    except UnicodeError:
                        pass
                    else:
                        if os.path.isdir(os.path.join(path, name)):
                            response.write(b'<li><a href="' + bname + b'/">' +
                                           bname + b'/</a></li>\r\n')
                        else:
                            response.write(b'<li><a href="' + bname + b'">' +
                                           bname + b'</a></li>\r\n')
            response.write(b'</ul>')
        else:
            response.add_header('Content-type', 'text/plain')
            response.send_headers()

            try:
                with open(path, 'rb') as fp:
                    chunk = fp.read(8192)
                    while chunk:
                        response.write(chunk)
                        chunk = fp.read(8192)
            except OSError:
                response.write(b'Cannot open')

        yield from response.write_eof()
        if response.keep_alive():
            self.keep_alive(True)
예제 #21
0
 def f(request):
     raise aiohttp.HttpProcessingError(code=401,
                                       headers=(('WWW-Authenticate',
                                                 'Basic'), ))
예제 #22
0
    async def handle_request(self, message, payload):
        print(
            "method = {!r}; path = {!r}; version = {!r}".format(
                message.method, message.path, message.version
            )
        )

        path = message.path

        if not (path.isprintable() and path.startswith("/")) or "/." in path:
            print("bad path", repr(path))
            path = None
        else:
            path = "." + path
            if not os.path.exists(path):
                print("no file", repr(path))
                path = None
            else:
                isdir = os.path.isdir(path)

        if not path:
            raise aiohttp.HttpProcessingError(code=404)

        for hdr, val in message.headers.items():
            print(hdr, val)

        if isdir and not path.endswith("/"):
            path = path + "/"
            raise aiohttp.HttpProcessingError(
                code=302, headers=(("URI", path), ("Location", path))
            )

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

        # content encoding
        accept_encoding = message.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)

        if isdir:
            response.add_header("Content-type", "text/html")
            response.send_headers()

            response.write(b"<ul>\r\n")
            for name in sorted(os.listdir(path)):
                if name.isprintable() and not name.startswith("."):
                    try:
                        bname = name.encode("ascii")
                    except UnicodeError:
                        pass
                    else:
                        if os.path.isdir(os.path.join(path, name)):
                            response.write(
                                b'<li><a href="'
                                + bname
                                + b'/">'
                                + bname
                                + b"/</a></li>\r\n"
                            )
                        else:
                            response.write(
                                b'<li><a href="'
                                + bname
                                + b'">'
                                + bname
                                + b"</a></li>\r\n"
                            )
            response.write(b"</ul>")
        else:
            response.add_header("Content-type", "text/plain")
            response.send_headers()

            try:
                with open(path, "rb") as fp:
                    chunk = fp.read(8192)
                    while chunk:
                        response.write(chunk)
                        chunk = fp.read(8192)
            except OSError:
                response.write(b"Cannot open")

        await response.write_eof()
        if response.keep_alive():
            self.keep_alive(True)