简体   繁体   English

Flask-Marshmallow通过API公开DB内容的问题

[英]Issue with Flask-Marshmallow exposing DB contents via API

I am developing a API which will return entries from a Database. 我正在开发一个API,它将从数据库返回条目。 I am using Flask-SQLAlchemy, Flask-Marshmallow, Flask-Admin and Docker to package it all up. 我正在使用Flask-SQLAlchemy,Flask-Marshmallow,Flask-Admin和Docker来打包它。

In one file Packages.py I have the following code regarding the database. 在一个文件Packages.py中,我有关于数据库的以下代码。 The class PckagesSchema is the class I've added when trying to get Flash-Marshmallow working. PckagesSchema类是我在尝试使Flash-Marshmallow工作时添加的类。

class Packages(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    trackingnumber = db.Column(db.String(15))
    email = db.Column(db.String(80))
    localid = db.Column(db.String(80))

class PackagesSchema(ma.ModelSchema):
    class Meta:
        model = Packages

The in the main file I have the following snippets of code 在主文件中我有以下代码片段

from app.models import Packages, PackagesSchema
packages_schema = PackagesSchema()
db.create_all()

and then further down the part which will deal with API GET Requests. 然后进一步向下处理API GET请求的部分。

@app.route('/packages', methods=['GET'])
def get_packages():
    result = packages_schema.dump(Packages).data
    return jsonify(result)

at the moment this returns: 此时此返回:

{
  "email": "Packages.email", 
  "localid": "Packages.localid", 
  "trackingnumber": "Packages.trackingnumber"
}   

However, there is definitely something in the database as the Flask-Admin app displays its. 但是,当Flask-Admin应用程序显示它时,数据库中肯定存在某些内容。

This is my first day working with Flask-Marshmallow so I am not that experienced at all and would appreciate any help. 这是我与Flask-Marshmallow合作的第一天,所以我根本没有经验,并感谢任何帮助。 I have read https://flask-marshmallow.readthedocs.io/en/latest/ but still stuck. 我已阅读https://flask-marshmallow.readthedocs.io/en/latest/但仍然卡住了。

I just brushed up a little on marshmallow: 我刚刚在棉花糖上刷了一点:

@app.route('/packages', methods=['GET'])
def get_packages():
    packages = Packages.query.all()
    result = packages_schema.dump(packages).data
    return jsonify(result)

Should give you everything in there. 应该给你一切。 If you are returning many records, you need to add packages_schema = PackagesSchema(many=True) . 如果要返回许多记录,则需要添加packages_schema = PackagesSchema(many=True)

Also, not sure what version of flask you are running... but pre the latest release, I dont think jsonify would work here since you could not call it on a list. 此外,不知道你正在运行什么版本的烧瓶...但在最新版本之前,我不认为jsonify会在这里工作,因为你不能在列表上调用它。 Juts a heads up. 抬起头来。

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

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