0

i'm creating an API in python + Flask + marshmallow. Here's the class + the first function (i don't already use the others )

import datetime
from marshmallow import Schema, fields, ValidationError, pre_load
from flask import Flask, jsonify
from flask_marshmallow import Marshmallow
from flask_sqlalchemy import SQLAlchemy
from flask import request
import os


app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'User.sqlite')
# Order matters: Initialize SQLAlchemy before Marshmallow
db = SQLAlchemy(app)
ma = Marshmallow(app)





class User(db.Model):
    userid = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30))
    badgenum = db.Column(db.String(30))
    mail = db.Column(db.String(30))
    status = db.Column(db.String(30))
    admin = db.Column(db.String(30))

    def __init__(self, userid, name, badgenum, mail, status, admin):
        self.userid = userid
        self.name = name
        self.badgenum = badgenum
        self.mail = mail
        self.status = status
        self.admin = admin


class UserSchema(ma.Schema):
    class Meta:
        fields = ('userid', 'name', 'badgenum', 'mail', 'status', 'admin')


user_schema = UserSchema()
users_schema = UserSchema(many=True)


@app.route("/User", methods=["POST"])
def add_User():
    userid = request.json['userid']
    name = request.json['name']
    badgenum = request.json['badgenum']
    mail = request.json['mail']
    status = request.json['status']
    admin = request.json['admin']


    new_user = User(userid, name, badgenum, mail, status, admin)

    db.session.add(new_user)
    db.session.commit()

    return jsonify(new_user)

I tested the function add_User using Postman with this json request :

{

    "userid" : 1,
    "name" : "name1",
    "badgenum" : "66897",
    "mail" : "ghh@orange.fr",
    "status" : "on",
    "admin" : "f"

}

and i got this error:

TypeError: <User 145> is not JSON serializable

Couldn't read row 0, col -1 from CursorWindow

Is saying that for row 0 (the first row in the cursor), it cannot read index(offset) -1. Index 0 is the first coulmn, 2 the 2nd etc. So you are tring to access a non-existant/impossible column.

However, the getColumnIndex method will return -1 if the column name passed to the method cannot be found as a column name.

Therefore one of these does not resolve/equate to a column name.

android.provider.MediaStore.Audio.Albums._ID
android.provider.MediaStore.Audio.Albums.ALBUM
android.provider.MediaStore.Audio.Albums.ALBUM_ART

You could determine which by commenting out each line in turn. Alternately you could add the following after the line cursor = getContentResolver().query(uri,null, selection,null, null); :-

String[] columns = cursor.getColumnNames();
for (String s: columns) {
    Log.d("CURSORCOLUMNS","Found column = " + s);
}
Log.d("NAMECOLUMN","The name column is " + android.provider.MediaStore.Audio.Albums._ID);
Log.d("ARTISTCOLUMN","The artist column is " + android.provider.MediaStore.Audio.Albums.ALBUM);
Log.d("ARTIST1COLUMN","The artist1 column is "+ android.provider.MediaStore.Audio.Albums.ALBUM_ART);

This will display the columns in the cursor followed by the columns that you are expecting to be in the cursor. One of the latter 3 will not be in the Found column = ????????. That will be the cause of the -1.

4

1 回答 1

3

用户有自己的自动生成的 ID user.id,即 ObjectId。您需要自定义 json 编码器来编码 ObjectId 字段。

import json, bson

def json_response(obj, cls=None):
    response = make_response(json.dumps(obj, cls=cls))
    response.content_type = 'application/json'

    return response

class MongoJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, bson.ObjectId):
            return str(obj)

        return json.JSONEncoder.default(self, obj)

现在尝试打电话return json_response(new_user, cls=MongoJsonEncoder)

于 2018-02-01T11:54:25.010 回答