簡體   English   中英

如何將我的 flask 應用程序連接到 MongoDB(VSCode)?

[英]How to connect my flask app to MongoDB (VSCode)?

當我通過 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 %}

請你幫助我好嗎? 或者給我一些我可以學習更多的材料。 我整整一周都被困在這部分,我無法繼續前進。

mongo = PyMongo(app)更改為

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM