Apache making python acting differently - python

I am working on a IoT project. I am using flask and apache2. When I to run the program, I get errors with it trying to use the modules. I tried the following Reinstalling the module to other versions, Adding PYTHONPATH, and expanding the python code search directory. The latter seemed to yield the best results. The former would do nothing (adding the PYTHONPATH) or adding the directory in the wsgi file would cause it to error in function calls in the module or other modules (like flask.py).
I am now getting issues in module call. It works separately when not in apache, but i get the following error in my apache2 log
[wsgi:error] [pid 22380:tid 3048207360] [client 192.168.1.10:62280] File "/usr/local/lib/python3.7/dist-packages/pigpio_dht/dht11.py", line 24, in __init__
[wsgi:error] [pid 22380:tid 3048207360] [client 192.168.1.10:62280] super(DHT11, self).__init__(gpio, pi=pi, timeout_secs=timeout_secs, use_internal_pullup=True, max_read_rate_secs=1, datum_byte_count=1)
[wsgi:error] [pid 22380:tid 3048207360] [client 192.168.1.10:62280] TypeError: super() argument 1 must beust be type, not classobj
Here is my python code
import sys
sys.path.append('/usr/local/lib/python3.7/dist-packages/')
sys.path.append('/usr/lib/python3/dist-packages/')
from pigpio_dht import DHT11
from flask import Flask, redirect, url_for, render_template, request, jsonify
import RPi.GPIO as io
import time
import os
os.system("sudo pigpiod")
#Raspberry Pi Variables
#Temp Sensor
temp_gpio = 4
sensor = DHT11(temp_gpio)
#Light/Relay Sensor
io.setmode(io.BCM)
light_gpio = 14
io.setup(light_gpio, io.OUT)
My wsgi file
#!/usr/bin/env python3
activate_this = '/var/www/webApp/venv/bin/activate_this.py'
with open(activate_this) as file_:
exec(file_.read(), dict(__file__=activate_this))
import sys
sys.path.insert(0, '/var/www/webApp')
from app import app as application
It errors at the sensor = DHT11(temp_gpio) call. I have other parts of the code, but I don't think theyre relevant to the issue. If I comment out the sensor=DHT11(temp_gpio) line, the code and web page successfully loads

Related

Wsgi script and the newest django with Python 3.5

