Python Flask Pymongo 全局 db 对象返回为 None。

huangapple go评论71阅读模式
英文:

Python Flask Pymongo global db object is returned as None

问题

I am trying to create an API to fetch data from my Atlas MongoDB using Flask. I was following this tutorial https://www.mongodb.com/compatibility/setting-up-flask-with-mongodb

However I get the following Error when trying to get some data from my database:

  File "C:\Users\salad\PycharmProjects\crypto_project\crypto\db.py", line 59, in get_currencies
    total_num_currencies = db.prices.count_documents(pipeline[0])
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'prices'

This is how I create the global db:

def get_db():
    """Configuration method to return db instance"""

    # All database access is routed through the global “db” object initializing the PyMongo client.
    db = getattr(g, "coin_markets", None)  # is equivalent to g._database

    if db is None:
        # The special variable object “g” is used here to define the PyMongo database in the global application context.
        db = g.coin_markets = PyMongo(current_app).db

    return db

db = LocalProxy(get_db)

In my run.py, I configure the app to use my variable in .env which contains the connection string to my MongoDB:

from crypto.factory import create_app

from crypto.credentials.creds import DB_CONNECTION

if __name__ == "__main__":
    app = create_app()
    app.config['DEBUG'] = True
    app.config['MONGO_URI'] = DB_CONNECTION

    app.run()

If I print app.config['MONGO_URI'], I get the connection string, so I don't understand why I get NoneType.

If it helps, I use a factory pattern to create the app:

import os

from flask import Flask, render_template
from flask.json import JSONEncoder
from flask_cors import CORS

from bson import json_util, ObjectId
from datetime import datetime, timedelta

from crypto.api.currencies import currencies_api_v1

def create_app():

    app = Flask(__name__)
    CORS(app)

    app.register_blueprint(currencies_api_v1)

    @app.route('/', defaults={'path': ''})
    @app.route('/<path:path>')
    def serve(path):
        return render_template('index.html')

    return app
英文:

I am trying to create an API to fetch data from my Atlas MongoDB using Flask. I was following this tutorial https://www.mongodb.com/compatibility/setting-up-flask-with-mongodb

However I get the following Error when trying to get some data from my database:

  File &quot;C:\Users\salad\PycharmProjects\crypto_project\crypto\db.py&quot;, line 59, in get_currencies
    total_num_currencies = db.prices.count_documents(pipeline[0])
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: &#39;NoneType&#39; object has no attribute &#39;prices&#39;

this is how I create the global db:

def get_db():
    &quot;&quot;&quot;Configuration method to return db instance&quot;&quot;&quot;

    # All database access is routed through the global “db” object initialising the PyMongo client.
    db = getattr(g, &quot;coin_markets&quot;, None)  # is equivalent to g._database

    if db is None:
        # The special variable object “g” is used here to define the PyMongo database in the global application context.
        db = g.coin_markets = PyMongo(current_app).db

    return db

db = LocalProxy(get_db)

In my run.py I config the app to use my variable in .env which contains the connection string to my mongodb:

from crypto.factory import create_app

from crypto.credentials.creds import DB_CONNECTION


if __name__ == &quot;__main__&quot;:
    app = create_app()
    app.config[&#39;DEBUG&#39;] = True
    app.config[&#39;MONGO_URI&#39;] = DB_CONNECTION

    app.run()

if I print app.config[&#39;MONGO_URI&#39;] I get the connection string so I don't understand why I get NoneType.

if it helps I use a factory pattern to create the app:

import os

from flask import Flask, render_template
from flask.json import JSONEncoder
from flask_cors import CORS

from bson import json_util, ObjectId
from datetime import datetime, timedelta

from crypto.api.currencies import currencies_api_v1

def create_app():

    app = Flask(__name__)
    CORS(app)

    app.register_blueprint(currencies_api_v1)

    @app.route(&#39;/&#39;, defaults={&#39;path&#39;: &#39;&#39;})
    @app.route(&#39;/&lt;path:path&gt;&#39;)
    def serve(path):
        return render_template(&#39;index.html&#39;)

    return app

答案1

得分: 1

在rickhg12hs的帮助下,问题得以解决。我没有在我的连接字符串中指定数据库,这就是为什么PyMongo(current_app).db不起作用的原因。如果你不想像我一样在连接字符串中添加数据库名称,你可以使用rickhg12hs的建议PyMongo(current_app).cx['your_database_name']

英文:

So with rickhg12hs help the problem got solved. I didn't specify a database in my connection string that's why PyMongo(current_app).db was not working. If you don't want to add the database name to your connection string like me, you can use rickhg12hs suggestion PyMongo(current_app).cx[&#39;your_database_name&#39;]

huangapple
  • 本文由 发表于 2023年3月4日 06:17:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75632314.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定