【问题标题】:Query using variable from url not executing - Flask-SQLAlchemy使用来自 url 的变量查询未执行 - Flask-SQLAlchemy
【发布时间】:2018-06-28 11:19:21
【问题描述】:

我让 jquery 向 api 端点发送一个请求。代码如下:

$.get("http://localhost:5000/api/update/"+ elm2, function(data){});

端点定义如下:

@app.route('/api/update/<id>', methods=['GET'])
def check_new_entries(id):
    result = Trades.query.filter_by(id=id).first_or_404()
    new_entries = Trades.query.filter(Trades.time_recorded > result.time_recorded).all()

查询的表是:

class Trades(db.Model):
    id = db.Column(db.String,default=lambda: str(uuid4().hex), primary_key=True)
    amount = db.Column(db.Integer, unique=False)
    time_recorded = db.Column(db.DateTime, unique=False)

问题: Jquery 成功发送了正确的请求,变量类型为字符串,但是在执行第一个查询时,它无法返回任何内容。 我在另一个应用程序中有一个类似的端点,它工作正常。为什么这是一个例外?可能缺少什么?我确信我正在查询的记录在数据库中,所以它应该返回它。

【问题讨论】:

    标签: python jquery flask sqlalchemy flask-sqlalchemy


    【解决方案1】:
    @app.route('/api/update/<id>', methods=['GET',])
    def check_new_entries(id):
        result = Trades.query.filter_by(id=id).first()
        if result:
            new_entries = Trades.query.filter(Trades.time_recorded >= result.time_recorded).all()
    

    【讨论】:

    • 对不起,我忘了显示表格...主键是一个字符串 - 类型为 uuid4().hex
    • 检查结果是否被 first_or_404 方法处理好。问题是该条目在数据库中,但由于某种原因无法获取它。我对为什么查询不起作用感到很困惑。
    【解决方案2】:

    问题是在字符串的其余部分之前有一些意想不到的空格。该错误源于 jquery 和 jinja,其中 jquery 获取元素的 html 内容并将它们作为变量发送。 jinja 语法类似于: &lt;p&gt; {{ variable }}&lt;/p&gt; 当 jquery 获取 html 内容时,它会占用段落开头标记和开头花括号之间的空格。传输的变量有一个导致错误的前导空格。

    【讨论】:

      猜你喜欢
      • 2018-01-16
      • 2014-10-09
      • 2018-05-09
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      • 2013-07-24
      • 1970-01-01
      相关资源
      最近更新 更多