def go():
            nonlocal auth_err

            app, _, url = yield from self.create_server('POST', '/')
            app.router.add_route(
                'POST', '/', handler, expect_handler=expect_handler)

            form = FormData()
            form.add_field('name', b'123',
                           content_transfer_encoding='base64')

            resp = yield from request(
                'post', url, data=form,
                expect100=True,  # wait until server returns 100 continue
                loop=self.loop)

            self.assertEqual(200, resp.status)
            resp.close(force=True)

            auth_err = True
            resp = yield from request(
                'post', url, data=form,
                expect100=True,  # wait until server returns 100 continue
                loop=self.loop)
            self.assertEqual(403, resp.status)
            resp.close(force=True)
Exemple #2
0
async def call(method, file=None, **kwargs):
    """
    Perform an API call to Slack.

    :param file: File pointer
    :type file: file

    :Keyword Arguments:
        All the arguments required by the Slack API.

    :return: JSON response.
    :rtype: dict
    """
    # JSON encode any sub-structure...
    for k, w in kwargs.items():
        # list, tuple or dict but not a str.
        if isinstance(w, (Mapping, list, tuple)):
            kwargs[k] = json.dumps(w)

    form = FormData(kwargs)

    # Handle file upload
    if file:
        form.add_field('file', file)

    with ClientSession() as session:
        async with session.post('https://slack.com/api/{0}'.format(method),
                                data=form) as response:
            assert 200 == response.status, response
            return await response.json()
async def test_100_continue_custom(aiohttp_client):

    expect_received = False

    async def handler(request):
        data = await request.post()
        assert b'123' == data['name']
        return web.Response()

    async def expect_handler(request):
        nonlocal expect_received
        expect_received = True
        if request.version == HttpVersion11:
            request.transport.write(b"HTTP/1.1 100 Continue\r\n\r\n")

    form = FormData()
    form.add_field('name', b'123',
                   content_transfer_encoding='base64')

    app = web.Application()
    app.router.add_post('/', handler, expect_handler=expect_handler)
    client = await aiohttp_client(app)

    resp = await client.post('/', data=form, expect100=True)
    assert 200 == resp.status
    assert expect_received
def test_files_upload_with_same_key(loop, test_client):
    @asyncio.coroutine
    def handler(request):
        data = yield from request.post()
        files = data.getall('file')
        file_names = set()
        for _file in files:
            assert not _file.file.closed
            if _file.filename == 'test1.jpeg':
                assert _file.file.read() == b'binary data 1'
            if _file.filename == 'test2.jpeg':
                assert _file.file.read() == b'binary data 2'
            file_names.add(_file.filename)
        assert len(files) == 2
        assert file_names == {'test1.jpeg', 'test2.jpeg'}
        resp = web.Response(body=b'OK')
        return resp

    app = web.Application(loop=loop)
    app.router.add_post('/', handler)
    client = yield from test_client(app)

    data = FormData()
    data.add_field('file', b'binary data 1',
                   content_type='image/jpeg',
                   filename='test1.jpeg')
    data.add_field('file', b'binary data 2',
                   content_type='image/jpeg',
                   filename='test2.jpeg')
    resp = yield from client.post('/', data=data)
    assert 200 == resp.status
def test_100_continue_custom_response(loop, test_client):

    @asyncio.coroutine
    def handler(request):
        data = yield from request.post()
        assert b'123', data['name']
        return web.Response()

    @asyncio.coroutine
    def expect_handler(request):
        if request.version == HttpVersion11:
            if auth_err:
                return web.HTTPForbidden()

            request.transport.write(b"HTTP/1.1 100 Continue\r\n\r\n")

    form = FormData()
    form.add_field('name', b'123',
                   content_transfer_encoding='base64')

    app = web.Application(loop=loop)
    app.router.add_post('/', handler, expect_handler=expect_handler)
    client = yield from test_client(app)

    auth_err = False
    resp = yield from client.post('/', data=form, expect100=True)
    assert 200 == resp.status

    auth_err = True
    resp = yield from client.post('/', data=form, expect100=True)
    assert 403 == resp.status
 def go():
     _, _, url = yield from self.create_server("POST", "/", handler)
     _data = FormData()
     _data.add_field("file", b"binary data 1", content_type="image/jpeg", filename="test1.jpeg")
     _data.add_field("file", b"binary data 2", content_type="image/jpeg", filename="test2.jpeg")
     resp = yield from request("POST", url, data=_data, loop=self.loop)
     self.assertEqual(200, resp.status)
     resp.close()
        def go():
            _, _, url = yield from self.create_server("POST", "/", handler)

            form = FormData()
            form.add_field("name", b"123", content_transfer_encoding="base64")

            resp = yield from request("post", url, data=form, loop=self.loop)

            self.assertEqual(200, resp.status)
            resp.close()
