Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a python function within a html file

Tags:

python

html

Is there a way to call a python function when a certain link is clicked within a html page?

Thanks

like image 297
hassaanm Avatar asked Apr 10 '11 22:04

hassaanm


People also ask

Can we call Python code from HTML?

At the PyconUS 2022, Anaconda unveiled a new framework called PyScript which uses python in HTML code to build applications. You can use python in your HTML code. You don't need to know javascript. PyScript is not just HTML only, it is more powerful, because of the rich and accessible ecosystem of Python libraries.


3 Answers

You'll need to use a web framework to route the requests to Python, as you can't do that with just HTML. Flask is one simple framework:

server.py:

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def index():
  return render_template('template.html')

@app.route('/my-link/')
def my_link():
  print 'I got clicked!'

  return 'Click.'

if __name__ == '__main__':
  app.run(debug=True)

templates/template.html:

<!doctype html>

<title>Test</title> 
<meta charset=utf-8> 

<a href="/my-link/">Click me</a>

Run it with python server.py and then navigate to http://localhost:5000/. The development server isn't secure, so for deploying your application, look at http://flask.pocoo.org/docs/0.10/quickstart/#deploying-to-a-web-server

like image 81
Blender Avatar answered Oct 16 '22 07:10

Blender


Yes, but not directly; you can set the onclick handler to invoke a JavaScript function that will construct an XMLHttpRequest object and send a request to a page on your server. That page on your server can, in turn, be implemented using Python and do whatever it would need to do.

like image 42
Michael Aaron Safyan Avatar answered Oct 16 '22 08:10

Michael Aaron Safyan


Yes. If the link points to your web server, then you can set up your web server to run any kind of code when that link is clicked, and return the result of that code to the user's browser. There are many ways to write a web server like this. For example, see Django. You might also want to use AJAX.

If you want to run code in the user's browser, use Javascript.

like image 23
David Grayson Avatar answered Oct 16 '22 08:10

David Grayson