Call a python function within a html file

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("https://stackoverflow.com/")
def index():
  return render_template('template.html')

@app.route("https://stackoverflow.com/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="https://stackoverflow.com/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

Leave a Comment