Exemple #8
0
        def go():
            _, _, url = yield from self.create_server('POST', '/', handler)

            form = FormData()
            form.add_field('name', b'123',
                           content_transfer_encoding='base64')

            resp = yield from request(
                'post', url, data=form,
                loop=self.loop)

            self.assertEqual(200, resp.status)
 def go():
     _, _, url = yield from self.create_server('POST', '/', handler)
     _data = FormData()
     _data.add_field('file', b'binary data 1',
                     content_type='image/jpeg',
                     filename='test1.jpeg')
     _data.add_field('file', b'binary data 2',
                     content_type='image/jpeg',
                     filename='test2.jpeg')
     resp = yield from request('POST', url, data=_data,
                               loop=self.loop)
     self.assertEqual(200, resp.status)
     resp.close()
        def go():
            app, _, url = yield from self.create_server("POST", "/")
            app.router.add_route("POST", "/", handler)

            form = FormData()
            form.add_field("name", b"123", content_transfer_encoding="base64")

            resp = yield from request(
                "GET", url, data=form, expect100=True, loop=self.loop  # wait until server returns 100 continue
            )

            self.assertEqual(405, resp.status)
            resp.close()
        def go():
            _, _, url = yield from self.create_server('POST', '/', handler)

            form = FormData()
            form.add_field('name', b'123',
                           content_transfer_encoding='base64')

            resp = yield from request(
                'post', url, data=form,
                expect100=True,  # wait until server returns 100 continue
                loop=self.loop)

            self.assertEqual(200, resp.status)
            resp.close()
def test_100_continue(loop, test_client):
    @asyncio.coroutine
    def handler(request):
        data = yield from request.post()
        assert b'123' == data['name']
        return web.Response()

    form = FormData()
    form.add_field('name', b'123',
                   content_transfer_encoding='base64')

    app = web.Application(loop=loop)
    app.router.add_post('/', handler)
    client = yield from test_client(app)

    resp = yield from client.post('/', data=form, expect100=True)
    assert 200 == resp.status
async def test_POST_DATA_with_content_transfer_encoding(loop, test_client):

    async def handler(request):
        data = await request.post()
        assert b'123' == data['name']
        return web.Response()

    app = web.Application()
    app.router.add_post('/', handler)
    client = await test_client(app)

    form = FormData()
    form.add_field('name', b'123',
                   content_transfer_encoding='base64')

    resp = await client.post('/', data=form)
    assert 200 == resp.status
