ModuleNotFoundError: No module named 'flask_session' - python

I have a simple python file that I am trying to set up to utilize sessions, when i run the file I am receiving the error below:
ModuleNotFoundError: No module named 'flask_session'
I believe I am importing the module properly, is there anything else that I can check to set this up properly?
from flask import Flask, render_template, request, session
from flask_session import Session
app = Flask(__name__)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
#app.route("/", methods=["GET", "POST"])
def index():
if session.get("notes") is None:
session["notes"] = []
if request.method == "POST":
note = request.form.get("note")
session["notes"].append(note)
return render_template("index.html", notes=notes)
Here is the traceback ( most recent call last )
File "c:\python37\lib\site-packages\flask\cli.py", line 325, in __call__
Open an interactive python shell in this frameself._flush_bg_loading_exception()
File "c:\python37\lib\site-packages\flask\cli.py", line 313, in _flush_bg_loading_exception
reraise(*exc_info)
File "c:\python37\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "c:\python37\lib\site-packages\flask\cli.py", line 302, in _load_app
self._load_unlocked()
File "c:\python37\lib\site-packages\flask\cli.py", line 317, in _load_unlocked
self._app = rv = self.loader()
File "c:\python37\lib\site-packages\flask\cli.py", line 372, in load_app
app = locate_app(self, import_name, name)
File "c:\python37\lib\site-packages\flask\cli.py", line 242, in locate_app
'\n\n{tb}'.format(name=module_name, tb=traceback.format_exc())

I've first encountered this problem while doing Harvard's CS50x class. I'm using Linux and I've been using Python3, as it turns out I've installed Flask-Session for Python2.
I don't know whether it also applies to Mac but I used the following instead:
$ pip3 install flask-session
Then you can check whether it's installed with pip's freeze command. After doing this my pylint in VSCode no longer gave an error.

I got the flask_session module not found a number of times and it took me 2 hours to find a fix after thousands of attempts. Well, I too visited a number of sites looking for a solution but didn't get any. I got this error while I was learning the online course cs50 web development on edx.org by Harvard and when I read the forum discussion on reddit I saw comments where they mentioned Harvard used a special server to make it work and I felt the pain of not going to Harvard but two hours later I'm screaming because I just found a solution that's no where on the internet.
You should not use from flask_session import Session
Instead use from flask_session.__init__ import Session
I cannot explain the terminology as to why we do this here but you can private message me if you want to understand why we do this. Happy Coding!

Be sure to have the extension installed:
pip install Flask-Session
oficial page with instructions
If you get the error "ModuleNotFoundError: No module named 'werkzeug.contrib'":
pip install werkzeug==0.16.0
The latest version is the 1.0.1 but only the 0.16.0 worked.
(where I found this solution) (official page)

simply goto terminal and type pip install flask_session , wait for installation, once done you are good to go. ( Also many other solutions do not work, look for red highlighted part in image. Once installed it works properly.)

I ran into the same error.
The following worked for me.
Install the extension with the following command:
$ easy_install Flask-Session
or alternatively, if you have pip installed:
$ pip install Flask-Session

I got it for windows:
There's no the library "flask_session" (--is a directory--) in your directory ...venv\Lib\site-packages (virtual environment)
You just need copy it from C:\Users\your _user\AppData\Local\Programs\Python\Python37-32\Lib\site-packages
and then paste it in venv\Lib\site-packages or where you have installed your virtual environment. Thats it and sorry for my english, greetings from Medellin Colombia.

Try to do following command instead of all go to terminal and type
$ easy_install Flask-Session
If it shows an error,use sudo before it , If it shows any error please let me know also feel free to upvote

Install the extension first using the following command $ pip install Flask-Session. You can read more on flask-session via https://pythonhosted.org/Flask-Session/

For completeness, I will share my solution:
In my case installed everything with pip3 to make it work with python 3.7, only worked with vscode after uninstalling python 2 from the system and reopening vscode.

Are you using this library? https://pythonhosted.org/Flask-Session/
The docs suggest importing it this way: from flask.ext.session import Session

Related

Basic Flask Issue w/ Importing

I'm following a Flask tutorial and am getting an import error. I have a file called run.py which contains:
from app import app
app.run(debug = True)
When I run ./run.py, I get:
Traceback (most recent call last):
File "./run.py", line 2, in <module>
from app import app
File "/Users/myName/Desktop/SquashScraper/app/__init__.py", line 1, in <module>
from flask import Flask
ImportError: cannot import name Flask
This seems similar to this issue: http://stackoverflow.com/questions/26960235/python3-cannot-import-name-flask
So I attempted the checked solution by running:
virtualenv -p /usr/bin/python3 my_py3_env
Unfortunately, I get:
The executable /usr/bin/python3 (from --python=/usr/bin/python3) does not exist
Any ideas what may be happening here?
Thanks for the help,
bclayman
If you want your virtual environment to be Python 3 but don't know the installation directory, use which python3. Use that directory in your virtualenv -p [directory] my_py3_env command to set up the Python 3 virtual environment.
I sounds like your pip is installing to your Python 2.X directory. If you're okay with that, you'll need to run the app either with python2 run.py, python2.X run.py where x is your installed version, or change the symlink of python in /usr/bin/python to your installation of Python 2.
This question has some more information.
Regardless of the version of Python that you wish to use, you will need to install Flask to that version of Python. See this question for that.

