【问题标题】:Getting plain text instead of Python script execution获取纯文本而不是 Python 脚本执行
【发布时间】:2015-05-19 07:19:08
【问题描述】:

我正在尝试在页面加载时使用 jquery 执行这个小请求:

$.ajax({
    type: "GET",
    url: "/static/query.py",
    cache: false,
    success: function (data) {
        $(body).text(data);
    }
});

在虚拟环境中运行 nginx、python 的服务器上,使用 Flask 框架,返回的是 query.py 源代码,而不是从数据库中检索到的数据。

query.py 被标记为可执行并且脚本有 shebang:

#!/home/gabriel/project/bin

它指向我的 virtualenv 中的 bin。我认为已经涵盖了基础,但问题仍然存在。

提示?

更多信息:

烧瓶脚本:

from flask import Flask, render_template

application = Flask(__name__)

@application.route('/')
def init():
    return render_template('index.html')

if __name__ == "__main__":
    application.run(host='0.0.0.0', debug=True)

uwsgi.py 加载 Flask 脚本:

from myapp import application

if __name__ == "__main__":
    application.run()

query.py:

from db import * //Database model, SQLAlchemy.

def something():
    data = Kingdom.query.all()
    return data

something()

【问题讨论】:

  • 您的设置中没有运行脚本的内容。该请求是完全“静态的”。当您说“运行 python”时,这是什么意思? python正在运行什么框架?烧瓶,姜戈?还有什么?应该有一种机制服务于 'static/query.py' 路由。指向一个文件只会为该文件提供服务(NGINX 正在这样做,python 不会以任何方式参与您的设置)。
  • 我正在使用 Flask。
  • 请贴出相关的flask代码,我们会搞清楚的..
  • 我到家后会查看它,但我遵循了本教程:digitalocean.com/community/tutorials/… 并且最初的 Python 工作正常,它在“/”时加载了主模板页面。我开始相信你的 cmets 这是一个配置问题。

标签: python nginx virtualenv uwsgi


【解决方案1】:

您应该在烧瓶内运行 query.py 中的实际代码。执行以下操作:

@application.route("/query"):
def get_data():
    .. whatever code you need; currently in query.py, you would probably use sqlalchemy/ flask-sqlalchemy
    data =  your data (dictionary? list?) 
    return jsonify(data=data) # flask will turn your data into a proper JSON string to send back as a response to the ajax call.

不要忘记从烧瓶中导入 jsonify,请参阅文档here。 在上面的示例中,还将“/static/query.py”重命名为“/query”,或者您认为合适的任何其他名称。您还可以通过 AJAX 调用发送烧瓶参数以在您的查询中进行处理;例如,过滤参数。关注问题以获得进一步的指导。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2014-04-29
    • 2019-05-09
    • 2019-06-11
    相关资源
    最近更新 更多