Tuesday, February 1, 2022

[SOLVED] Cannot import new modules into venv project

Issue

This is my first time working with a virtual environment so I'm not sure I'm doing anything right. I've followed the setup guide in the "flask mega tutorial"

$ python3 -m venv flask
$ flask/bin/pip3 install flask
$ flask/bin/pip3 install flask-login
$ flask/bin/pip3 install flask-openid
$ flask/bin/pip3 install flask-mail
$ flask/bin/pip3 install flask-sqlalchemy
$ flask/bin/pip3 install sqlalchemy-migrate
$ flask/bin/pip3 install flask-whooshalchemy
$ flask/bin/pip3 install flask-wtf
$ flask/bin/pip3 install flask-babel
$ flask/bin/pip3 install guess_language
$ flask/bin/pip3 install flipflop
$ flask/bin/pip3 install coverage

And everything worked fine. Until I realized I needed a new package (two of them actually, yaml and requests) I installed them like I normally would, outside of the virtual environment, with pip3 install packagename

I can import the packages in any other python file, I can import them in the ipython3 shell, but I cannot import them in my flask project. If I place them in views.py and then execute ./run.py

I get the error

ImportError: No module named 'yaml'

I've tried installing them again with apt-get but nothing changes.

my flask files are as follows:

run.py

#!flask/bin/python3
from app import app
app.run(debug=True)

__ init __.py

from flask import Flask

app = Flask(__name__)
app.config.from_object('config')

from app import views

veiws.py

from flask import Flask, render_template, request, session, redirect, url_for
from app import app
import time, os, subprocess
import yaml

## other stuff that works until I try to import yaml or any new package

Solution

You are not able to import the modules since they are not installed in the virtualenv flask that you created. Solve this by installing it in the same way as the other flask modules, ie. following your approach:

$ python3 -m venv flask
$ flask/bin/pip3 install flask
$ flask/bin/pip3 install flask-login
$ flask/bin/pip3 install flask-openid
$ flask/bin/pip3 install flask-mail
$ flask/bin/pip3 install flask-sqlalchemy
$ flask/bin/pip3 install sqlalchemy-migrate
$ flask/bin/pip3 install flask-whooshalchemy
$ flask/bin/pip3 install flask-wtf
$ flask/bin/pip3 install flask-babel
$ flask/bin/pip3 install guess_language
$ flask/bin/pip3 install flipflop
$ flask/bin/pip3 install coverage
$ flask/bin/pip3 install yaml
$ flask/bin/pip3 install requests


Answered By - J.R.
Answer Checked By - Terry (WPSolving Volunteer)