I'm in the early stages of creating a Flask application and came across a great example from @Miguel Grinberg on creating a long running task. At the moment I want to reduce the amount of JavaScript that I would have to learn / use in my project and Transcrypt caught my eye.
However, I am a bit lost in the documentation trying to figure out how I would accomplish POST requests to trigger the task. Here is the code in 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');
}
});
How would I accomplish this in Python using Transcrypt?
Proceed as follows:
$
isn't a valid identifier in Python so use __pragma__ ('alias', 'jq', '$')
as below.
Apart from lambda's, Python doesn't know anonymous functions, so use ordinary functions as callbacks instead. In the examples below, local functions are used.
Take care to put quotes around field names, so e.g. 'success' rather than success, since this is the Python convention.
Example of Ajax using 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 ()