Call a python function within a html file

前端 未结 5 1040
甜味超标
甜味超标 2020-12-02 11:56

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

Thanks

5条回答
  •  Happy的楠姐
    2020-12-02 12:05

    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:

    
    
    Test 
     
    
    Click me
    

    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

提交回复
热议问题