首页 > 解决方案 > AIOHTTP:TypeError: index() 接受 0 个位置参数,但给出了 1 个

问题描述

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)

主文件

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

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

标签: async-awaitpython-asyncioaiohttppytest-aiohttp

解决方案


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

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

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


推荐阅读