Exemple #14
0
async def test_100_continue(aiohttp_client):

    async def handler(request):
        data = await request.post()
        assert b'123' == data['name']
        return web.Response()

    form = FormData()
    form.add_field('name', b'123',
                   content_transfer_encoding='base64')

    app = web.Application()
    app.router.add_post('/', handler)
    client = await aiohttp_client(app)

    resp = await client.post('/', data=form, expect100=True)
    assert 200 == resp.status
    async def test_request_with_form_data(self):
        debug_app = self.make_debug_app()
        async with TestServer(debug_app) as server:
            url = str(server.make_url("/"))
            app = self.make_app_with_response(target=url)
            payload = FormData([
                ("field1", "value1"),
                ("field1", "value2"),
                ("field2", "null"),
            ])
            payload._is_multipart = True

            async with run(app) as client:
                response = await client.request(POST, "/", data=payload)
                body = await response.json()
                self.assertEqual(body["method"], POST)
                self.assertEqual(body["form"], {
                    "field1": ["value1", "value2"],
                    "field2": ["null"],
                })
    async def test_request_with_file(self):
        debug_app = self.make_debug_app()
        async with TestServer(debug_app) as server:
            url = str(server.make_url("/"))
            app = self.make_app_with_response(target=url)
            payload = FormData()
            payload.add_field("field1", "value1")
            payload.add_field("field2", b"binary", content_type="image/jpeg", filename="image.jpg")

            async with run(app) as client:
                response = await client.request(POST, "/", data=payload)
                body = await response.json()
                self.assertEqual(body["method"], POST)
                self.assertEqual(body["form"], {
                    "field1": ["value1"],
                    "field2": [{
                        "name": "image.jpg",
                        "size": str(len(b"binary")),
                        "type": "image/jpeg",
                    }],
                })
        def go():
            nonlocal expect_received

            app, _, url = yield from self.create_server('POST', '/')
            app.router.add_route('POST',
                                 '/',
                                 handler,
                                 expect_handler=expect_handler)

            form = FormData()
            form.add_field('name', b'123', content_transfer_encoding='base64')

            resp = yield from request(
                'post',
                url,
                data=form,
                expect100=True,  # wait until server returns 100 continue
                loop=self.loop)

            self.assertEqual(200, resp.status)
            self.assertTrue(expect_received)
            resp.close()
Exemple #18
0
 async def on_guild_post(self):
     bot = self.sonata
     guild_count = len(bot.guilds)
     data = FormData({
         "servers": str(guild_count),
         "shards": str(bot.shard_count or 1)
     })
     await bot.session.post(
         f"https://api.server-discord.com/v2/bots/{bot.user.id}/stats",
         headers={"Authorization": "SDC " + bot.config["bot"].sdc_token},
         data=data,
     )
     bot.logger.info("Server count posted successfully")
Exemple #19
0
 def _prepare_data(request: Request) -> Optional[Union[Data, FormData]]:
     if request.data is not None:
         return request.data
     if request.files is not None:
         data = FormData()
         for name, value in request.files.items():
             filename, content_type = None, None
             if isinstance(value, tuple):
                 if len(value) == 2:
                     filename, content = value  # type: ignore
                 else:
                     filename, content, content_type = value  # type: ignore
             else:
                 content = value
             data.add_field(
                 name,
                 content,
                 filename=filename,
                 content_type=content_type,
             )
         return data
     return None
Exemple #20
0
async def async_send_request(url, filename):
    headers = {
        "X-Requested-With": "XMLHttpRequest",
        "Accept": "application/json",
        "Authorization": "Bearer " + access_token
    }

    data = FormData()
    data.add_field('file',
                   open(filename, 'rb'),
                   filename=filename,
                   content_type='application/vnd.ms-excel')

    async with aiohttp.ClientSession() as session:
        async with session.post(url, data=data, headers=headers) as response:
            data = {
                "message": "failed"
            }
            if response.status == 200:
                data = await response.json()

            print(await response.json())
Exemple #21
0
async def test_upload_image_too_small(cli, url, factory: Factory, login):
    await factory.create_company()
    await factory.create_user()
    await factory.create_cat()
    await login()
    data = FormData()
    data.add_field('image',
                   create_image(200, 100),
                   filename='testing.png',
                   content_type='application/octet-stream')
    r = await cli.post(url('categories-add-image', cat_id=factory.category_id),
                       data=data,
                       headers={
                           'Referer':
                           f'http://127.0.0.1:{cli.server.port}/foobar/',
                           'Origin': f'http://127.0.0.1:{cli.server.port}',
                       })
    assert r.status == 400, await r.text()
    data = await r.json()
    assert data == {
        'message': 'image too small: 200x100 < 1920x500',
    }
