首页 > 解决方案 > 在没有 Web 服务器的情况下从 localhost 获取文件

问题描述

我想在没有网络服务器的情况下异步从本地主机获取文件。似乎可以使用 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”,但我认为应该有一种方法来修复代码

标签: pythonwebserverpython-asyncioaiohttp

解决方案


如果需要获取本地文件的内容,可以用普通的Python内置函数来完成,比如:

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

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

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

推荐阅读