Transcrypt:如何发送 ajax POST 请求以使用 Python / Flask 启动服务器端作业

Transcrypt: How to send an ajax POST request to start a server side job using Python / Flask

我正处于创建 Flask 应用程序的早期阶段,并且从@Miguel Grinberg 那里看到了一个关于创建长 运行 任务的很好的例子。目前我想减少我在项目中必须学习/使用的 JavaScript 的数量,Transcrypt 引起了我的注意。

但是,我有点迷失在试图弄清楚如何完成 POST 请求以触发任务的文档中。这是 JavaScript 中的代码:

    // send ajax POST request to start background job
        $.ajax({
            type: 'POST',
            url: '/longtask',
            success: function(data, status, request) {
                status_url = request.getResponseHeader('Location');
                update_progress(status_url, nanobar, div[0]);
            },
            error: function() {
                alert('Unexpected error');
            }
        });

我如何在 Python 中使用 Transcrypt 完成此操作?

您可以在 Flask 中使用 post 方法。

from flask import Flask
app = Flask(__name__)

@app.route('/index/', methods=['POST'])
def sample_function():
    # do your server task here
    return "BROWSER Update/response"

app.run("127.0.0.1", "8000")

在JavaScript中,用AJAX调用http://127.0.0.1:8000/index/

进行如下操作:

$ 不是 Python 中的有效标识符,因此请使用 __pragma__ ('alias', 'jq', '$'),如下所示。

除了 lambda 之外,Python 不知道匿名函数,所以使用普通函数作为回调。在下面的示例中,使用了局部函数。

注意在字段名称周围加上引号,例如'success' 而不是成功,因为这是 Python 约定。

Ajax 使用 Transcrypt 的示例:

__pragma__ ('alias', 'jq', '$')

# For use by eval'ed turtle applet
import turtle
import random
import math

def clear ():
    editor.setValue ('')
    turtle.reset ()
    run ()

def run ():
    def success (result):
        turtle.reset ()
        eval (result)

    def fail (a, b, c):
        print ('Run error:', a, b, c)

    # N.B. The request has to be explicitly encoded, but the response is already implicitly decoded
    jq.ajax ({
        'url':'http://www.transcrypt.org/compilemodule',
        'type': 'POST',
        'data': JSON.stringify (editor.getValue ()),
        'dataType': 'json',
        'contentType': 'application/json',
        'success': success,
        'fail': fail
    })

def mail ():
    def success (result):
        print (result)

    def fail (a, b, c):
        print ('Run error:', a, b, c)

    jq.ajax ({
        'url':'http://www.transcrypt.org/sendmail',
        'type': 'POST',
        'data': JSON.stringify ([document.getElementById ('mail_address') .value, editor.getValue ()]),
        'dataType': 'json',
        'contentType': 'application/json',
        'success': success,
        'fail': fail
    })

def selectExample ():
    def success (result):
        editor.setValue (result [0])
        turtle.reset ()     # Using old paths
        window.terminate = True
        eval (result [1])   # Using new paths (so cannot clear old result)

    def fail (a, b, c):
        print ('Select example error:', a, b, c)

    selector = document.getElementById ('select_example')

    jq.ajax ({
        'url':'http://www.transcrypt.org/selectexample',
        'type': 'POST',
        'data': JSON.stringify (selector.options [selector.selectedIndex] .value),
        'dataType': 'json',
        'contentType': 'application/json',
        'success': success,
        'fail': fail
    })

selectExample ()