Exemple #22
0
    async def upload_cover(self, group_id, cover_img, width=1590, height=400):
        try:
            params = {
                "group_id": group_id,
                "crop_x": 0,
                "crop_y": 0,
                "crop_x2": width,
                "crop_y2": height
            }
            upload_url = await self.get_response(
                'photos.getOwnerCoverPhotoUploadServer', params)

            data = FormData()
            data.add_field('photo',
                           io.BytesIO(cover_img),
                           filename='photo.jpg',
                           content_type='image/png')

            uploaded_data = await req.post(upload_url["upload_url"],
                                           data=data,
                                           timeout=60)
            uploaded_data = json.loads(uploaded_data.decode('utf-8'))

            params = {
                "hash": uploaded_data["hash"],
                "photo": uploaded_data["photo"],
                'v': '5.103',
                'access_token': self.token
            }

            upload_result = await req.get(self.url +
                                          'photos.saveOwnerCoverPhoto',
                                          params=params)

            return upload_result.decode('utf-8')

        except:
            logs()
            return False
Exemple #23
0
    async def track_error(track_id: str) -> str:
        try:
            data = load_error(track_id)
        except ReadFileError:
            return "请检查ID是否正确..."

        prompt = data.get("prompt", "ignore")
        time = data.get("time", "ignore")
        content = data.get("content", "ignore")

        msg0 = TRACK_BACK_FORMAT.format(track_id=track_id,
                                        prompt=prompt,
                                        time=time,
                                        content=content)
        f_data = FormData()
        f_data.add_field("poster", "ATRI running log")
        f_data.add_field("syntax", "text")
        f_data.add_field("expiration", "day")
        f_data.add_field("content", msg0)

        repo = f"详细请移步此处~\n{await UbuntuPaste(f_data).paste()}"
        return repo
Exemple #24
0
 async def test_validate_model_form(self, server):
     url = f"http://127.0.0.1:{server.port}/component/form_model"
     async with ClientSession(conn_timeout=10, read_timeout=10) as session:
         data = FormData()
         data.add_field("a", "11")
         data.add_field("b", 2)
         resp = await session.post(url, data=data)
         assert await resp.json() == {"a": "11", "b": 2, "c": "test"}
Exemple #25
0
async def publish_models(request):
    PATH = '/models'
    async with request.app['db'].acquire() as conn:
        service_config = await get_service_config_by_action(conn=conn,
                                                            action='publish',
                                                            media_type='model')
    logging.debug(msg='service_config: {}'.format(str(service_config)))
    service_name = service_config.get('name')

    if request.method == 'POST':
        try:
            q = request.query
            did = q.get('deposit_id')
            metadata = await request.json()
            data = {}
            data.update({'metadata': metadata})
            fd = FormData()
            fd.add_field('data',
                         json.dumps(data),
                         content_type='application/json')
            async with request.app['db'].acquire() as conn:
                service_config = await db.get_service_config(conn=conn,
                                                             name=service_name)
                if service_config:
                    endpoint = service_config.get('endpoint')
                    config = service_config.get('config')
                    fd.add_field('config',
                                 json.dumps(config),
                                 content_type='application/json')
                    with open('./data/{}'.format(did), 'rb') as f:
                        fd.add_field('file',
                                     f,
                                     filename=did,
                                     content_type='application/octet-stream')
                        async with new_request(method='POST',
                                               url=endpoint + PATH,
                                               data=fd) as resp:
                            resp_json = await resp.json()
                            uri = resp_json.get('uri')
                            return web.json_response(uri)
                else:
                    return web.json_response({
                        'err':
                        'could not retrieve config for service: {}'.format(
                            service_name)
                    })
        except Exception as err:
            return web.json_response({'err': str(err)})
Exemple #26
0
 async def prove(self):
     await self.get_url()
     if self.base_url:
         async with ClientSession() as session:
             for path in self.url_normpath(self.url, './'):
                 url = path + "kindeditor/php/upload_json.php?dir=file"
                 data = FormData()
                 data.add_field('imgFile',
                                "this is a test for you. ",
                                filename='mytestforyou.html',
                                content_type='text/plain')
                 async with session.post(url=url, data=data) as res:
                     if res != None:
                         text = await res.text()
                         try:
                             res = json.loads(text)
                             if 'url' in res.keys(
                             ) and 'kindeditor' in res['url']:
                                 self.flag = 1
                                 self.req.append({"url": url})
                                 self.res.append({"info": url, "key": url})
                         except:
                             pass
