This is my tornado file::
from tornado.wsgi import WSGIContainer
from tornado.ioloop import IOLoop
from tornado.web import FallbackHandler, RequestHandler, Application
from flasky import app
class MainHandler(RequestHandler):
def get(self):
self.write("This message comes from Tornado ^_^")
tr = WSGIContainer(app)
application = Application([
(r"/tornado", MainHandler),
(r".*", FallbackHandler, dict(fallback=tr)),
])
if __name__ == "__main__":
application.listen(5000)
IOLoop.instance().start()
Basically I'm running a flask server in Tornado. But I'm getting this error:
from tornado.wsgi import WSGIContainer
ImportError: No module named 'tornado'
I've already gone through this post: Python Tornado: WSGI module missing?
But my file is not named Tornado.py so that doesn't apply to me.
Please help.
A common problem is having multiple Python interpreters, or multiple Python environments, installed. "pip" and "python" may use different environments. Try installing Tornado like this:
python -m pip install tornado
I got rid of this by using following command.
sudo python3 -m pip install tornado
I faced the issue while testing tornado for the first time. It was because I named the file as tornado.py (as also mentioned by Mohamed Abdelijelil). I renamed it to tornado_test.py and it worked.
check if tornado module is installed with pip and if you are using a virtualenv check if it's activated
Related
I am trying to use google OAuth for my web app. To do so I installed the packages google-api-python-client and google-auth in my venv and during my Docker build(from a requirements.txt). Despite this when I run my app it can't find the requests module, complaining that:
flask.cli.NoAppException: While importing "debateit", an ImportError was raised:
Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/google/auth/transport/requests.py", line 23, in <module>
import requests
ImportError: No module named 'requests'
The import is as follows:
from google.auth.transport import requests
and is used like:
idinfo = id_token.verify_oauth2_token(token, requests.Request(), app.config["GOOGLE_LOGIN_CLIENT_ID"])
Other imports such as the id_token.verify_oauth2_token work fine.
I checked my docker build and it says I have included google-auth correctly:
Installing collected packages: ... google-auth, httplib2, google-auth-httplib2, google-api-python-client
Successfully installed ... google-api-python-client-1.7.3 google-auth-1.5.0 google-auth-httplib2-0.0.3 httplib2-0.11.3 ...
I can clearly see the google.auth.transport.requests module when I look in the venv, it just doesn't work in the app itself.
What am I missing? What could cause this module to not be found?
So I found out what was wrong - within the google.auth.transport.requests module they try to import the library "requests". I did not have this library installed. I have done so and it works now.
The guide I was following: https://developers.google.com/identity/sign-in/web/backend-auth did not mention that you need to install this library. I misunderstood what the import for requests in the requests module was supposed to do.
As reported in the documentation, it should be more likely like:
import google.auth.transport.requests
import requests
request = google.auth.transport.requests.Request()
credentials.refresh(request)
But for your purpose I'll suggest:
from google.auth.transport.requests import Request
then change the following from:
idinfo = id_token.verify_oauth2_token(token, requests.Request(), app.config["GOOGLE_LOGIN_CLIENT_ID"])
to:
idinfo = id_token.verify_oauth2_token(token, Request(), app.config["GOOGLE_LOGIN_CLIENT_ID"])
It was an error because inside the path google.auth.transport.requests there is no function or class which is named requests.
My suggestion is based on the line
idinfo = id_token.verify_oauth2_token(token, requests.Request(), app.config["GOOGLE_LOGIN_CLIENT_ID"])
which show us that you use a class named Requests() which is present into google.auth.transport.requests as you can see in the documentation.
I know this was answered but you can quickly install those libraries globally by the running the command :
pip install google-auth
Here is how to install pip or installing the libraries in local virtual environment if someone doesn't want to install them globally:
https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/
pip install requests
It seems like google.auth.transport.requests uses requests.
trying to use the VM as a server to host some python code but it has a problem with the files import of 'firebase'
Output: ImportError: No module named firebase
Has anyone had this or anything like this before?
The file which I'm trying run the app from is (serveme.py):
from flask import Flask, request, render_template
from firebase import firebase
import json
import requests
import os.path
firebase = firebase.FirebaseApplication('https://***********.firebaseio.com/')
app = Flask(__name__)
#app.route('/')
def index():
return 'Method was %s' % request.method
#app.route('/firetest', methods=['GET', 'POST'])
etc etc. It has a problem with the import at line 2.
I am using gunicorn to do
gunicorn -w 2 -b :5000 serveme:app
You have to run
sudo easy_install pip
then you're able to do
sudo pip install requests
sudo pip install python-firebase
Python was already installed, apparently you have to install pip again, brew doesn't like multiple downloads of the same package. So use the easy install for just pip.
Hope this helps someone else if they ever come across this.
I'd like to have a python script which in the beginning create a virtual environment, install required modules (e.g. cherrypy) and then continues with the rest of the code.
What I found so far is as follow:
import os, virtualenv
HOME_DIRECTORY = "venv"
virtualenv.create_environment(HOME_DIRECTORY)
execfile(os.path.join(HOME_DIRECTORY, "bin", "activate_this.py"))
import pip
pip.main(["install", "--prefix", HOME_DIRECTORY, "cherrypy"])
import cherrypy
class Root(object):
#cherrypy.expose
def index(self):
return "Hello World!"
if __name__ == '__main__':
cherrypy.quickstart(Root(), '/')
The script creates virtual environment and install cherrypy (based on the log), but still I get ImportError: No module named cherrypy error.
I also tried the following, but got the same error:
import importlib
CHERRYPY = 'cherrypy'
try:
importlib.import_module(CHERRYPY)
except ImportError:
import pip
pip.main(["install", "--prefix", HOME_DIRECTORY, CHERRYPY])
finally:
globals()[CHERRYPY] = importlib.import_module(CHERRYPY)
Apart from the above problem, also, I'd like to know how to specify the python version (e.g. python 3.6) while creating virtual environment. Thanks.
For the record the issue was with the virtual environment activate (the line to execute activate_this.py). For Python 3 the following worked for me:
ACTIVATE_THIS = 'venv/bin/activate_this.py'
exec(Path(ACTIVATE_THIS).read_text(), dict(__file__ = ACTIVATE_THIS))
Trying to import safemine from cherrypy
from cherrypy import safemime
ImportError: cannot import name safemime
Cherrypy is installed with PIP ie.
sudo pip install -U cherrypy
According to cherrypy-users mailing list, safemime module was removed:
That module was removed in http://www.cherrypy.org/changeset/2319
because its functionality was folded into the new _cpreqbody.py
module.
I want to write a script to automatically setup a brand new ubuntu installation and install a django-based app. Since the script will be run on a new server, the Python script needs to automatically install some required modules.
Here is the script.
#!/usr/bin/env python
import subprocess
import os
import sys
def pip_install(mod):
print subprocess.check_output("pip install %s" % mod, shell=True)
if __name__ == "__main__":
if os.getuid() != 0:
print "Sorry, you need to run the script as root."
sys.exit()
try:
import pexpect
except:
pip_install('pexpect')
import pexpect
# More code here...
The installation of pexpect is success, however the next line import pexpect is failed. I think its because at runtime the code doesn't aware about the newly installed pexpect.
How to install and import Python modules at runtime? I'm open to another approaches.
You can import pip instead of using subprocess:
import pip
def install(package):
pip.main(['install', package])
# Example
if __name__ == '__main__':
try:
import pexpect
except ImportError:
install('pexpect')
import pexpect
Another take:
import pip
def import_with_auto_install(package):
try:
return __import__(package)
except ImportError:
pip.main(['install', package])
return __import__(package)
# Example
if __name__ == '__main__':
pexpect = import_with_auto_install('pexpect')
print(pexpect)
[edit]
You should consider using a requirements.txt along with pip. Seems like you are trying to automate deployments (and this is good!), in my tool belt I have also virtualenvwrapper, vagrant and ansible.
This is the output for me:
(test)root#vagrant:~/test# pip uninstall pexpect
Uninstalling pexpect:
/usr/lib/python-environments/test/lib/python2.6/site-packages/ANSI.py
/usr/lib/python-environments/test/lib/python2.6/site-packages/ANSI.pyc
/usr/lib/python-environments/test/lib/python2.6/site-packages/FSM.py
/usr/lib/python-environments/test/lib/python2.6/site-packages/FSM.pyc
/usr/lib/python-environments/test/lib/python2.6/site-packages/fdpexpect.py
/usr/lib/python-environments/test/lib/python2.6/site-packages/fdpexpect.pyc
/usr/lib/python-environments/test/lib/python2.6/site-packages/pexpect-2.4-py2.6.egg-info
/usr/lib/python-environments/test/lib/python2.6/site-packages/pexpect.py
/usr/lib/python-environments/test/lib/python2.6/site-packages/pexpect.pyc
/usr/lib/python-environments/test/lib/python2.6/site-packages/pxssh.py
/usr/lib/python-environments/test/lib/python2.6/site-packages/pxssh.pyc
/usr/lib/python-environments/test/lib/python2.6/site-packages/screen.py
/usr/lib/python-environments/test/lib/python2.6/site-packages/screen.pyc
Proceed (y/n)? y
Successfully uninstalled pexpect
(test)root#vagrant:~/test# python test.py
Downloading/unpacking pexpect
Downloading pexpect-2.4.tar.gz (113Kb): 113Kb downloaded
Running setup.py egg_info for package pexpect
Installing collected packages: pexpect
Running setup.py install for pexpect
Successfully installed pexpect
Cleaning up...
<module 'pexpect' from '/usr/lib/python-environments/test/lib/python2.6/site-packages/pexpect.pyc'>
(test)root#vagrant:~/test#
For those who are using pip version greater than 10.x, there is no main function for pip so the alternative approach is using import pip._internal as pip instead of import pip like :
Updated answer of Paulo
import pip._internal as pip
def install(package):
pip.main(['install', package])
if __name__ == '__main__':
try:
import pexpect
except ImportError:
install('pexpect')
import pexpect
I actually made a module for this exact purpose (impstall)
It's really easy to use:
import impstall
impstall.now('pexpect')
impstall.now('wx', pipName='wxPython')
Github link for issues/contributions
I solved my problem using the imp module.
#!/usr/bin/env python
import pip
import imp
def install_and_load(package):
pip.main(['install', package])
path = '/usr/local/lib/python2.7/dist-packages'
if path not in sys.path:
sys.path.append(path)
f, fname, desc = imp.find_module(package)
return imp.load(package, f, fname, desc)
if __name__ == "__main__":
try:
import pexpect
except:
pexpect = install_and_load('pexpect')
# More code...
Actually the code is less than ideal, since I need to hardcode the Python module directory. But since the script is intended for a known target system, I think that is ok.
I had the same issue but none of Google's searches helped. After hours debugging, I found that it may be because the sys.path is not reloaded with new installation directory.
In my case on my Ubuntu Docker, I want to import dns.resolver at runtime for Python3.8 (pre-installed). I also created ubuntu user and run all things with this user (including my Python script).
Before installing, sys.path doesn't have /home/ubuntu/.local/lib/python3.8/site-packages since I didn't install anything.
While installing with subprocess or pip.main like above, it creates /home/ubuntu/.local/lib/python3.8/site-packages (as user installation).
After installing , the sys.path should be refreshed to include this new location.
Since the sys.path is managed by site module, we should reload it (ref HERE):
import site
from importlib import reload
reload(site)
The full block for anyone that needs:
import subprocess
import sys
try:
import dns.resolver
except ImportError:
subprocess.check_call([sys.executable, "-m", "pip", "install", "dnspython"])
import site
from importlib import reload
reload(site)
import dns.resolver
I'm not Python developer so these code can be simplify more. This may help in cases such as fresh CI/CD environment for DevOps engineers like me.