Home > Enterprise >  How to connect my flask app to MongoDB (VSCode)?
How to connect my flask app to MongoDB (VSCode)?

Time:11-18

When I deploy it through Heroku it works just fine, but I cannot see anything during development because I get:

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

I am a student, and my programme is on GitPod, while I use VS Code and they aren't able to help me because of that.

So my app.py file is this:

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)

My env.py is like this:

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:[email protected]/dbname?retryWrites=true&w=majority")
os.environ.setdefault("MONGO_DBNAME", "task_manager")

I also added settings.json in .vscode folder at the root:

{   
    "terminal.integrated.env.windows": {
        "DEVELOPMENT": "1",
        "SECRET_KEY": "somesecretkey",
        "IP": "0.0.0.0",
        "PORT": "5000",
        "MONGO_URI": "mongodb srv://root:[email protected]/dbname?retryWrites=true&w=majority",
        "MONGO_DBNAME": "task_manager"
    }
}

And at the end this is how I try to access in html body:

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

Could you please help me? Or give me some kind of materials that I can learn more. I am stuck on this part for entire week and I just cannot move on.

CodePudding user response:

Change mongo = PyMongo(app) to

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

You can find more information at official documentation https://pymongo.readthedocs.io/en/stable/examples/tls.html

  • Related