【问题标题】:How to connect my flask app to MongoDB (VSCode)?如何将我的烧瓶应用程序连接到 MongoDB(VSCode)?
【发布时间】:2021-12-28 13:52:52
【问题描述】:

当我通过 Heroku 部署它时,它工作得很好,但我在开发过程中看不到任何东西,因为我得到:

pymongo.errors.ServerSelectionTimeoutError: cluster0-shard-00-02.cxur9.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED]

我是一名学生,我的程序在 GitPod 上,而我使用 VS Code,因此他们无法帮助我。

所以我的 app.py 文件是这样的:

import os
from flask import (
    Flask, flash, render_template, 
    redirect, request, session, url_for)
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
if os.path.exists("env.py"):
    import env


app = Flask(__name__)

app.config["MONGO_DBNAME"] = os.environ.get("MONGO_DBNAME")
app.config["MONGO_URI"]  = os.environ.get("MONGO_URI")
app.secret_key = os.environ.get("SECRET_KEY")

mongo = PyMongo(app)


@app.route("/")
@app.route("/get_tasks")
def get_tasks():
    tasks = mongo.db.tasks.find()
    return render_template("tasks.html", tasks=tasks)


if __name__ == "__main__":
    app.run(
        host = os.environ.get("IP"),
        port = int(os.environ.get("PORT")),
        debug = True)

我的 env.py 是这样的:

import os


os.environ.setdefault("IP", "0.0.0.0")
os.environ.setdefault("PORT", "5000")
os.environ.setdefault("SECRET_KEY", "somesecretkey")
os.environ.setdefault("MONGO_URI", "mongodb+srv://root:password@cluster0.cxur9.mongodb.net/dbname?retryWrites=true&w=majority")
os.environ.setdefault("MONGO_DBNAME", "task_manager")

我还在根目录的 .vscode 文件夹中添加了 settings.json:

{   
    "terminal.integrated.env.windows": {
        "DEVELOPMENT": "1",
        "SECRET_KEY": "somesecretkey",
        "IP": "0.0.0.0",
        "PORT": "5000",
        "MONGO_URI": "mongodb+srv://root:password@cluster0.cxur9.mongodb.net/dbname?retryWrites=true&w=majority",
        "MONGO_DBNAME": "task_manager"
    }
}

最后这是我尝试在 html 正文中访问的方式:

{% for task in tasks %}
    {{ task.task_name }}<br>
    {{ task.category_name }}<br>
    {{ task.task_description }}<br>
    {{ task.due_date }}<br>
{% endfor %}

你能帮帮我吗?或者给我一些我可以学习更多的材料。我整整一周都被困在这部分,我无法继续前进。

【问题讨论】:

    标签: python mongodb flask


    【解决方案1】:

    mongo = PyMongo(app)更改为

    mongo = PyMongo(app, tls=True, tlsAllowInvalidCertificates=True)
    

    您可以在官方文档https://pymongo.readthedocs.io/en/stable/examples/tls.html找到更多信息

    【讨论】:

    • 哇,这正好解决了我的问题!非常感谢,我一定会阅读提供的链接。
    • 很高兴我能帮上忙。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 2019-07-19
    • 1970-01-01
    相关资源
    最近更新 更多