We are trying to deploy one more web-application on our VPS.
There is one flask application in production already, which is held by Python 3.5 interpreter.
Now we need another one - django app. We have configured our apache2 to host both of then (django is working on subdomain, whereas flask is on the 'root' domain. Everything is okay here.
But, since flask application is using global python interpreter (version 3.5) we cannot run django since it requires version 3.6 or newer.
Here is django WSGI script:
import os
import sys
print('Python version is ... ') # 3.5
python_home = '/var/www/mysite/venv'
activate_this = python_home + '/bin/activate_this.py'
exec( open(activate_this).read() )
print(sys.executable) # in case of virtualenv it refers to /usr/bin/python3.5
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/mysite/mysite")
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
application = get_wsgi_application()
We could have upgraded our interpreter to 3.6, but since established flask app is in production we are not allowed to do so by our managers.. And it is okay probably
If we go with virtualenv nevertheless it created virtual environment with existing global interpreter , as is written above version 3.5.
And this is where we are stuck now. Apache2 log is constanlty saying to us:
[wsgi:error] mod_wsgi (pid=10081): Target WSGI script '/var/www/mysite/mysite/wsgi.py' cannot be loaded as Python module.
[wsgi:error] mod_wsgi (pid=10081): Exception occurred processing WSGI script '/var/www/mysite/mysite/wsgi.py'.
[wsgi:error] Traceback (most recent call last):
[wsgi:error] File "/var/www/mysite/mysite/wsgi.py", line 18, in <module>
[wsgi:error] from django.core.wsgi import get_wsgi_application
[wsgi:error] ImportError: No module named 'django'
If we run python3 in terminal and then from django.core.wsgi import get_wsgi_application
we are going to git this:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/ivan/.local/lib/python3.5/site-packages/django/core/wsgi.py", line 2, in <module>
from django.core.handlers.wsgi import WSGIHandler
File "/home/ivan/.local/lib/python3.5/site-packages/django/utils/crypto.py", line 6, in <module>
import secrets
ImportError: No module named 'secrets'
And we assume that upgrading would solved our problem since django requires version 3.6
https://github.com/quolc/neural-collage/issues/2 and https://docs.djangoproject.com/en/3.0/intro/tutorial01/ ("This tutorial is written for Django 3.0, which supports Python 3.6 and later ... ")
What will be the best step here? Trying to download and establish python 3.6 or newer and refer our wsgi to that or try to use another version of django ...?
Thank you in advance!
In my case that was pretty easy. I was foolish to install and configured all my python services with sudo privileges , that is why when I did
pip3 install <package-name>
that all went okay, but since all services have been run under root I could not get package in usage, so I did
sudo pip3 install <package-name>
And have managed to localize the issue

Django not found in my ubuntu system

I'm trying to deploy django project on Ubuntu 14.04, but I’ve got import error: No module named ‘Django’ but actually the module exist. I reinstalled it many times but anyway the same problem occurs.
There is wsgy.py file
#wsgi.py
import os
import time
import traceback
import signal
import sys
from django.core.wsgi import get_wsgi_application
# Calculate the path based on the location of the WSGI script.
apache_configuration= os.path.dirname(__file__)
project = os.path.dirname(apache_configuration)
workspace = os.path.dirname(project)
sys.path.append(workspace)
sys.path.append(project)
# Add the path to 3rd party django application and to django itself.
sys.path.append('/var/www/s052d78fe.fastvps-server.com/public_html/myv/lib/python3.4/site-packages')
os.environ['DJANGO_SETTINGS_MODULE'] = 'msite.apache.override'
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
And sys. path
'', '/var/www/s052d78fe.fastvps-server.com/public_html/myv/lib/python3.4',
'/var/www/s052d78fe.fastvps-server.com/public_html/myv/lib/python3.4/plat-x86_64-linux-gnu', '/var/www/s052d78fe.fastvps-server.com/public_html/myv/lib/python3.4/lib-dynload',
'/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/var/www/s052d78fe.fastvps-server.com/public_html/myv/lib/python3.4/site-packages']
Thanks.

ImportError: cannot import name NullHandler

I'm trying to deploy a hello-world type app on Elastic Beanstalk. Just about everything seems to work, packages are installed, etc. up to the point where mod_wsgi attempts to retrieve the "application" object from wsgi.py. At that point, the following appears in the logs (once in the logs for each unsuccessfuly HTTP request):
mod_wsgi (pid=6114): Target WSGI script '/opt/python/current/app/myapp/wsgi.py' cannot be loaded as Python module.
mod_wsgi (pid=6114): Exception occurred processing WSGI script '/opt/python/current/app/myapp/wsgi.py'.
Traceback (most recent call last):
File "/opt/python/current/app/caserails/wsgi.py", line 20, in <module>
application = get_wsgi_application()
File "/opt/python/run/venv/lib/python2.7/site-packages/django/core/wsgi.py", line 14, in get_wsgi_application
django.setup()
File "/opt/python/run/venv/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
from django.utils.log import configure_logging
File "/opt/python/run/venv/lib/python2.7/site-packages/django/utils/log.py", line 16, in <module>
from logging import NullHandler # NOQA
ImportError: cannot import name NullHandler
Link to concurrent AWS Forum Post.
The NullHandler is only available on Python version 2.7+. You could create the NullHandler yourself on an ImportError:
import logging
try:
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger(__name__).addHandler(NullHandler())
More information about logging.NullHandler: https://docs.python.org/3/library/logging.handlers.html#logging.NullHandler.
I had similar problem and in my case the issue was that for some unrelated project I created logging.py file in home folder and when I ran something in home, it was importing this file instead of the real module.
You can check which file is being imported like this:
import logging
print(logging.__file__)
I fixed it by deleting logging.py I created previously.
NullHandler was introduced in version 2.7. Are you sure you are running 2.7 on your server?
After much trial and error, the (immediate) problem was solved by removing python logging from requirements.txt and rebuilding the environment.
I do not yet fully understand why this is a problem. On my local machine, I'm able to install logging and run Django without error. I suspect as vikramls pointed out that something weird is happening in the intersection between mod_wsgi, the baselineenv in which mod_wsgi executes, and the virtualenv in which my app operates.
But, at least for now, I'm fixing this error by not including "logging" in requirements.txt when deploying Django 1.7 on Elastic Beanstalk.
I had this issue while creating a build for python 2.7 with PyInstaller.So, I uninstalled logger from my ENV.else you can also remove the package name from the requirement.txt.
This approach solves my issue [Happy Coding:)]

