15

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

Thanks

hassaanm
  • 391
  • 2
  • 5
  • 14

5 Answers5

28

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

Blender
  • 289,723
  • 53
  • 439
  • 496
  • can you do this with bottle? – Temere Oct 10 '13 at 08:17
  • @Temere: The syntax should be exactly the same. I think `render_template` has just a different name. – Blender Oct 10 '13 at 12:53
  • Creating just these two files does not work. Is there more to be done (creating projects) ? – Pravesh Jain May 12 '15 at 13:32
  • @PraveshJain: Are you running `server.py`? What's the error? "Not working" isn't very useful. – Blender May 12 '15 at 17:08
  • 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 May 12 '15 at 17:25
  • 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". – Pravesh Jain May 12 '15 at 17:33
  • @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. – Blender May 12 '15 at 17:33
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/77640/discussion-between-pravesh-jain-and-blender). – Pravesh Jain May 12 '15 at 17:35
  • 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. – Pravesh Jain May 12 '15 at 17:40
  • 1
    @PraveshJain: Change `app.run()` to `app.run(debug=True)` and it should be more clear. – Blender May 12 '15 at 17:46
  • Now it is showing the error as "TemplateNotFound: template.html". However, I rechecked and the template.html file is in the same directory. – Pravesh Jain May 12 '15 at 17:49
  • 2
    @PraveshJain: Oh, sorry if I wasn't clear. You need to put `template.html` into a `templates` folder. – Blender May 12 '15 at 17:50
  • great it works for me...but what if i would pass something? like variables? thanks – Tommy Jul 28 '23 at 08:49
7

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.

Michael Aaron Safyan
  • 93,612
  • 16
  • 138
  • 200
2

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.

David Grayson
  • 84,103
  • 24
  • 152
  • 189
2

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.

Community
  • 1
  • 1
schurpf
  • 609
  • 7
  • 7
1

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

Anderson Green
  • 30,230
  • 67
  • 195
  • 328