【问题标题】:AIOHTTP:TypeError: index() takes 0 positional arguments but 1 was givenAIOHTTP:TypeError: index() 接受 0 个位置参数,但给出了 1 个
【发布时间】:2018-12-13 14:51:46
【问题描述】:
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 响应相同的响应,我不知道在这种情况下出了什么问题

【问题讨论】:

    标签: async-await python-asyncio aiohttp pytest-aiohttp


    【解决方案1】:

    您的 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() 被正确定义就不会起作用。

    【讨论】:

    • 但是每当我尝试运行服务器时,我都无法停止服务器并且无法访问该页面,它说我无法加载该页面,我能知道为什么以及如何解决这个问题吗??
    【解决方案2】:

    您的 index() 异步函数应该接受 request 参数才能兼容网络处理程序。

    【讨论】:

      猜你喜欢
      • 2020-06-13
      • 1970-01-01
      • 2013-09-23
      • 2017-10-05
      • 2016-01-30
      • 2019-06-26
      • 2014-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多