0

因此,我正在尝试使用 MongoAlchemy 学习 Flask 和 MongoDB,并且在尝试查询我的应用程序以获取数据时遇到了问题,我不确定自己做错了什么。我已经搜索了 MongoAlchemy 文档并关注了一些 StackOverflow 帖子,但没有真正的用处。这是我的代码:

from flask import Flask, jsonify, request
from flask_mongoalchemy import MongoAlchemy

app = Flask(__name__)
app.config['MONGOALCHEMY_DATABASE'] = 'user'
app.config['MONGOALCHEMY_SERVER_AUTH'] = False
db = MongoAlchemy(app)

class User(db.Document):
    user_name = db.StringField()
    password = db.StringField()
    first_name = db.StringField()
    last_name = db.StringField()
    phone_number = db.StringField()

def init_app():
    app = Flask(__name__)
    db.init_app(app)
    return app

user_1 = User(user_name = "user1", 
    password = "password", 
    first_name = "John", 
    last_name = "Doe",
    phone_number = "123-456-7890")

user_1.save()

@app.route('/', methods=['GET', 'POST'])
def index():
    return "Hello, world!"

@app.route('/user/<user_name>', methods=['GET', 'POST'])
def findUser(user_name=None):
    uName = request.args.get('user_name', user_name)
    user = User.query.filter({User.user_name:uName}).first()
    return jsonify(user)


##=====================================================================

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

当我去 localhost:5000/user/user1 它返回 null,我不确定我做错了什么?提前致谢!

参考帖子: MongoAlchemy 查询嵌入文档

Flask Value 错误查看函数没有返回响应

http://www.mongoalchemy.org/api/schema/document.html

4

0 回答 0