Did I give a virus to my Django? manage.py disappearing

My Django installation is falling a part - could I have a virus?
I recently installed : https://github.com/chrisdev/django-pandas/
using pip and now very scary things are happening:
my manage.py in the root directory clears after every execution
even when I rename it something else, the starting script becomes a blank file
The admin section of the app wont run at all. I get errors
like:
[06/Feb/2015 06:27:48] "GET /admin/ HTTP/1.1" 200 4308
Exception happened during processing of request from ('127.0.0.1', 51159)
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 295, in _handle_request_noblock
self.process_request(request, client_address)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 601, in process_request
t = threading.Thread(target = self.process_request_thread,
AttributeError: 'NoneType' object has no attribute 'Thread'
What is really confusing is I had to comment out a settings line pertaining to “SessionAuthenticationMiddleware” or I get this
File "/Users/rpanos/.virtualenvs/JiraStat_Local_JB/lib/python2.7/site-packages/django/utils/module_loading.py", line 31, in import_by_path
error_prefix, module_path, class_name))
ImproperlyConfigured: Module "django.contrib.auth.middleware" does not define a "SessionAuthenticationMiddleware" attribute/class
Why would that suddenly be necessary?
If any one has any idea how these things are happening, please let me know.
I already did a pip uninstall on django-pandas but I imagine there could be some nefarious remnant doing this?
My sincere apologies if django-pandas has nothing to do with this but my django install has been working great for a year and now all is going to crap!
Just in case another package might be the issue, please see my virtual environement here:
(JiraStat_Local_JB)Rs-Mac-mini:JiraStats rXXXXs$ lssitepackages
Django-1.6.10-py2.7.egg-info lxml-3.4.0-py2.7.egg-info queuelib
OpenSSL model_utils queuelib-1.2.2-py2.7.egg-info
Scrapy-0.24.4-py2.7.egg-info numpy requests
Twisted-14.0.2-py2.7.egg-info numpy-1.9.0-py2.7.egg-info requests-2.4.3-py2.7.egg-info
_cffi_backend.so oauthlib requests_oauthlib
_markerlib oauthlib-0.6.3-py2.7.egg-info requests_oauthlib-0.4.1-py2.7.egg-info
cffi pandas scrapy
cffi-0.8.6-py2.7.egg-info pandas-0.14.1-py2.7.egg-info setuptools
cryptography pip setuptools-1.1.5-py2.7.egg-info
cryptography-0.6-py2.7.egg-info pip-1.4.1-py2.7.egg-info six-1.8.0-py2.7.egg-info
cssselect pkg_resources.py six.py
cssselect-0.9.1-py2.7.egg-info pkg_resources.pyc six.pyc
dateutil psycopg2 tlslite
django psycopg2-2.5.4-py2.7.egg-info tlslite-0.4.6-py2.7.egg-info
django_model_utils-2.2-py2.7.egg-info pyOpenSSL-0.14-py2.7.egg-info twisted
easy_install.py pycparser w3lib
easy_install.pyc pycparser-2.10-py2.7.egg-info w3lib-1.10.0-py2.7.egg-info
jira python_dateutil-2.2-py2.7.egg-info zope
jira-0.32-py2.7.egg-info pytz zope.interface-4.1.1-py2.7-nspkg.pth
lxml pytz-2014.7-py2.7.egg-info zope.interface-4.1.1-py2.7.egg-info
UPDATE
django-pandas did downgrade my Django and that solved a couple problems. Thank you Alasdair and Bernhard! However, there seems to be another issue.
I had two poorly formed packages - ones that I made by hand because I thought I knew what I was doing - when I remove them, all of the issues with the manage.py script go away. I usually trust PyCharm to do it, but these two I just copied the init files from another directory an started coding.
I have replaced and removed both of them to test this theory and its pretty solid.
Could any of you Django experts guess why a bad package would cause Django to crash AND delete its own manage.py?
It was still deleting "itself" after I re-upgraded Django.
Installing django-pandas most likely downgraded your Django installation as it explicitly requires Django < 1.7.
SessionAuthenticationMiddleware was added in Django 1.7. The traceback suggests that you may have Django 1.6 or earlier installed.

