Upvotes
Anonymous 0
User 0
Member votes
Anonymous votes
CEFPython: Initiating a Python-based Web Service Call from within JavaScript
When developing an app with CEFPython, there may be many reasons you'd like to make a service call from Python.
Sensitive security credentials need to be sent The service isn't simple to consume from JavaScript (e.g. SOAP)
If the service call takes a while, you may notice that the browser's UI hangs (I noticed this). I created a class to help handle the threading:
import requests
import threading
class ThreadedRequestHelper ( threading . Thread ):
def __init__ ( self , external ):
self . external = external
def SendRequestThread ( self ):
#time.sleep(3)
response = requests . post ( self . url , json = self . json_obj )
self . external . ExecuteFunction ( 'OnStatesDataReceived' , response . text )
def SendRequest ( self , url , json_obj ):
self . url = url
self . json_obj = json_obj
threading . Thread ( target = self . SendRequestThread ) . start ()
Note: This code is for a quick demo, so it was quickly thrown together. The
sleep() function above is for testing, to see if the browser UI hangs while we're waiting.
The JavaScript handler in the Python code looks like this:
def GetStates ( self , json_obj ):
request_helper = ThreadedRequestHelper ( self )
request_helper . SendRequest ( 'http://localhost:9090/GetStates' , json_obj )
$ ( document ). ready ( function () {
$ ( '#states-filter' ). on ( 'keypress' , function ( e ) {
if ( e . which == 13 ) {
GetStates ();
}
})
$ ( '#submitButton' ). on ( 'click' , function () {
GetStates ();
});
});
function GetStates () {
var request = {
filter : $ ( '#states-filter' ). val ()
};
external . GetStates ( request );
}
function OnStatesDataReceived ( json_response ) {
var response = JSON . parse ( json_response );
var html = '' ;
for ( var i = 0 ; i < response . length ; i ++ ) {
html += '<li>' + response [ i ] + '</li>' ;
}
$ ( '#states' ). html ( html );
}
The full wxpython.py and some web files are attached below. Note that this is not all of the files necessary needed to run (as that is very large in size).
Download 1cc3088a-f589-11e4-8d5a-f23c91df6128.zip
Comments
Leave a Comment
We'll review your submission and post it to this page.