pythonflaskpymongopython-venvflask-cors

Issues getting Flask-PyMongo and Flask-Cors to work in my venv


I just started the app with the following code:

 from flask import Flask, request, jsonify
 from flask_pymongo import PyMongo, ObjectId
 from flask_cors import CORS

app = Flask(__name__)
app.config["MONGO_URI"]="mongodb://localhost/crudapp"
mongo = PyMongo(app)

CORS(app)

db = mongo.db.users

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

In my explorer I have something like:

>Project Folder
  >Backend
    >src
      app.py
    >venv

I'm getting the same error for these two lines:

from flask_pymongo import PyMongo, ObjectID
from flask_cors import CORS

It says 'Import "flask_pymongo" could not be resolved' and 'Import "flask_cors" could not be resolved from source.' I tried reinstalling it within the venv and globally, nothing worked. I did some digging and found a post on reddit where someone said they solved this by pressing Shift+Command+P, finding the interpreter for Python and changing it to one following the path of the virtual environment. I tried that, and found two alternative interpreters to use, neither of them worked. I'm out of ideas.

EDIT: If it matters, the file path for the site-packages is:

Project Folder > Backend > venv > lib > python 3.9 > site-packages

Any help would be greatly appreciated!


Solution

  • I got it by restarting the project from scratch and following a tutorial for setting up a virtual environment in mac (the tutorial I was originally watching was on windows, not sure if that made a difference). Anyway, heres what I did. In terminal first:

    python3 -m venv venv
    

    then:

    source venv/bin/activate
    

    then:

    pip install Flask Flask-PyMongo Flask-Cors
    

    Finally, I typed Shift+Command+P select interpreter and ./venv/bin/python

    It works! I hope this can help someone else one day.