Tornado Error In database.py line 58 - NameError global name 'CONVERSIONS' is not defined

I'm trying to run the Tornado Demo 'Blog'. I've changed the database options in the blog.py file. but when i try to run the blog.py file i get the following error!!
blog.py file link
database.py file link
What needs to be done to get past this error??
I met the same problem. If you're using Ubuntu, try "sudo apt-get install python-MySQLdb"
Install MySQLdb (required by tornado.database).

Import error in twilio

I am having the same problem as this thread regarding twilio-python:
twilio.rest missing from twilio python module version 2.0.8?
However I have the same problem but I have 3.3.3 installed. I still get "No module named rest" when trying to import twilio.rest.
Loading the library from stand alone python script works. So I know that pip installing the package worked.
from twilio.rest import TwilioRestClient
def main():
account = "xxxxxxxxxxxxxxxx"
token = "xxxxxxxxxxxxxxxx"
client = TwilioRestClient(account, token)
call = client.calls.create(to="+12223344",
from_="+12223344",
url="http://ironblanket.herokuapp.com/",
method="GET")
if __name__ == "__main__":
main()
but this does not work:
from twilio.rest import TwilioRestClient
def home(request):
client = TwilioRestClient(account, token)
Do you have any idea what I can try next?
I named a python file in my project twilio.py. Since that file was loaded first, then subsequent calls to load twilio would reference that file instead of the twilio library.
TLDR: just don't name your python file twilio.py
Check which versions of pip and python you are running with this command:
which -a python
which -a pip
pip needs to install to a path that your Python executable can read from. Sometimes there will be more than one version of pip like pip-2.5, pip-2.7 etc. You can find all of them by running compgen -c | grep pip. There can also be more than one version of Python, especially if you have Macports or brew or multiple versions of Python installed.
Check which version of the twilio module is installed by running this command:
$ pip freeze | grep twilio # Or pip-2.7 freeze etc.
The output should be twilio==3.3.3.
I hope that helps - please leave a comment if you have more questions.
This Worked For me : (Windows)
Python librarys are in G:\Python\Lib
(Python is installed at G:, it might be different for you)
Download Twilio from github at paste the library at >> G:\Python\Lib <<
import problem gone :)
I had the same issue and it drove me crazy. Finally I figured it out. When you get the error:
AttributeError: module 'twilio' has no attribute 'version'
Look 2 lines above and the error is telling you where it expects to find the twilio file. So I moved it from where it was to where it was asking it to be.
Installed to:
c:\users\rhuds\appdata\local\programs\python\python37-32\lib\site-packages
Moved it to:
Traceback (most recent call last):
File "", line 1, in
import twilio
File "C:\Users\rhuds\AppData\Local\Programs\Python\Python37-32\twilio.py", line 2, in
Now I can import twilio. Besides that, the only other thing I did was uninstall old versions of Python, but I don't think that really mattered.

How can I use Django with MySQL in MAMP stack?

