【问题标题】:Return data from Python to Javascript将数据从 Python 返回到 Javascript
【发布时间】:2012-11-12 23:08:57
【问题描述】:

我有一个 Python 脚本,可以打印并返回服务器文件夹中的所有图像文件。

import os
images = ""
for dirname, dirnames, filenames in os.walk('..\directory'):
    for filename in filenames:
        images = images + os.path.join(dirname, filename) + "^"
print(images)
return images

我在 Javascript 中使用:

$.get("scripts/filename.py", function(data){
  alert(data);
});

但是,它只是显示来自 filename.py 的代码,而不是获取“打印”或返回的数据。我在这里错过了什么吗?

编辑: 顺便说一句,我正在使用 Google App Engine 来托管我的网站。

【问题讨论】:

  • 你用的是什么框架?只是只有 python 不能帮助你现在正在做的事情,你应该使用一些框架运行开发服务器,例如django 框架,简单而强大。
  • @doniyor 我正在使用谷歌应用引擎。

标签: javascript python return


【解决方案1】:

只需将 Phyton 脚本放在 cgi 文件夹中

【讨论】:

    【解决方案2】:

    【讨论】:

    • 关于那个,我正在使用谷歌应用引擎来托管我的应用程序。现在,我已经启动了 Google App Engine 启动器,所以我通过localhost:8080/index.html 访问我的网页。我不确定是否还应该为 windows 设置 python?
    • 当然,一旦你运行你的开发服务器,你应该为 windows 设置 python...
    • 我没有看到 Google App Engine 教程中关于设置开发服务器的任何说明。我会试试这个。谢谢!
    【解决方案3】:

    您需要进行一些 Web 框架设置,例如 Flaskcherrypy。我建议使用 Flask,它是最容易上手的 Web 框架。

    然后您需要有一些端点,您可以向其发送AJAX GET 请求,然后您的 Python 脚本将返回 JSON 响应。您可以遍历此 JSON 响应以打印出结果。

    此代码可能适合您:

    import sys, os
    from flask import Flask, request, url_for, render_template
    
    @app.route('/images')
    def index():
        images = ""
        for dirname, dirnames, filenames in os.walk('..\directory'):
            for filename in filenames:
                images = images + os.path.join(dirname, filename) + "^"
        print(images)
        # return a json encoded response
        return Response(json.dumps(images, sort_keys=True, indent=4), mimetype='application/json')
    
    if __name__ == '__main__':
        # Bind to PORT if defined, otherwise default to 5000.
        port = int(os.environ.get('PORT', 5000))
        app.run(host='0.0.0.0', port=port)
    

    现在您需要启动服务器,每当您在localhost:5000/images 发送 GET 请求时,它都会返回您正在寻找的 JSON 响应。

    【讨论】:

      猜你喜欢
      • 2020-07-20
      • 2016-08-21
      • 2013-01-24
      • 1970-01-01
      • 1970-01-01
      • 2013-03-29
      • 2013-02-22
      • 2018-11-16
      • 2016-06-05
      相关资源
      最近更新 更多