带附件Python的并发POST请求

带附件Python的并发POST请求,python,concurrency,python-requests,python-asyncio,aiohttp,Python,Concurrency,Python Requests,Python Asyncio,Aiohttp,我有一个服务器,它正在等待包含图片的请求: @app.route("/uploader_ios", methods=['POST']) def upload_file_ios(): imagefile = request.files['imagefile'] 我可以使用python中的请求非常轻松地提交post请求,如下所示: url = "<myserver>/uploader_ios" files = {'imagefile': open(fname, 'rb')} %

我有一个服务器,它正在等待包含图片的请求:

@app.route("/uploader_ios", methods=['POST'])
def upload_file_ios():
    imagefile = request.files['imagefile']
我可以使用python中的请求非常轻松地提交post请求,如下所示:

url = "<myserver>/uploader_ios"
files = {'imagefile': open(fname, 'rb')}
%time requests.post(url, files=files).json()  # 2.77s

我假设这是因为我没有正确地附加图像文件

我猜
数据
参数是用于文章正文的。文件可能有一个
files
参数。@dirn-Ah所以服务器需要request.files.imagefile,但得到request.data.imagefile。我重新阅读了,似乎将它们添加为“数据”是唯一的方法。我想知道是否有可能在发送之前将数据的名称更改为文件,就像我说的,这只是一个猜测。您最好检查服务器上的日志(如果
app
支持这样的操作,则在调试模式下运行),以查看实际触发400错误的原因。我猜
data
参数是针对文章主体的。文件可能有一个
files
参数。@dirn-Ah所以服务器需要request.files.imagefile,但得到request.data.imagefile。我重新阅读了,似乎将它们添加为“数据”是唯一的方法。我想知道是否有可能在发送之前将数据的名称更改为文件,就像我说的,这只是一个猜测。您最好检查服务器上的日志(如果
app
支持此功能,则在调试模式下运行),以查看实际触发400错误的原因。
import aiohttp
import asyncio
import json

# Testing with small amount
concurrent = 2
url_list = ['<myserver>/uploader_ios'] * 10

def handle_req(data):
    return json.loads(data)['English']

def chunked_http_client(num_chunks, s):
    # Use semaphore to limit number of requests
    semaphore = asyncio.Semaphore(num_chunks)
    @asyncio.coroutine
    # Return co-routine that will work asynchronously and respect
    # locking of semaphore

    def http_get(url):
        nonlocal semaphore
        with (yield from semaphore):

            # Attach files
            files = aiohttp.FormData()
            files.add_field('imagefile', open(fname, 'rb'))

            response = yield from s.request('post', url, data=files)
            print(response)

            body = yield from response.content.read()
            yield from response.wait_for_close()
        return body
    return http_get

def run_experiment(urls, _session):
    http_client = chunked_http_client(num_chunks=concurrent, s=_session)

    # http_client returns futures, save all the futures to a list
    tasks = [http_client(url) for url in urls]

    dfs_route = []

    # wait for futures to be ready then iterate over them
    for future in asyncio.as_completed(tasks):
        data = yield from future
        try:
            out = handle_req(data)
            dfs_route.append(out)
        except Exception as err:
            print("Error {0}".format(err))
    return dfs_route

with aiohttp.ClientSession() as session:  # We create a persistent connection
    loop = asyncio.get_event_loop()
    calc_routes = loop.run_until_complete(run_experiment(url_list, session))
.../uploader_ios) [400 BAD REQUEST]>