Python flask : No module named requests - python

I'm having trouble using requests module in my flask app. I have two files rest_server.py and independent.py at same directory level. The independent.py uses requests module and it executes correctly if I directly run it. But when I import independent.py in rest_server.py it shows following error
`
import independent
File "/home/satwik/Desktop/angelhack/independent.py", line 5, in <module>
import requests
ImportError: No module named requests`
I've tried pip install requests and it shows requirement already satisfied. Also I've tried to import requests in rest_server.py and found it to execute correctly too.
Here's my code
**independent.py **
`import json
import os
import sys
import requests
sys.path.append('/home/satwik/Desktop/angelhack/comprehensive_search')
** rest_server.py **
`#!flask/bin/python
import six
from flask import Flask, jsonify, abort, request, make_response, url_for
from flask.ext.httpauth import HTTPBasicAuth
import independent
app = Flask(__name__, static_url_path="")`
How should I fix this?

Why you get the "no module named ..." error
Your two files have one big difference: rest_server.py includes a shebang line, while independent.py doesn't.
When you say you directly execute the file independent.py, you type python independent.py (I'm assuming here, because you didn't specify that). That means you are executing with the system python interpreter, which will look for modules installed at system level. Systemwide you have the requests module installed, via pip install requests, so python finds it, imports the thing and happily runs your script.
When you execute the file rest_server.py, instead, you can do so calling the script's name: ./rest_server.py (assuming correct permissions settings). In this case, the first line #!flask/bin/python (the so called shebang line) instructs to use a different python interpreter, the one contained in the flask folder, which I assume contains a virtual environment.
You get the no module named requests because that module is not installed inside the flask virtual environment.
How you can fix the error
To fix the problem, just install the requests module inside the virtual environment.
You first activate the virtual environment and then install the module you need:
$ source flask/bin/activate
$ pip install requests
Then you can try execute ./rest_server.py again and the requests module should be properly imported.
For more on the shebang line: https://en.wikipedia.org/wiki/Shebang_(Unix)
For more on virtual environments: https://pypi.python.org/pypi/virtualenv

Whenever you do pip install <package>, it installs the package to a certain location. Add that location to the list of PATHs mentioned in your Environment Variables, and your problem will be solved.

hi i had same problem but i solved it :
after you activate venv env by this command . venv/bin/activate
in this env u can type pip install requests
or
in ur project directory u can open pyvenv.cfg and turn
include-system-site-packages = false
to
include-system-site-packages = true
:)

Related

How to import two files from different directories?

Try to run this file:
#!flask/bin/python
from flask import Flask, jsonify
#!/usr/bin/python
import psycopg2
And this return:
ImportError: No module named psycopg2
I have file with only psycopg2 and it is work. And I have another file with only flask and it is work too. But when I try to run file with both imports it crush.
How to fix it (include flask/bin/python and /usr/bin/python, that flask and psycopg2 work toogether)?
#! PATH is shebang and Unix/Linux use it for path for executor. (/path/to/script.py insted of python /path/to/script.py)
However, it might help to extend the path in which to look for packages.
Run for your extra enviroment (python bin) this:
# Example:
python -c "import PACKAGE; print(PACKAGE.__path__)"
# Psycopg2
python -c "import psycopg2; print(psycopg2.__path__)"
Output:
['/path/to/some/python/psycopg2']
(My output: /home/usr/miniconda3/envs/free/lib/python3.6/site-packages/psycopg2)
#!flask/bin/python
from flask import Flask, jsonify
import sys
sys.path.insert(0, '/path/to/some/python') # Without package name
import psycopg2
If you add a path with a package name, you must then be one level down, but beware, __init__.py files can edit paths through the "namespace" so it's not ideal. But you only work with the package itself. Without it, you work with packages that are available in that directory.
You have probably two different python installations running.
One in [some path]/flask/bin/python and one in /usr/bin/python. The modules are installed in different environments so you can not use them together.
To fix this install flask module in your 'main' python installation or install psycopg2 in your flask environment.
You need to install a package module.
In terminal execute:
pip install psycopg2
more information in PyPi - PSYCOPG2

Cookiecutter created directory giving me issues running development server and python shell

I created a django project using cookiecutter as reccomended by Two scoops of Django 1.8. It's called icecreamratings_project
I use the git cmd prompt and use
'cd icecreamratings_project'.
When i want to use the built-in python interpreter by using
python manage.py shell it gives me the following error.
File "C:\Users\Armando\Desktop\icecreamratings_project\config\settings\common.py", line 13, in
import environ
ImportError: No module named 'environ'
I looked into the directory and the following code is there:
from __future__ import absolute_import, unicode_literals
from sys import path
import environ
ROOT_DIR = environ.Path(__file__) - 3 # (/a/b/myfile.py - 3 = /)
APPS_DIR = ROOT_DIR.path('twoscoops_project')
env = environ.Env()
No module named environ exists, but I'm assuming environ is in reference to the virtual environment. Im not familiar with the cookiecutter documentation or how it creates django templates, but i created a virtual environment named environ.
The message i got after that is that there is no Path in environ. Can someone help?
The environ module can be found in django-environ.
django-environ is a requirement of cookiecutter-django's requirements/base.txt.
base.txt is a requirement of cookiecutter-django's requirements/local.txt.
It seems you'll install environ and other needed modules by completing the following steps from cookiecutter-django's README.rst:
Getting up and running
The steps below will get you up and running with a local development
environment. We assume you have the following installed:
pip
virtualenv
PostgreSQL
First make sure to create and activate a virtualenv, then open a
terminal at the project root and install the requirements for local
development:
$ pip install -r requirements/local.txt
Source: https://github.com/pydanny/cookiecutter-django#getting-up-and-running

Import Configurator Error for Python Pyramid

i'm trying to learn python pyramid for linux and following the pylonsproject documentation in doing so.I'm also new to linux.
I've installed everything correctly(I'm pretty sure), but when i invoke my helloworld.py, i got this following error
ImportError: No module named pyramid.config
the documentation says this should be the path to the file
$ /path/to/your/virtualenv/bin/python helloworld.py
but i'm confused as the python after the bin is a executable not a directory? my env is located in the Downloads folder
Thanks!
These symptoms are almost always a misuse of the virtualenv in one way or another.
1) Make sure you are running the virtualenv
$ env/bin/python helloworld.py
2) Make sure you installed pyramid into the virtualenv
$ env/bin/python
>>> import pyramid.config
# ImportError or not?

Can't import my own modules in Python

I'm having a hard time understanding how module importing works in Python (I've never done it in any other language before either).
Let's say I have:
myapp/__init__.py
myapp/myapp/myapp.py
myapp/myapp/SomeObject.py
myapp/tests/TestCase.py
Now I'm trying to get something like this:
myapp.py
===================
from myapp import SomeObject
# stuff ...
TestCase.py
===================
from myapp import SomeObject
# some tests on SomeObject
However, I'm definitely doing something wrong as Python can't see that myapp is a module:
ImportError: No module named myapp
In your particular case it looks like you're trying to import SomeObject from the myapp.py and TestCase.py scripts. From myapp.py, do
import SomeObject
since it is in the same folder. For TestCase.py, do
from ..myapp import SomeObject
However, this will work only if you are importing TestCase from the package. If you want to directly run python TestCase.py, you would have to mess with your path. This can be done within Python:
import sys
sys.path.append("..")
from myapp import SomeObject
though that is generally not recommended.
In general, if you want other people to use your Python package, you should use distutils to create a setup script. That way, anyone can install your package easily using a command like python setup.py install and it will be available everywhere on their machine. If you're serious about the package, you could even add it to the Python Package Index, PyPI.
The function import looks for files into your PYTHONPATH env. variable and your local directory. So you can either put all your files in the same directory, or export the path typing into a terminal::
export PYTHONPATH="$PYTHONPATH:/path_to_myapp/myapp/myapp/"
exporting path is a good way. Another way is to add a .pth to your site-packages location.
On my mac my python keeps site-packages in /Library/Python shown below
/Library/Python/2.7/site-packages
I created a file called awesome.pth at /Library/Python/2.7/site-packages/awesome.pth and in the file put the following path that references my awesome modules
/opt/awesome/custom_python_modules
You can try
from myapp.myapp import SomeObject
because your project name is the same as the myapp.py which makes it search the project document first
You need to have
__init__.py
in all the folders that have code you need to interact with.
You also need to specify the top folder name of your project in every import even if the file you tried to import is at the same level.
In your first myapp directory ,u can add a setup.py file and add two python code in setup.py
from setuptools import setup
setup(name='myapp')
in your first myapp directory in commandline , use pip install -e . to install the package
pip install on Windows 10 defaults to installing in 'Program Files/PythonXX/Lib/site-packages' which is a directory that requires administrative privileges. So I fixed my issue by running pip install as Administrator (you have to open command prompt as administrator even if you are logged in with an admin account). Also, it is safer to call pip from python.
e.g.
python -m pip install <package-name>
instead of
pip install <package-name>
In my case it was Windows vs Python surprise, despite Windows filenames are not case sensitive, Python import is. So if you have Stuff.py file you need to import this name as-is.
let's say i write a module
import os
my_home_dir=os.environ['HOME'] // in windows 'HOMEPATH'
file_abs_path=os.path.join(my_home_dir,"my_module.py")
with open(file_abs_path,"w") as f:
f.write("print('I am loaded successfully')")
import importlib
importlib.util.find_spec('my_module') ==> cannot find
we have to tell python where to look for the module. we have to add our path to the sys.path
import sys
sys.path.append(file_abs_path)
now importlib.util.find_spec('my_module') returns:
ModuleSpec(name='my_module', loader=<_frozen_importlib_external.SourceFileLoader object at 0x7fa40143e8e0>, origin='/Users/name/my_module.py')
we created our module, we informed python its path, now we should be able to import it
import my_module
//I am loaded successfully
This worked for me:
from .myapp import SomeObject
The . signifies that it will search any local modules from the parent module.
Short Answer:
python -m ParentPackage.Submodule
Executing the required file via module flag worked for me. Lets say we got a typical directory structure as below:
my_project:
| Core
->myScript.py
| Utils
->helpers.py
configs.py
Now if you want to run a file inside a directory, that has imports from other modules, all you need to do is like below:
python -m Core.myscript
PS: You gotta use dot notation to refer the submodules(Files/scripts you want to execute). Also I used python3.9+. So I didnt require neither any init.py nor any sys path append statements.
Hope that helps! Happy Coding!
If you use Anaconda you can do:
conda develop /Path/To/Your/Modules
from the Shell and it will write your path into a conda.pth file into the standard directory for 3rd party modules (site-packages in my case).
If you are using the IPython Console, make sure your IDE (e.g., spyder) is pointing to the right working directory (i.e., your project folder)
Besides the suggested solutions like the accepted answer, I had the same problem in Pycharm, and I didn't want to modify imports like the relative addressing suggested above.
I finally found out that if I mark my src/ (root directory of my python codes) as the source in Interpreter settings, the issue will be resolved.

Problem with Python modules

I'm uploading my first Django app to my Dreamhost server. My app uses xlwt package and since I can't install it in the default location ( /usr/lib/python2.3/site-packages/xlwt ), I installed it on another location by:
python setup.py install --home=$HOME
Then xlwt is installed here:
/home/myuser/lib/python/xlwt/
After that, I add this folder to de env var PYTHONPATH
export PYTHONPATH=$PYTHONPATH:/home/myuser/lib/python
... And in a python promt I can do this (without problems)
import xlwt
... But if I do the same thing in my app code, I have the follow error:
Could not import ISI.restaurante.views. Error was: No module named xlwt
[where ISI.restaurante.views is my code where I do the import]
Could u help me? Thanks!
PYTHONPATH may only be set when you run from the shell, you can set path programatically from python using
import sys
sys.path.append('/home/myuser/lib/python')

Categories