如何从Javascript(jquery / ajax)调用Python脚本中的特定函数/方法

时间:2022-03-14 06:45:45

To clarify: I am running this as cgi via Apache web server. That isn't the problem My question is regarding a way to specify which function within the Python script to run when I call it via an ajax request.

澄清一下:我通过Apache Web服务器将其作为cgi运行。这不是问题我的问题是关于指定Python脚本中的哪个函数在我通过ajax请求调用时运行的方法。

I read a tutorial that said to pass the function name I want to call as a var. I did that. In the Python, I tried

我读了一个教程,说要传递我想要调用的函数名作为var。我做到了在Python中,我试过了

Here's my ajax function

这是我的ajax功能

 $(document).ready(function() {
    $.ajax({
       url: "monStat.py",
       type: "post",
       data: {'callFunc':'isRunning'},
       success: function(response){
           $('#blurg').html(response).fadeIn(1500);
       }
    });
 });

Here's the Python

这是Python

 def main():
      if callFunc:
           funcResp = isRunning()
      else:
           print("No function passed")

 def isRunning( process_name ):
    ''' the content ''' 

3 个解决方案

#1


4  

You'll need to make your script web-capable. I haven't worked with CGI, so here's an example with Flask:

您需要使您的脚本具有Web功能。我没有使用过CGI,所以这是Flask的一个例子:

from flask import Flask, request

app = Flask(__name__)

@app.route('/is_running', methods=['POST'])
def isRunning():
    process_name = request.values.get('name', None)

    ''' the content '''

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000)

Now, you can just send a request to /is_running:

现在,您只需向/ is_running发送请求即可:

$.ajax({
   url: "/is_running",
   type: "post",
   data: {'name': 'ls'},
   success: function(response){
       $('#blurg').html(response).fadeIn(1500);
   }
});

#2


1  

Even though you don't mention what kind of web framework you are using (if any), I am going to assume from the naming of your url that you are trying to directly call a python script on your server.

即使你没有提到你正在使用什么样的Web框架(如果有的话),我将从你的url命名中假设你试图直接调用服务器上的python脚本。

The only way for this to work is if your monStat.py script is structured as a CGI script, and hosted on your server accordingly (in a way that CGI scripts will be executed). Your javascript implies that you want to make a POST request to this script, so your python script will need to accept a POST request, and then read the parameters and act on them. You cannot just name a callable as a string in javascript and have the CGI script automatically know what to run. This is the place of a web framework to provide advanced URL handling.

这种方法的唯一方法是将monStat.py脚本构造为CGI脚本,并相应地托管在服务器上(以执行CGI脚本的方式)。您的javascript意味着您要对此脚本发出POST请求,因此您的python脚本需要接受POST请求,然后读取参数并对其进行操作。你不能只在javascript中将一个callable命名为一个字符串,并让CGI脚本自动知道要运行什么。这是Web框架提供高级URL处理的地方。

If you are trying to just call a regular python script via a url, that is not going to work. The most basic primitive approach is using the python CGI module. This is good for just learning and getting started, but a very inefficient and dated approach. You should probably look into a web framework: Python WebFrameworks

如果你试图通过url调用常规python脚本,那就不行了。最基本的原始方法是使用python CGI模块。这对于刚学习和入门很有好处,但这是一种非常低效和过时的方法。您应该研究一下Web框架:Python WebFrameworks

Update

As you stated you are in fact using a CGI script...
"Routing" is something you get for free when you use web frameworks. It takes the incoming request into the main loop and decides where it should go to be handled. When you use only CGI, you will have to do this yourself. Every time you make a request to the CGI script, it executes just like a normal script, with a normal entrypoint.

正如您所说,您实际上正在使用CGI脚本......当您使用Web框架时,“路由”是您免费获得的。它将传入的请求带入主循环并决定它应该在哪里处理。当您仅使用CGI时,您必须自己完成此操作。每次向CGI脚本发出请求时,它都会像普通脚本一样执行,并具有正常的入口点。

In that entrypoint, you have to read the request. If the request is POST and contains "is_running" then you can forward that request off to your is_running() handler. The "function name" is just string data. It is up to your code to read the request and determine what to do.

在该入口点,您必须阅读该请求。如果请求是POST并包含“is_running”,那么您可以将该请求转发到is_running()处理程序。 “函数名称”只是字符串数据。由您的代码来读取请求并确定要执行的操作。

Here is a super rough example of what it might look like, where you map some acceptable handlers to functions you allow:

下面是一个非常粗略的例子,它可能会将一些可接受的处理程序映射到您允许的函数:

#!/usr/bin/env python
import cgi
import cgitb
cgitb.enable()

def isRunning(form):
    print "Content-Type: text/html\n" 
    print "isRunning()"
    print form.getvalue('name') 