I have difficulty especially in installing MySQLdb module (MySQL-python-1.2.3c1), to connect to the MySQL in MAMP stack.
I've done a number of things such as copying the mysql include directory and library (including plugin) from a fresh installation of mysql (version 5.1.47) to the one inside MAMP (version 5.1.37).
Now, the MySQLdb module build and install doesnt give me error.
The error happens when I'm calling 'import MySQLdb' from python shell (version 2.6).
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "build/bdist.macosx-10.6-universal/egg/MySQLdb/__init__.py", line 19, in <module>
File "build/bdist.macosx-10.6-universal/egg/_mysql.py", line 7, in <module>
File "build/bdist.macosx-10.6-universal/egg/_mysql.py", line 6, in __bootstrap__
ImportError: dlopen(/Users/rhenru/.python-eggs/MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so, 2): Symbol not found: _mysql_affected_rows
Referenced from: /Users/rhenru/.python-eggs/MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so
Expected in: flat namespace
in /Users/rhenru/.python-eggs/MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so
Any idea, what else do I need to do to make it works?
Thanks a bunch,
Robert
=========
Add the system response after using virtualenv as suggested by Hank Gay below...
(MyDjangoProject)MyMacPro:MyDjangoProject rhenru$ which python
/Users/rhenru/Workspace/django/MyDjangoProject/bin/python
After I run python in virtualenv, importing MySQLdb:
>>> import MySQLdb
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "build/bdist.macosx-10.6-universal/egg/MySQLdb/__init__.py", line 19, in <module>
File "build/bdist.macosx-10.6-universal/egg/_mysql.py", line 7, in <module>
File "build/bdist.macosx-10.6-universal/egg/_mysql.py", line 6, in __bootstrap__
ImportError: dlopen(/Users/rhenru/.python-eggs/MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so, 2): Symbol not found: _mysql_affected_rows
Referenced from: /Users/rhenru/.python-eggs/MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so
Expected in: flat namespace
in /Users/rhenru/.python-eggs/MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so
import sys and sys.path
>>> import sys
>>> print sys.path
['', '/Users/rhenru/Workspace/django/MyDjangoProject/lib/python2.6/site-packages/distribute-0.6.10-py2.6.egg', '/Users/rhenru/Workspace/django/MyDjangoProject/lib/python2.6/site-packages/pip-0.7.1-py2.6.egg', '/Users/rhenru/Workspace/django/MyDjangoProject/lib/python26.zip', '/Library/Python/2.6/site-packages/PyXML-0.8.4-py2.6-macosx-10.6-universal.egg', '/Library/Python/2.6/site-packages/pydot-1.0.2-py2.6.egg', '/Library/Python/2.6/site-packages/pyparsing-1.5.2-py2.6.egg', '/Library/Python/2.6/site-packages/vobject-0.8.1c-py2.6.egg', '/Library/Python/2.6/site-packages/pytz-2010h-py2.6.egg', '/Library/Python/2.6/site-packages/MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg', '/Library/Python/2.6/site-packages/distribute-0.6.12-py2.6.egg', '/Library/Python/2.6/site-packages/pip-0.7.1-py2.6.egg', '/Users/rhenru/Workspace/django/MyDjangoProject/lib/python2.6', '/Users/rhenru/Workspace/django/MyDjangoProject/lib/python2.6/plat-darwin', '/Users/rhenru/Workspace/django/MyDjangoProject/lib/python2.6/plat-mac', '/Users/rhenru/Workspace/django/MyDjangoProject/lib/python2.6/plat-mac/lib-scriptpackages', '/Users/rhenru/Workspace/django/MyDjangoProject/Extras/lib/python', '/Users/rhenru/Workspace/django/MyDjangoProject/lib/python2.6/lib-tk', '/Users/rhenru/Workspace/django/MyDjangoProject/lib/python2.6/lib-old', '/Users/rhenru/Workspace/django/MyDjangoProject/lib/python2.6/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages', '/Users/rhenru/Workspace/django/MyDjangoProject/lib/python2.6/site-packages', '/Library/Python/2.6/site-packages', '/Library/Python/2.6/site-packages/PIL', '/Library/Python/2.6/site-packages/setuptools-0.6c11-py2.6.egg-info', '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/PyObjC', '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/wx-2.8-mac-unicode']
How are you installing MySQL-Python? I just tested in a fresh virtualenv and pip install mysql-python seems to have done the trick.
UPDATE:
pip is sort of like a package manager for Python packages.
By default, pip installs to your current site-packages directory, which is on your $PYTHONPATH. This lets other libraries/applications (like Django) access it. pip also works well with virtualenv (it should; Ian Bicking wrote them both), which is a nifty library that lets you sandbox an application. This is nice because it means you can try out new things without polluting (or even needing write access to) the global site-packages directory.
It probably seems like yak-shaving right now, but I'd say it's worth the effort to get up to speed on pip and virtualenv (you may also want to look into virtualenvwrapper, but we'll skip that for now; it's just sugar for virtualenv). It will lead to a slightly more complicated deployment scenario than putting everything in the global site-packages, but for development it's really no harder, and there are lots of good guides to deploying using a virtualenv.
I'd recommend something like the following:
curl -0 http://python-distribute.org/distribute_setup.py
python distribute_setup.py
easy_install pip
pip install virtualenv
virtualenv --distribute MyDjangoProject --no-site-packages
cd MyDjangoProject
source bin/activate (this activates the sandbox that virtualenv created)
pip install django mysql-python
At this point, you should have a totally functional Django+MySQL install (if I missed any steps, just comment and I'll try to add it in). You can start your Django project like this: django-admin.py startproject MyDjangoProject. cd into your project's directory, edit your settings.py file to point to your MySQL database, and run the dev server to test it out like so: ./manage.py runserver (you may need to chmod u+x your manage.py file). Voila! You should be able to access your site on localhost:8000. When you're done working on the project, you can just use deactivate to exit the virtualenv sandbox.
Try not to hold all this against Django: a lot of it is just best practices stuff for working with Python libraries. You could get by with a lot less, but this way it's more reproducible and you're less likely to accidentally mess up one of this project's dependencies when working on a different project.
I had this problem and it turned out to be due to an errant configuration:
export VERSIONER_PYTHON_PREFER_32_BIT=yes
I can't recall what I had this enabled for (some package that required 32-bit), probably related to Google AppEngine. But Setting it to 'no' solved by issues.
Otherwise I just installed everything using homebrew and pip.

Categories