【发布时间】:2019-09-05 18:09:02
【问题描述】:
我希望能够以简单的方式通过 Web 请求触发长时间运行的 Python 脚本。另外,我希望能够在初始副本仍在运行时触发具有不同参数的脚本的其他副本。
我研究了烧瓶、aiohttp 和排队的可能性。 Flask 和 aiohttp 的设置似乎开销最小。我计划通过 subprocess.run 执行现有的 python 脚本(但是,我确实考虑将脚本重构为可用于 Web 响应函数的库)。
使用 aiohttp,我正在尝试类似: 摄取服务.py:
from aiohttp import web
from pprint import pprint
routes = web.RouteTableDef()
@routes.get("/ingest_pipeline")
async def test_ingest_pipeline(request):
'''
Get the job_conf specified from the request and activate the script
'''
#subprocess.run the command with lookup of job conf file
response = web.Response(text=f"Received data ingestion request")
await response.prepare(request)
await response.write_eof()
#eventually this would be subprocess.run call
time.sleep(80)
return response
def init_func(argv):
app = web.Application()
app.add_routes(routes)
return app
虽然初始请求会立即返回,但后续请求会阻塞,直到初始请求完成。我正在通过以下方式运行服务器:
python -m aiohttp.web -H localhost -P 8080 ingestion_service:init_func
我知道多线程和并发可能提供比 asyncio 更好的解决方案。在这种情况下,我不是在寻找一个健壮的解决方案,只是让我能够通过 http 请求一次运行多个脚本,理想情况下内存成本最低。
【问题讨论】:
标签: python multithreading http subprocess aiohttp