Exemple #27
0
    async def upload_file_worker(self, file, ts):
        filename, content = self.files.pop(file)
        async with ClientSession() as session:
            form = FormData()
            form.add_field('file', content, filename=filename)

            response = await session.post('https://slack.com/api/files.upload',
                                          data=form,
                                          params={
                                              'channels': self.slack_channel,
                                              'thread_ts': ts,
                                          },
                                          headers={
                                              'Authorization':
                                              f'Bearer {self.slack_token}',
                                          })

            response = await response.json()
            print(response)
            if not response['ok']:
                return response

            return {'ok': True}
Exemple #28
0
async def test_upload_logo_too_small(cli, url, factory: Factory, db_conn,
                                     login, dummy_server):
    await factory.create_company()
    await factory.create_user()
    await login()
    assert None is await db_conn.fetchval('SELECT logo FROM companies')
    data = FormData()
    data.add_field('image',
                   create_image(100, 300),
                   filename='testing.png',
                   content_type='application/octet-stream')
    r = await cli.post(url('company-upload', field='logo'),
                       data=data,
                       headers={
                           'Referer':
                           f'http://127.0.0.1:{cli.server.port}/foobar/',
                           'Origin': f'http://127.0.0.1:{cli.server.port}',
                       })
    assert r.status == 400, await r.text()
    data = await r.json()
    assert data == {'message': 'image too small: 100x300 < 256x256'}
    assert dummy_server.app['images'] == []
    assert None is await db_conn.fetchval('SELECT logo FROM companies')
Exemple #29
0
        async def form_all_data():
            """Forms both image and json data for the uploading"""

            data = FormData()
            for key, item in json_data.items():
                data.add_field(name=key, value=item, content_type="application/json")
            for key, item in files.items():
                data.add_field(name=key, value=item[1], filename=item[0], content_type="multipart/form-data")
            return data
Exemple #30
0
async def test_add_image_delete_old(cli, url, factory: Factory, db_conn, login,
                                    dummy_server):
    await factory.create_company()
    await factory.create_cat()
    await factory.create_user()
    await factory.create_donation_option()
    await login()
    await db_conn.execute("UPDATE donation_options SET image='testing'")
    data = FormData()
    data.add_field('image',
                   create_image(700, 500),
                   filename='testing.png',
                   content_type='application/octet-stream')
    r = await cli.post(url('donation-image-upload',
                           pk=factory.donation_option_id),
                       data=data,
                       headers={
                           'Referer':
                           f'http://127.0.0.1:{cli.server.port}/foobar/',
                           'Origin': f'http://127.0.0.1:{cli.server.port}',
                       })
    assert r.status == 200, await r.text()
    assert sum('DELETE aws_endpoint_url/' in e
               for e in dummy_server.app['log']) == 2
Exemple #31
0
def function663(arg1801, arg549):
    var1478 = False

    @asyncio.coroutine
    def function146(arg675):
        var2387 = yield from arg675.post()
        assert (b'123' == var2387['name'])
        return web.Response()

    @asyncio.coroutine
    def function2702(arg602):
        nonlocal expect_received
        var1478 = True
        if (arg602.version == HttpVersion11):
            arg602.transport.write(b'HTTP/1.1 100 Continue\r\n\r\n')

    var3611 = FormData()
    var3611.add_field('name', b'123', content_transfer_encoding='base64')
    var992 = web.Application()
    var992.router.add_post('/', function146, expect_handler=function2702)
    var776 = yield from arg549(var992)
    var4637 = yield from var776.post('/', data=var3611, expect100=True)
    assert (200 == var4637.status)
    assert expect_received