def _error(*args):
    print "Content-Type: text/html\n" 
    print "Error"


HANDLERS = {
    'isRunning': isRunning
}


def main():
    form = cgi.FieldStorage()

    h_name = form.getvalue('callFunc')
    handler = HANDLERS.get(h_name, _error)
    handler(form)


if __name__ == "__main__":
    main()

#3


0  

This is a start:

这是一个开始:

import cgi
fs = cgi.FieldStorage()

print "Content-type: text/plain\n"
for key in fs.keys():
    print "%s = %s" % (key, fs[key].value)

#1


4  

You'll need to make your script web-capable. I haven't worked with CGI, so here's an example with Flask:

您需要使您的脚本具有Web功能。我没有使用过CGI,所以这是Flask的一个例子:

from flask import Flask, request

app = Flask(__name__)

@app.route('/is_running', methods=['POST'])
def isRunning():
    process_name = request.values.get('name', None)

    ''' the content '''

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000)

Now, you can just send a request to /is_running:

现在,您只需向/ is_running发送请求即可:

$.ajax({
   url: "/is_running",
   type: "post",
   data: {'name': 'ls'},
   success: function(response){
       $('#blurg').html(response).fadeIn(1500);
   }
});

#2


1  

Even though you don't mention what kind of web framework you are using (if any), I am going to assume from the naming of your url that you are trying to directly call a python script on your server.

即使你没有提到你正在使用什么样的Web框架(如果有的话),我将从你的url命名中假设你试图直接调用服务器上的python脚本。

The only way for this to work is if your monStat.py script is structured as a CGI script, and hosted on your server accordingly (in a way that CGI scripts will be executed). Your javascript implies that you want to make a POST request to this script, so your python script will need to accept a POST request, and then read the parameters and act on them. You cannot just name a callable as a string in javascript and have the CGI script automatically know what to run. This is the place of a web framework to provide advanced URL handling.

这种方法的唯一方法是将monStat.py脚本构造为CGI脚本,并相应地托管在服务器上(以执行CGI脚本的方式)。您的javascript意味着您要对此脚本发出POST请求,因此您的python脚本需要接受POST请求,然后读取参数并对其进行操作。你不能只在javascript中将一个callable命名为一个字符串,并让CGI脚本自动知道要运行什么。这是Web框架提供高级URL处理的地方。

If you are trying to just call a regular python script via a url, that is not going to work. The most basic primitive approach is using the python CGI module. This is good for just learning and getting started, but a very inefficient and dated approach. You should probably look into a web framework: Python WebFrameworks

如果你试图通过url调用常规python脚本,那就不行了。最基本的原始方法是使用python CGI模块。这对于刚学习和入门很有好处,但这是一种非常低效和过时的方法。您应该研究一下Web框架:Python WebFrameworks

Update

As you stated you are in fact using a CGI script...
"Routing" is something you get for free when you use web frameworks. It takes the incoming request into the main loop and decides where it should go to be handled. When you use only CGI, you will have to do this yourself. Every time you make a request to the CGI script, it executes just like a normal script, with a normal entrypoint.

正如您所说,您实际上正在使用CGI脚本......当您使用Web框架时,“路由”是您免费获得的。它将传入的请求带入主循环并决定它应该在哪里处理。当您仅使用CGI时,您必须自己完成此操作。每次向CGI脚本发出请求时,它都会像普通脚本一样执行,并具有正常的入口点。

In that entrypoint, you have to read the request. If the request is POST and contains "is_running" then you can forward that request off to your is_running() handler. The "function name" is just string data. It is up to your code to read the request and determine what to do.

在该入口点,您必须阅读该请求。如果请求是POST并包含“is_running”,那么您可以将该请求转发到is_running()处理程序。 “函数名称”只是字符串数据。由您的代码来读取请求并确定要执行的操作。

Here is a super rough example of what it might look like, where you map some acceptable handlers to functions you allow:

下面是一个非常粗略的例子,它可能会将一些可接受的处理程序映射到您允许的函数:

#!/usr/bin/env python
import cgi
import cgitb
cgitb.enable()

def isRunning(form):
    print "Content-Type: text/html\n" 
    print "isRunning()"
    print form.getvalue('name') 

def _error(*args):
    print "Content-Type: text/html\n" 
    print "Error"


HANDLERS = {
    'isRunning': isRunning
}


def main():
    form = cgi.FieldStorage()

    h_name = form.getvalue('callFunc')
    handler = HANDLERS.get(h_name, _error)
    handler(form)


if __name__ == "__main__":
    main()

#3


0  

This is a start:

这是一个开始:

import cgi
fs = cgi.FieldStorage()

print "Content-type: text/plain\n"
for key in fs.keys():
    print "%s = %s" % (key, fs[key].value)