gpt4 book ai didi

async-await - AIOHTTP:TypeError: index() 采用 0 个位置参数,但给出了 1 个

转载 作者:行者123 更新时间:2023-12-02 03:24:35 24 4
gpt4 key购买 nike

from aiohttp import web
import aiohttp
from settings import config
import asyncio
import psycopg2 as p
import json
import aiopg

import aiohttp
import asyncio

async def fetch(client):
async with client.get('https://jsonplaceholder.typicode.com/todos/1') as resp:
assert resp.status == 200
return await resp.json()

async def index():
async with aiohttp.ClientSession() as client:
html = await fetch(client)
return web.Response(html)

loop = asyncio.get_event_loop()
loop.run_until_complete(index())

这是我的观点.py

from aiohttp import web
from routes import setup_routes
from settings import config

app = web.Application()
setup_routes(app)

web.run_app(app,port=9090)

main.py

from views import index

def setup_routes(app):
app.router.add_get('/', index)

这是我的routes.py

但是当我尝试触发 localhost:9090 的 url 时,我只是收到内部服务器 500 错误说

TypeError: index() takes 0 positional arguments but 1 was given

但是我可以在终端中打印 json,但无法像浏览器中的 Web 响应一样触发,我不知道这种情况下出了什么问题

最佳答案

您的 index 协程是 handler ,因此它必须接受单个位置参数,该参数将收到 Request实例。例如:

async def index(request):
async with aiohttp.ClientSession() as client:
html = await fetch(client)
return web.Response(html)

views.py 顶层的 loop.run_until_complete(index()) 是不必要的,一旦 index() 定义正确。

关于async-await - AIOHTTP:TypeError: index() 采用 0 个位置参数,但给出了 1 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53764494/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com