Exemple #32
0
    async def upload_from_file(
        self,
        filename,
        title="",
        tags=None,
        keep_audio=True,
        check_duplicate=False,
        check_upload=True,
    ):
        tags = tags or []

        key = await self._get_key(title, tags, keep_audio, check_duplicate)

        data = FormData()
        data.add_field("key", key)

        with open(filename, "rb") as file:
            data.add_field("file", file, filename=filename)

            await self._http.request(CustomRoute("POST", FILEDROP_ENDPOINT),
                                     data=data,
                                     no_auth=True)

        if check_upload:
            status = await self._check_upload_status(key)

            num_checks = 0
            while status["task"] != "complete":
                if num_checks > self.MAX_CHECKS:
                    # the gfycat was likely uploaded correctly, but gfycat is not sending 'task': 'complete'
                    break
                status = await self._check_upload_status(key)
                num_checks += 1
                await asyncio.sleep(3)

            try:
                gfy = await self.get_gfycat(key)

                logger.info("\n%s has been uploaded as %s/%s.", filename,
                            GFYCAT_URL, key)
                return gfy
            except GfypyApiException:
                logger.info(
                    "\n%s has probably been uploaded as %s/%s, but the check was unsuccessful.",
                    filename,
                    GFYCAT_URL,
                    key,
                )
                return None
        else:
            logger.info(
                "\n%s has been uploaded as %s/%s; checks have been skipped.",
                filename,
                GFYCAT_URL,
                key,
            )
 async def test_save_file_on_upload(self, test_conf, aiohttp_client,
                                    event_loop, create_user, setup_db):
     app = await create_app(config=test_conf)
     client = await aiohttp_client(app)
     data = FormData()
     data.add_field("configuration",
                    io.StringIO("test content"),
                    filename="test.conf")
     r = await client.get(
         "api/v1/configurations/",
         headers={"Authorization": f"Token {create_user['api_key']}"},
     )
     start_configurations = await r.json()
     await client.post(
         "api/v1/configurations/",
         data=data,
         headers={"Authorization": f"Token {create_user['api_key']}"},
     )
     r = await client.get(
         "api/v1/configurations/",
         headers={"Authorization": f"Token {create_user['api_key']}"},
     )
     after_saved_configuration = await r.json()
     assert len(after_saved_configuration) == len(start_configurations) + 1
Exemple #34
0
async def upload_to_telegraph(file_id):
    response = await GetFile(file_id).send()
    API_FILE_URL = 'https://api.telegram.org/file/bot{}/'.format(
        context.bot.token)
    url = API_FILE_URL + response.file_path

    session: ClientSession = context.bot.connector._session

    response = await session.get(url)
    file_data = await response.read()

    form = FormData()
    form.add_field('file', file_data)

    async with session.post('https://telegra.ph/upload',
                            data=form) as response:
        resp = await response.json()
        if 'error' in resp:
            logger.error(resp)
            return resp
        else:
            p = (await response.json())[0]['src']
            attach = f'https://telegra.ph{p}'
            return attach
Exemple #35
0
async def submit_experiment(session):
    """ Submit experiment scenario """
    users = molotov.get_var('users')
    if users.empty():
        print("No users ...")
        assert False
    user = users.get()
    config = molotov.get_var('config')['experiments']
    exp = _Experiment(name=generate_exp_name(),
                      duration=config['duration'])
    alias = AliasNodes(config['nb_nodes'], molotov.get_var('site'), 'm3:at86rf231', False)
    exp.set_alias_nodes(alias)
    form = FormData()
    form.add_field("exp", json_dumps(exp),
                   content_type="application/json")
    async with session.post(
        urljoin(molotov.get_var('url'), 'experiments'),
        # password = Monkey-<login>
        auth=get_auth(user, 'Monkey-{}'.format(user)),
        data=form,
    ) as resp:
        res = await resp.json()
        assert res['id'] is not None
        assert resp.status == 200
Exemple #36
0
 async def test_args(self, server):
     url = f"http://127.0.0.1:{server.port}/component/args_test?" \
         f"query_arg=test_query"
     async with ClientSession(conn_timeout=10,
                              read_timeout=10,
                              cookies={
                                  "session": "111",
                                  "uid": "222"
                              },
                              headers={"referer":
                                       'http://www.baidu.com/'}) as session:
         data = FormData()
         data.add_field("form_arg", "test_form")
         resp = await session.post(url, data=data)
         assert await resp.json() == {
             "query_arg": "test_query",
             "referer": 'http://www.baidu.com/',
             "form_arg": "test_form",
             "session": "111",
             "cookies": {
                 "session": "111",
                 "uid": "222"
             }
         }
