![](/img/trans.png)
[英]generate csv in JS and send it using ajax request POST to 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');
}
});
如何使用Transcrypt在Python中完成此操作?
進行如下:
$
在Python中不是有效的標識符,因此請使用__pragma__ ('alias', 'jq', '$')
,如下所示。
除了lambda之外,Python不知道匿名函數,因此請使用普通函數作為回調。 在以下示例中,使用了本地功能。
請注意,在字段名兩邊加上引號,例如,“成功”而不是成功,因為這是Python約定。
使用Transcrypt的Ajax示例:
__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 ()
您可以在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/
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.