python - 在没有 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”,但我认为应该有一种方法来修复代码
解决方案
如果需要获取本地文件的内容,可以用普通的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
推荐阅读
- javascript - TinyMCE:如何让用户在“只读:真”时标记文本;
- vba - 使文本在单行的一系列单元格中从右到左爬行
- jquery - 我需要编辑或删除内联样式
- html - 如何设置标题元素之间的相等距离?
- c - 总是打印相同的浮点值
- javascript - 在 React JS Jest 测试中测试一个函数
- spring-boot - 应用不断尝试重启消息服务,如何只运行一次消息服务?
- django - 使用 HTML 表单而不是 Django 模型表单编辑对象
- go - 为什么 post 请求在 gin golang 中不起作用?
- r - 惯用矩阵类型转换,例如将整数(0/1)矩阵转换为布尔矩阵