Exemple #37
0
 def content(self) -> FormData:
     """ multipart forms are tricky, but aiohttp does well if we fill in the right blanks. """
     form = FormData()
     form.add_field('payload_json', super().content())
     for i, (fp, filename, content_type) in enumerate(self._files):
         form.add_field(f'file{i}',
                        fp,
                        filename=filename,
                        content_type=content_type)
     return form
Exemple #38
0
    async def async_set_hvac_mode(self, hvac_mode):
        try:
            powerOn = hvac_mode == HVAC_MODE_HEAT
            _LOGGER.info("Swtting Power Mode: %s", powerOn)
            params = {}
            params["value"] = powerOn
            websession = async_get_clientsession(self.hass)
            with async_timeout.timeout(_TIMEOUT):
                response = await websession.post('http://192.168.20.15/power',
                                                 data=FormData(params))

            # The status takes a while to set after the POST
            await asyncio.sleep(2)

        except Exception as error:
            _LOGGER.error("Error setting power mode: %s", error)
Exemple #39
0
 async def uploadImage(self,
                       image_bytes: bytes,
                       method: UploadMethods,
                       return_external: bool = False) -> Image:
     data = FormData()
     data.add_field("sessionKey", self.connect_info.sessionKey)
     data.add_field("type", method.value)
     data.add_field("img", image_bytes)
     async with self.session.post(self.url_gen("uploadImage"),
                                  data=data) as response:
         response.raise_for_status()
         resp_json = await response.json()
         raise_for_return_code(resp_json)
         external_component = external.Image.parse_obj(resp_json)
         if return_external:
             return external_component
         else:
             return Image.fromExternal(external_component)
async def get_user_info_and_redirect(access_token, next_url, request_session):
    '''
    We use the access_token to get the user info.
    Upon success, we save the info in request_session and redirect the next_url.
    On failure (ie an invalid token), we remove the info from the request_session,
    try to get an explanation, and do _not_ redirect anywhere.
    '''
    # LOG.debug('Token: %s', access_token)
    async with ClientSession() as session:
        headers = {
            'Accept': 'application/json',
            'Authorization': 'Bearer ' + access_token
        }
        LOG.debug('Contacting %s', conf.idp_user_info)
        async with session.get(conf.idp_user_info, headers=headers) as resp:
            # LOG.debug('Response %s', resp)
            if resp.status == 200:
                user = await resp.json()
                # Save and exit
                LOG.info('user: %s', user)
                request_session['user'] = user
                raise HTTPFound(next_url)
            else:
                content = await resp.text()
                LOG.error('Content: %s', content)

    # Invalid access token
    LOG.error('Invalid token')
    del request_session['access_token']
    if 'user' in request_session:
        del request_session['user']
    # Get the explanation
    async with ClientSession() as session:
        async with session.post(conf.idp_introspection,
                                auth=BasicAuth(
                                    conf.idp_client_id,
                                    password=conf.idp_client_secret),
                                data=FormData(
                                    {
                                        'token': access_token,
                                        'token_type_hint': 'access_token'
                                    },
                                    charset='UTF-8')) as resp:
            LOG.debug('Response %s', resp)
            content = await resp.text()
            LOG.debug('Content: %s', content)
    LOG.debug('Invalid token, try to get a new one')
