简体   繁体   中英

run python in javascript

I have a python script python.py as follow:

import requests
import json

url = "https://api.dropboxapi.com/2/sharing/list_shared_links"

headers = {
    "Authorization": "Bearer MY_ACCESS_KEY",
    "Content-Type": "application/json"
}

data = {
    "path": "/downloads/files.txt"
}

r = requests.post(url, headers=headers, data=json.dumps(data))

and a php web page as follow:

<html>
    <script src='//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'></script>

        <button id="getlink">Get Link</button>
        <div id="output"></div>
<script>
        function handleSharedLink(evt) {
             exec(python getLink.py);
        }

        var obj = document.getElementById('getlink').addEventListener('click', handleSharedLink, false);
        document.getElementById('output').innerHTML = obj;
</script>

Btw, I couldn't get the result from the python and show in the html div<'output'> . How can I show that? Any help will be appreciated!

EDITED: I edited my code as follow instead of running the python file in the javascript. But the result still doesn't show.

<html>
<script src='//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'></script>

<input type="file" id="files" name="files[]" multiple />
<br/><br/>

<button id="getlink">Get Link</button>
<div id="output"></div>

<script>
 function handleSharedLink(evt) {

  $.ajax({     
     url: "https://api.dropboxapi.com/2/sharing/get_shared_links",

     headers:
        {
            "Authorization": "Bearer 1lzp0Ii5agAAAAAAAAAAJTVD-jRpVMcOfefVBzVkXOzM-W_LiFHSl7F9mgkd4bYk",
            "Content-Type": "application/json"
        },

    data:
        {
            "path": "TARCpace.apk"
        },
    success: function (data) {
            console.log(data);
    },
    error: function (data) {
            console.log(data);
    }
    r = requests.post(url, headers=headers, data=json.dumps(data))       
 })
}

  var output = document.getElementById('getlink').addEventListener('click', handleSharedLink, false);
  output.innerHTML = html(r);
</script>

</html> 

How can I improve that?

I never came across any scenario to run ad-hoc scripts from javascript. Most of the cases, the server side scripts are exposed as APIs and can be triggered by simple AJAX calls.

I found a probable solution with little research which you might have already looked at it.

Call python function from JS

Note: this is best suites as comment. But I don't have enough reputation today to post a comment :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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