简体   繁体   English

Flask Jsonify在一台计算机上返回对象列表,在另一台计算机上返回包含元组的列表

[英]Flask Jsonify returning a list of objects on one computer and a list containing tuples on another

Both computers are running Flask version 0.12.2, on the same browser version (chrome 58.0.3029.110 (64-bit)). 两台计算机都在同一浏览器版本(chrome 58.0.3029.110(64位))上运行Flask版本0.12.2。

This is an example of the data passed into the jsonify function serialized data: 这是传递到jsonify函数序列化数据中的数据的示例:

[('Code1', ['website1.com']), ('Code2', ['website2.com'])]

The output of the machine without simplejson installed is: 没有安装simplejson的机器的输出为:

[["Code1",["website1.com"]],["Code2",["website2.com"]]]

versus this with simplejson installed: 与此相比,安装了simplejson:

[{"code":"Code1",place:["website1.com"]},{"code":"Code2",place:["website2.com"]}]
from flask import jsonify, Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://localhost:5432/test_db'
db = SQLAlchemy(app)

class myModel(db.Model):
    __tablename__ = 'testtable'

    code1 = db.Column(db.Text, primary_key=True)
    code2 = db.Column(db.Text)
    def __init__(self, co1, co2):
        self.code1 = co1
        self.code2 = co2

@app.route("/")
def b():
    a = [('Code1', ['website1.com']), ('Code2', ['website2.com'])]
    myModel = test_model.myModel("website1.com", "website2.com")
    myModel = test_model.myModel("website3.com", "website4.com")
    db.session.add(myModel)
    db.session.commit()
    query = test_model.myModel.query.with_entities(test_model.myModel.code1).all()
    print("my model", query, type(query))
    foo = jsonify(query)
    print(foo)
    return foo

if __name__ == "__main__":
    app.run(debug=True)

When running python test_file.py without simplejson installed the output is 在未安装simplejson的情况下运行python test_file.py ,输出为

[
  [
    "website3.com"
  ], 
  [
    "website3.com"
  ], 
  [
    "website3.com"
  ], 
  [
    "website3.com"
  ], 
  [
    "website3.com"
  ], 
  [
    "website3.com"
  ]
]

When running with simplejson installed the output is 在安装了simplejson的情况下运行时,输出为

[
  {
    "code1": "website3.com"
  }, 
  {
    "code1": "website3.com"
  }, 
  {
    "code1": "website3.com"
  }, 
  {
    "code1": "website3.com"
  }, 
  {
    "code1": "website3.com"
  }, 
  {
    "code1": "website3.com"
  }, 
  {
    "code1": "website3.com"
  }
]

All in all it is something about the interaction between simplejson and flask-sqlalchemy maybe? 总而言之,这可能与simplejson和flask-sqlalchemy之间的交互有关? just happened across it using flask 刚发生在烧瓶上

The issue was having the simplejson python package installed on the machine running ubuntu. 问题是在运行ubuntu的计算机上安装了simplejson python软件包。 It overrides the python json library causing it to return an array of objects instead of an array of arrays as expected when calling jsonify. 它会覆盖python json库,导致它返回对象数组,而不是调用jsonify时所期望的数组数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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