我可以在 GCP 云功能中使用 python - aiohttp 吗?

Can I use python - aiohttp inside of a GCP cloud function?

我正在尝试 route/divvy 将一些工作负载分配给其他云功能,它们都需要大致相同的时间,但我必须同步调用它们。我尝试设置它,并在使用 Flask 实现它时听从了某人的建议,以在 Flask 上下文之外实例化我的循环,因为它需要控制主线程(也需要 return),并且一切似乎仍然是同步执行的,我只需要在一个对象中收集一些响应。这个简单的 I/O 问题似乎不适用于 GCP Cloud Functions。我看过这个 。那只是简单的异步,所以这应该可以工作。如果有人之前让这个工作过,你能分享一个例子吗?

loop = asyncio.get_event_loop()
app = Flask(__name__)
CORS(app)

@app.route('/', methods=['POST'])
def calculations():
    calculations_to_perform_queue = []
            for calculation_request in request_data['calculations']:
                for calculation in calculation_request['calculation_requests']:
                    calculations_to_perform_queue.append(calculation)

    async def threaded_calculation_request_operation(session, 
        calculation_meta_data) -> dict: reference in calculations if exists
        url = calculation_meta_data['endpoint_url']
        async with session.post(
            url=url,
            headers={'X-Access-Token': request.headers['X-Access-Token']},
            json=json_safe_response(calculation_meta_data) as response:
        return await response.json()


    async def session_controler():
        async with aiohttp.ClientSession() as session:
            finished_queue = []
            for calculation in calculations_to_perform_queue:
                response = await threaded_calculation_request_operation(session, calculation)
                finished_queue.append(response)
            return finished_queue

    all_returned_charts = loop.run_until_complete(session_controler())
    prccesed_response = processed_for_return(all_returned_charts)
    return prccesed_response, 200

你不能直接使用 asyncio,python 运行时是沙盒的,所以 asyncio.get_event_loop() 会出错。

有一种方法可以实现异步请求分派,但是(模糊地)记录在此处:

https://cloud.google.com/appengine/docs/standard/python/migrate-to-python3/migrate-outbound-requests#making_asynchronous_https_requests

这也适用于 Cloud Functions。