2011-04-10 81 views

回答

19

您需要使用Web框架将请求路由到Python,因为您不能仅使用HTML来完成此操作。 Flask是一个简单的框架:

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) 

模板/ template.html

<!doctype html> 

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

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

python server.py运行它,然后导航到http://localhost:5000/。开发服务器是不安全的,所以为了部署你的应用程序,看看http://flask.pocoo.org/docs/0.10/quickstart/#deploying-to-a-web-server

+0

你可以用瓶子做这个吗? – Temere 2013-10-10 08:17:27

+0

@Temere:语法应该完全一样。我认为'render_template'只是一个不同的名字。 – Blender 2013-10-10 12:53:32

+0

创建这两个文件不起作用。是否还有更多工作要做(创建项目)? – 2015-05-12 13:32:51

6

是的,但不是直接;您可以设置onclick处理程序来调用JavaScript函数,该函数将构造一个XMLHttpRequest对象并将请求发送到服务器上的页面。反过来,您的服务器上的那个页面可以使用Python实现,并执行需要的任何操作。

2

是的。如果链接指向您的Web服务器,那么您可以将Web服务器设置为在单击该链接时运行任何类型的代码,并将该代码的结果返回给用户的浏览器。有很多方法来编写这样的Web服务器。例如,请参阅Django。您可能也想使用AJAX。

如果您想在用户的浏览器中运行代码,请使用Javascript。

2

有几种方法可以做到这一点,但最适合我的方法是使用CherryPy。 CherryPy是一个极简主义的Python Web框架,允许您在任何计算机上运行小型服务器。在stackoverflow - Using the browser for desktop UI上有一个非常类似的问题。

下面的代码将做你想要的。它的示例2来自CherryPy教程。

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) 

我个人使用的CherryPy结合其他几个模块和工具:

  • 真子(模板库)
  • py2exe(转换成Windows可执行文件)
  • GccWinBinaries(结合使用py2exe)

我写了一篇关于Browser as Desktop UI with CherryPy的文章t介绍了使用的模块和工具以及一些可能有所帮助的进一步链接

1

除了在服务器上运行Python脚本,您还可以使用Skulpt在客户端运行Python脚本。

相关问题