我一直在尝试创建一个服务器进程,该进程从客户端进程异步接收输入文件路径和输出路径。服务器执行一些依赖于数据库的转换,但为了简单起见,我们假设它只是将所有内容都设为大写。这是服务器的一个玩具示例:
import asyncio
import aiofiles as aiof
import logging
import sys
ADDRESS = ("localhost", 10000)
logging.basicConfig(level=logging.DEBUG,
format="%(name)s: %(message)s",
stream=sys.stderr)
log = logging.getLogger("main")
loop = asyncio.get_event_loop()
async def server(reader, writer):
log = logging.getLogger("process at {}:{}".format(*ADDRESS))
paths = await reader.read()
in_fp, out_fp = paths.splitlines()
log.debug("connection accepted")
log.debug("processing file {!r}, writing output to {!r}".format(in_fp, out_fp))
async with aiof.open(in_fp, loop=loop) as inp, aiof.open(out_fp, "w", loop=loop) as out:
async for line in inp:
out.write(line.upper())
out.flush()
writer.write(b"done")
await writer.drain()
log.debug("closing")
writer.close()
return
factory = asyncio.start_server(server, *ADDRESS) …Run Code Online (Sandbox Code Playgroud) 我有一个在 fastapi 和 aiofiles 上运行的异步代码,我正在尝试从 .json 文件加载和保存我的信息,但是每次我关闭程序时,它只保存字典的键并显示“ASGI 'lifespan'协议似乎不受支持”按摩
这是我的开启/关闭部分:
@app.on_event("startup")
async def startup_event():
global beers
try:
async with aiofiles.open("data.json", mode='r+', json=True) as file:
beers = await file.read()
except:
beers = {}
@app.on_event("shutdown")
async def on_exit_app():
async with aiofiles.open("data.json", "w+") as outfile:
await outfile.write(beers)
Run Code Online (Sandbox Code Playgroud)
任何想法问题出在哪里?
我有一个问题,我是 python 异步世界的新手,我编写了一些代码来测试 的功能asyncio,我创建了 10 个包含随机内容的文件,名为file1.txt, file2.txt, ..., file10.txt
这是我的代码:
import asyncio
import aiofiles
import time
async def reader(pack, address):
async with aiofiles.open(address) as file:
pack.append(await file.read())
async def main():
content = []
await asyncio.gather(*(reader(content, f'./file{_+1}.txt') for _ in range(10)))
return content
def core():
content = []
for number in range(10):
with open(f'./file{number+1}.txt') as file:
content.append(file.read())
return content
if __name__ == '__main__':
# Asynchronous
s = time.perf_counter()
content = asyncio.run(main())
e = time.perf_counter()
print(f'Take {e - s: …Run Code Online (Sandbox Code Playgroud) 我的程序执行以下操作:
对于每个文件:
2.1. 读取文件
2.2 将内容排序为列表并将列表推送到主列表
我在没有任何 async/await 的情况下这样做了,这些是时间统计信息
real 0m0.036s
user 0m0.018s
sys 0m0.009s
Run Code Online (Sandbox Code Playgroud)
使用下面的异步/等待代码我得到
real 0m0.144s
user 0m0.116s
sys 0m0.029s
Run Code Online (Sandbox Code Playgroud)
考虑到用例表明我错误地使用了 aysncio。
有人知道我做错了什么吗?
import asyncio
import aiofiles
import os
directory = "/tmp"
listOfLists = list()
async def sortingFiles(numbersInList):
numbersInList.sort()
async def awaitProcessFiles(filename,numbersInList):
await readFromFile(filename,numbersInList)
await sortingFiles(numbersInList)
await appendToList(numbersInList)
async def readFromFile(filename,numbersInList):
async with aiofiles.open(directory+"/"+filename, 'r') as fin:
async for line in fin:
return numbersInList.append(int(line.strip("\n"),10))
fin.close()
async def appendToList(numbersInList):
listOfLists.append(numbersInList)
async def main():
tasks=[]
for filename …Run Code Online (Sandbox Code Playgroud)