0

I am a newbie for the aiohttp, and I have a question below,

First, I have a button in the page as below,

<body>

<button class="button" name="click_me" onclick="click_me">Click Me</button>

</body>

and in the python code, I define the function as below,

async def click_me(request):
    logger.info(f'test on click_me')


async def handler(request):
    ... ... default code here ... ... 

However, when I open the browser and click the "click_me" button, the debugging page shows the error,

Uncaught ReferenceError: click_me is not defined at HTMLButtonElement.onclick

How to define the function in the python script to catch click_me event?

rainbirdy
  • 15
  • 2

1 Answers1

1

No, the onclick attribute refers to a Javascript function, that must be loaded in your page. If you want to call a Python function from that click event, you must perform an HTTP request (or whatever, there are many other ways), for instance with AJAX or fetch, to your corresponing server's url. e.g.

<body>
  <button onclick="doFoo()"></button>
  <script>
    async function doFoo() {
      const response = await fetch('http://YOURSERVER/foo')
      // do whatever you want with your response
    }
  </script>
</body>

Will call the Python foo function defined here

from aiohttp import web

async def foo(request):
    logger.info("button clicked")
    return web.Response()

app = web.Application()
app.add_routes([web.get('/foo', foo)])

if __name__ == '__main__':
    web.run_app(app)
geertjanvdk
  • 3,440
  • 24
  • 26
michaeldel
  • 2,204
  • 1
  • 13
  • 19