Exemple #41
0
async def store_objects(request):
    PATH = '/object'
    async with request.app['db'].acquire() as conn:
        service_config = await get_service_config_by_action(conn=conn, action='store', media_type='default')
    logging.debug(msg='store_objects service_config: {}'.format(str(service_config)))
    config = dict(service_config.get('config'))
    endpoint = service_config.get('endpoint')
    bucket_name = dict({'bucket_name': '3deposit'})
    config.update(bucket_name)

    if request.method == 'GET':
        try:
            data = request.query
            config.update({'bucket_name': data.get('bucket_name')})
            payload = dict({'config': config})
            async with new_request(method='GET', url=endpoint+PATH, json=payload) as resp:
                try:
                    resp_json = await resp.json()
                except Exception as err:
                    return web.json_response({'err': str(err), 'resp': await resp.text()})
                return web.json_response({'resp': resp_json, 'payload': payload})
        except Exception as err:
            return web.json_response({'origin': 'gateway', 'err': str(err)})

    if request.method == 'POST':
        try:
            q = dict(request.query)
            fd = FormData()
            reader = await request.multipart()
            while True:
                part = await reader.next()
                if part is None:
                    break
                if part.name == 'file':
                    fd.add_field(name='file', value=await part.read(), filename=q.get('deposit_id'), content_type='application/octet-stream')
                else:
                    continue
            fd.add_field('config', json.dumps(config), content_type='application/json')
            fd.add_field('data', json.dumps(q), content_type='application/json')
            async with new_request(method='POST', url=endpoint+PATH, data=fd) as resp:
                resp_json = await resp.json()
                return web.json_response(resp_json)
        except Exception as err:
            return web.json_response({'origin': 'gateway', 'err': str(err)})
Exemple #42
0
async def test_api_upload_put(app, headers) -> None:
    file = io.StringIO('Mock In-Memory File')

    data = FormData()
    data.add_field('media',
                   '{"id": "ABC123"}',
                   content_type='application/json')
    data.add_field('file', file, content_type='text/plain')

    response = await app.put('/upload', headers=headers, data=data)
    assert response.status == 200
Exemple #43
0
def get_multipart_file_data(directory):
    form_data = FormData()

    form_data.add_field("metadata",
                        dumps({"data_type": DATA_TYPE}),
                        content_type="application/json")

    form_data.add_field("file",
                        open(directory / AUDIO_FILE, "rb"),
                        content_type=CONTENT_TYPE)

    return form_data
async def post(session, url):
    with async_timeout.timeout(60):
        data = FormData()
        data.add_field('file',
                       open('lamb.jpg', 'rb'),
                       filename='lamb.jpg',
                       content_type='image/jpeg')
        data.add_field('action[]', 'post1')
        data.add_field('action[]', 'post2')

        async with session.post(url, data=data) as response:
            return await response.text()
 def go():
     _, _, url = yield from self.create_server('POST', '/', handler)
     _data = FormData()
     _data.add_field('file', b'binary data 1',
                     content_type='image/jpeg',
                     filename='test1.jpeg')
     _data.add_field('file', b'binary data 2',
                     content_type='image/jpeg',
                     filename='test2.jpeg')
     resp = yield from request('POST', url, data=_data,
                               loop=self.loop)
     self.assertEqual(200, resp.status)
     resp.close()
Exemple #46
0
 async def upload_files(self, files, guid):
     async with self.get_session() as session:
         data = FormData()
         data.add_field(
             'data',
             files[0]['body'],
             filename=files[0]['filename'],
         )
         data.add_field("user", str(guid))
         res = await session.post(settings.upload_service, data=data)
     # tasks = [asyncio.Task(aiohttp.request("POST", settings.upload_service, data=f)) for f in files]
     # res = await asyncio.gather(*tasks)
     return res
    async def _upload_test(self, test_id):
        csv_file = await self._get_csv_data(test_id)

        form = FormData()
        form.add_field('token', BMSENSE_TOKEN, content_type='text/plain')
        form.add_field('projectKey', 'AIOLT_TEST')
        form.add_field('jtl_file', csv_file, filename='report.gz')

        async with self._client_session.post(url=self.BASE_URL + 'api/file/upload/?format=json',
                                             headers={'User-Agent': 'AIOLT-Uploader'},
                                             data=form) as response:
            if response.status == 200:
                async with self._db.acquire() as conn:
                    async with conn.transaction():
                        await conn.execute("""
                            UPDATE tests
                            SET status = 'uploaded'
                            WHERE id = $1 
                            """, test_id)
                        self._logger.info(f'Test \'{test_id}\' results are successfully uploaded')
            else:
                self._logger.error(f'Unexpected response from BMSense: {response!r}')