An error occurred importing your passenger_wsgi.py on server

I am getting an error "An error occurred importing your passenger_wsgi.py" on dreamhost server
passenger_wsgi.py file
import sys, os
INTERP = '/home/dramira/books.everycrave.me/intra/bin/python'
sys.path.append('/home/dramira/books.everycrave.me/flipbook/')
if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv)
sys.path.append(os.getcwd())
os.environ['DJANGO_SETTINGS_MODULE'] = "settings"
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
exact error i am getting when compiling the passenger_wsgi.py is
Traceback (most recent call last):
File "passenger_wsgi.py", line 7, in <module>
import django.core.handlers.wsgi
ImportError: No module named django.core.handlers.wsgi
i checked compiling the passenger_wsgi.py file for other website its working fine on same server.
I dont know what problem i am facing here.
Please help me out.
Your passenger_wsgi.py looks fairly similar to mine, also hosted on Dreamhost. Three differences that stand out to me:
You're only adding the current directory os.getcwd() to sys.path. In mine, I add the current directory and the project directory: os.path.join(os.getcwd(), 'projectname')).
Your DJANGO_SETTINGS_MODULE is only called 'settings'. I use a qualified module: 'projectname.settings'
This may be a difference in Django versions — I'm on 1.7 — but at some point I had to move away from application = WSGIHandler().
My actual WSGI invocation is now:
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

Error when importing WSGIHandler with django

Without any code changing, my django app started throwing an exception while loading the WSGI script. I'm using django 1.3 with python 2.7, and the top-level .wsgi is essentially unmodified from the default:
import os
import sys
from django.core.handlers.wsgi import WSGIHandler
os.environ['DJANGO_SETTINGS_MODULE'] = 'api.settings'
application = WSGIHandler()
It started producing these errors on any request, as reported by Apache:
mod_wsgi (pid=3283): Target WSGI script '/home/beder/webapps/api/api.wsgi' cannot be loaded as Python module.
mod_wsgi (pid=3283): Exception occurred processing WSGI script '/home/beder/webapps/api/api.wsgi'.
Traceback (most recent call last):
File "/home/beder/webapps/api/api.wsgi", line 4, in <module>
from django.core.handlers.wsgi import WSGIHandler
File "/home/beder/webapps/api/lib/python2.7/django/core/handlers/wsgi.py", line 10, in <module>
from django import http
File "/home/beder/webapps/api/lib/python2.7/django/http/__init__.py", line 122, in <module>
from django.utils.http import cookie_date
File "/home/beder/webapps/api/lib/python2.7/django/utils/http.py", line 7, in <module>
from email.Utils import formatdate
File "/usr/local/lib/python2.7/email/__init__.py", line 79, in __getattr__
__import__(self.__name__)
File "/usr/local/lib/python2.7/email/utils.py", line 27, in <module>
import random
File "/usr/local/lib/python2.7/random.py", line 47, in <module>
from os import urandom as _urandom
ImportError: cannot import name urandom
I restarted the server, and it now works normally (no errors). I'm at a loss for what to do - I want to make sure this doesn't happen again, but it's not happening now, and I have no idea why that import error appeared.
Are you executing Django inside a virtualenv? Did you updated or upgraded your system? If so and you upgraded to Python 2.7 from Python 2.6 for example you need to regenerate the virtualenv:
$ virtualenv [your-options] [your-django-project-directory]
For anyone using webfaction like Jesse and myself to run his django app but is not using virtualenv, it can happen that after the upgrade, the custom apache installation for the webapp was never restarted. This means that the stdlib changed but apache still uses python 2.7.2 because its the version it has loaded into memory.
The solution in this case is simple: login to your account via ssh and execute:
[username#webXX ~]$ ~/webapps/<webapp-name>/apache2/bin/restart
This restarts the web server and causes apache to reload the new interpreter binary.
I also found the same error when I updated Python 2.6.5 to 2.6.8, building from source. I also had built mod_wsgi from source, and initially forgot to recompile mod_wsgi for the new version of Python, and that led to the same error concerning urandom.

Categories

Resources