Python flask : No module named requests
Question: 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?


Answer: # 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>

