Call a python function within a html file

101,064

Solution 1

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

Solution 2

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.

Solution 3

There are several ways to do this, but the one that has worked best for me is to use CherryPy. CherryPy is a minimalist python web framework that allows you to run a small server on any computer. There is a very similiar question to yours on stackoverflow - Using the browser for desktop UI.

The code below will do what you want. Its example 2 from the CherryPy tutorial.

import cherrypy

class HelloWorld:

    def index(self):
        # Let's link to another method here.
        return 'We have an <a href="showMessage">important message</a> for you!'
    index.exposed = True

    def showMessage(self):
        # Here's the important message!
        return "Hello world!"
    showMessage.exposed = True

import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')

if __name__ == '__main__':
    # CherryPy always starts with app.root when trying to map request URIs
    # to objects, so we need to mount a request handler root. A request
    # to '/' will be mapped to HelloWorld().index().
    cherrypy.quickstart(HelloWorld(), config=tutconf)
else:
    # This branch is for the test suite; you can ignore it.
    cherrypy.tree.mount(HelloWorld(), config=tutconf)

I personally use CherryPy in combination with several other modules and tools:

  • Mako (template library)
  • py2exe (convert into Windows executable)
  • GccWinBinaries (used in combination with py2exe)

I wrote an article about Browser as Desktop UI with CherryPy that introduces modules and tools used plus some further links that might help.

Solution 4

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.

Solution 5

In addition to running Python scripts on a server, you can run Python scripts on the client-side using Skulpt.

Share:
101,064

Related videos on Youtube

hassaanm
Author by

hassaanm

Updated on July 09, 2022

Comments

  • hassaanm
    hassaanm over 1 year

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

    Thanks

  • Temere
    Temere about 10 years
    can you do this with bottle?
  • Blender
    Blender about 10 years
    @Temere: The syntax should be exactly the same. I think render_template has just a different name.
  • Pravesh Jain
    Pravesh Jain over 8 years
    Creating just these two files does not work. Is there more to be done (creating projects) ?
  • Blender
    Blender over 8 years
    @PraveshJain: Are you running server.py? What's the error? "Not working" isn't very useful.
  • Pravesh Jain
    Pravesh Jain over 8 years
    Sorry for the unclear query. When I run server.py, it runs and doesn't produce any output. Neither does it wait to listen for url requests. And when I click on the "click me" link in doc.html, it gives a "page not found error".
  • Pravesh Jain
    Pravesh Jain over 8 years
    That's what has baffled me. The execution of server.py lasts only a second. It doesn't stall. So when I go to localhost:5000, it expectedly says "webpage not available".
  • Blender
    Blender over 8 years
    @PraveshJain: Are you running this through Windows? Can you open a Command Prompt window, cd into the folder where the script resides, and then run it with python server.py? This should generate output.
  • Pravesh Jain
    Pravesh Jain over 8 years
  • Pravesh Jain
    Pravesh Jain over 8 years
    Sorry there was a typo in the code (most embarrassing moment ever). Now the file produces output but when I go to 127.0.0.1:5000, it says Internal Server Error and the terminal output also confirms this with response code 500.
  • Blender
    Blender over 8 years
    @PraveshJain: Change app.run() to app.run(debug=True) and it should be more clear.
  • Pravesh Jain
    Pravesh Jain over 8 years
    Now it is showing the error as "TemplateNotFound: template.html". However, I rechecked and the template.html file is in the same directory.
  • Blender
    Blender over 8 years
    @PraveshJain: Oh, sorry if I wasn't clear. You need to put template.html into a templates folder.