在没有 Web 服务器的情况下从本地主机获取文件

Fetch file from localhost without web server

我想在没有网络服务器的情况下从本地主机异步获取文件。似乎可以使用 file:// 方案。以下代码示例取自文档,但显然它不起作用:

import aiohttp
import asyncio

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    async with aiohttp.ClientSession() as session:
        html = await fetch(session, 'file://localhost/Users/user/test.txt')
        print(html)

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

如何让它发挥作用?

我看到的一种方法是使用 run_in_executor 在单独的线程池中使用“curl file://path”,但我认为应该有一种修复代码的方法

如果需要获取本地文件的内容,可以用普通的Pythonbuilt-ins,如:

with open('Users/user/test.txt') as rd:
    html = rd.read()

如果文件不是很大,并且存储在本地文件系统中,您甚至不需要将其设为异步,因为读取速度足够快,不会干扰事件循环。如果文件较大或由于其他原因读取速度较慢,则应通过 run_in_executor 读取它以防止它阻塞其他 asyncio 代码。例如(未经测试):

def read_file_sync(file_name):
    with open('Users/user/test.txt') as rd:
        return rd.read()

async def read_file(file_name):
    loop = asyncio.get_event_loop()
    html = await loop.run_in_executor(None, read_file_sync, file_name)
    return html