简体   繁体   English

如何使用表格调用python函数而不是脚本?

[英]How do you call a python function instead of a script using a form?

I've been reading the book 'Head First Python' where the writer talks about creating dynamic webpages using a module he created called 'yate', an HTML template engine (which I renamed to site_yate in the code below). 我一直在读《 Head First Python》一书,作者在其中谈论如何使用他创建的名为“ yate”的模块创建动态网页,该模块是HTML模板引擎(在下面的代码中我将其重命名为site_yate)。 The example he works through is a hypothetical coach wanting his athletes to be able to check their times online. 他工作的示例是一个假设的教练,希望他的运动员能够在线检查自己的时间。 The design is as follows: first you enter the homepage which has a link to run a script which generates a webpage where you can select the athlete whose times you want to view. 设计如下:首先进入主页,该主页具有运行脚本的链接,该脚本生成一个网页,您可以在其中选择要查看其时间的运动员。 Then when you select your athlete and click submit the form calls another script called "site_generate_timing_data.py" where you can views the athlete's top times. 然后,当您选择运动员并单击“提交”表单时,将调用另一个名为“ site_generate_timing_data.py”的脚本,您可以在其中查看运动员的上班时间。 So I decided to take it further and add functionality to add a time for the athlete, using this extra line of code in my python script. 因此,我决定更进一步,并添加功能以使用我的python脚本中的这些额外代码行为运动员增加时间。

print(site_yate.do_form("addtime.py", [athlete_id]))

The HTML this will generate will be this: 这将生成的HTML将是这样的:

<form action="addtime.py" method="POST">
<h1>Want to add a time?</h1>
<input type="Text" name="1" size=40> //"1" is the athlete's id in this example
<input type="Submit" value="Submit">
</form>

As you can see this code calls the script 'addtime.py' which has the following code: 如您所见,此代码调用脚本“ addtime.py”,该脚本具有以下代码:

import cgi
import sqlite3

data = cgi.FieldStorage().value[0] #this attribute will be in the form MininFieldStorage(name, value)
id = data.name #this attribute is the input's name i.e. athlete's id
time = data.value #this attribute is the input's value i.e. the time

connection = sqlite3.connect("NUACDB.sqlite") #my DB's name
cursor = connection.cursor()
cursor.execute("""INSERT INTO timing_data (athlete_id, time) 
                VALUES (?, ?)""",
                (id, time)) #just SQL stuff
connection.commit()
connection.close()

Which works fine, however I want to change a few thing about this, since it leaves the user on a blank page. 效果很好,但是我想对此进行一些更改,因为它将用户留在了空白页上。 I could generate some HTML code to provide links to the homepage etc. or even JavaScript code to redirect the user automatically, but I want to keep this script HTML-free so that I can also use it elsewhere. 我可以生成一些HTML代码来提供指向首页等的链接,甚至可以生成JavaScript代码来自动重定向用户,但是我想将此脚本保持HTML格式,这样我也可以在其他地方使用它。

What I want to do instead is make the script execute on the same page. 我要做的是使脚本在同一页面上执行。 Not only that, but I would also prefer if I could put the addtime.py code as a function in another module called 'athletemodel.py' and call it form there, ie athletemodel.addtime() (or I could do from athletemodel import addtime so I can call the function directly). 不仅如此,如果我可以将addtime.py代码作为一个函数放在另一个名为“ athletemodel.py”的模块中,然后在此处调用它的形式,即athletemodel.addtime() (或者我可以from athletemodel import addtime以便我可以直接调用该函数)。 How can I call a python function using HTML code? 如何使用HTML代码调用python函数? I'm aware of the onsubmit="" form attribute but apparently that is for JavaScript functions. 我知道onsubmit=""表单属性,但显然这是针对JavaScript函数的。 Another thing I'm unsure about is whether the data submitted in the form will still be accessible through CGI FieldStorage and hence whether my addtime.py code will still work as it is. 我不确定的另一件事是,是否仍可以通过CGI FieldStorage访问表单中提交的数据,因此我的addtime.py代码是否仍将按原样工作。

This stuff is so confusing! 这些东西真令人困惑! All help is appreciated. 感谢所有帮助。

Not sure if you already had it in mind, but I would use ajax (remember to include the jQuery library). 不知道您是否已经有了它,但是我会使用ajax(请记住包括jQuery库)。 Here's a rough example to get you started if this is what you want. 如果需要的话,这是一个使您入门的粗糙示例。 It'll keep them on the same page: 它将保持在同一页面上:

JavaScript file: JavaScript文件:

$('#submitButtonId').click(function (event) {
        event.preventDefault();
        $('#submitButtonId').hide();
        $('#thinking').show(); //some div with a nice ajax loader gif...
        $.ajax({
            type: 'POST',
            data: $('#formId').serialize(),
            url: '/URL_path_to_function',
            success: function (data) {
                $('#loading').hide();
                var response = data.result  //now do stuff with your response
                }
            error: function(error){
                   console.log('Error')}
         });

Python view/function: Python视图/功能:

import jsonify
if request.method == 'POST':
    value = request.form['input value'] #flask...
    #Do stuff
    return jsonify(result='Some response')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM