Module is not imported after sys.path.append() - django

I am trying to deploy my django application.
Like many others I faced the problem of "missing" django, no module named django, though it exists.
I had to install Django of version 2, not the newest and it was installed into '/home/ivan/.local/lib/python3.5/site-packages/'.
I have my apache configured and wsgi.py looks like this:
"""
WSGI config for mysite project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
import sys
sys.path.append('/home/ivan/.local/lib/python3.5/site-packages/')
print(sys.path)
# import /home/ivan/.local/lib/python3.5/site-packages/django
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
application = get_wsgi_application()
When I type python3 in terminal and do this:
>>> import django
>>> django.__path__
['/home/ivan/.local/lib/python3.5/site-packages/django']
So I got my path of django module and I append it, I also tried:
sys.path.insert(0, '/home/ivan/.local/lib/python3.5/site-packages/django')
and still I got 500 error with annoying:
[Tue Apr 21 13:12:41.861348 2020] [wsgi:error] [pid 29470] [remote 185.201.90.67:1131] Traceback (most recent call last):
[Tue Apr 21 13:12:41.861379 2020] [wsgi:error] [pid 29470] [remote 185.201.90.67:1131] File "/var/www/mysite/mysite/wsgi.py", line 15, in <module>
[Tue Apr 21 13:12:41.861384 2020] [wsgi:error] [pid 29470] [remote 185.201.90.67:1131] from django.core.wsgi import get_wsgi_application
[Tue Apr 21 13:12:41.861397 2020] [wsgi:error] [pid 29470] [remote 185.201.90.67:1131] ImportError: No module named 'django'
Why wsgi cannot work properly? What am I doing wrong here?
Why interpreter cannot find a module after I forced him by sys.path.insert() ?
Huge thank in advance!
UPDATE ONE
print(sys.path) inside of wsgi returns:
['/var/www/mysite', '/usr/lib/python35.zip', '/usr/lib/python3.5',
'/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload',
'/usr/local/lib/python3.5/dist-packages',
'/usr/lib/python3/dist-packages',
'/home/ivan/.local/lib/python3.5/site-packages/']
UPDATE TWO
Since I am trying to deploy the app, no matter how I solve it.
Thanks to #KolaB for advice of virtualenv.
I just did it , now I have this structure:
├── mysite
├── requirements.txt
└── venvdjang
venvdjang is a dir with virtual interpreter.
I also installed django by source /venvdjang/bin/activate
pip install -r requirements.txt
Now, how can I tell my wsgi and apache2 that I want to use virtualenv?
Update Three
Thank you all for your help!
I have a VPS with flask application in production (www.example.com)
Now I have to deploy another one web application on subdomain - django. (www.sub.example.com)
This is config for django.
/etc/apache2/sites-available/mysite.conf
<VirtualHost *:80>
ServerName sub.example.com
ServerAlias www.sub.example.com
ServerAdmin sub.example.com#gmail.com
#DocumentRoot /var/www/mysite
ErrorLog ${APACHE_LOG_DIR}/mysite-error.log
CustomLog ${APACHE_LOG_DIR}/mysite-access.log combined
#DocumentRoot /var/www/mysite/index.html
WSGIDaemonProcess mysite processes=2 threads=25 python-path=/var/www/mysite
WSGIProcessGroup mysite
WSGIScriptAlias / /var/www/mysite/mysite/wsgi.py
Alias /robots.txt /var/www/mysite/static/robots.txt
Alias /favicon.ico /var/www/mysite/static/favicon.ico
Alias /static/ /var/www/mysite/static/
Alias /static/ /var/www/mysite/media/
<Directory /var/www/mysite/mysite>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
<Directory /var/www/mysite/static>
Require all granted
</Directory>
<Directory /var/www/mysite/media>
Require all granted
</Directory>
</VirtualHost>
and this is config for flask
/etc/apache2/sites-available/FlaskApp-le-ssl.conf
<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerName www.example.com
ServerAdmin example.com#mywebsite.com
WSGIScriptAlias / /var/www/FlaskApp/flaskapp.wsgi
<Directory /var/www/FlaskApp/FlaskApp/>
Order allow,deny
Allow from all
</Directory>
Alias /static /var/www/FlaskApp/FlaskApp/static
<Directory /var/www/FlaskApp/FlaskApp/static/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
Include /etc/letsencrypt/options-ssl-apache.conf
ServerAlias example.com
SSLCertificateFile /etc/letsencrypt/live/example.com
--p1ai/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/example.com--p1ai/privkey.pem
</VirtualHost>
</IfModule>
<IfModule mod_ssl.c>
<VirtualHost *:80>
ServerName example.com
Redirect / https://www.example.com
ServerAdmin admin#mywebsite.com
WSGIScriptAlias / /var/www/FlaskApp/flaskapp.wsgi
<Directory /var/www/FlaskApp/FlaskApp/>
Order allow,deny
Allow from all
</Directory>
Alias /static /var/www/FlaskApp/FlaskApp/static
<Directory /var/www/FlaskApp/FlaskApp/static/>
Order allow,deny
Allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
RewriteEngine on
# Some rewrite rules in this file were disabled on your HTTPS site,
# because they have the potential to create redirection loops.
# RewriteCond %{SERVER_NAME} = example.com
# RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
#RewriteCond %{SERVER_PORT} !^443$
#RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
</VirtualHost>
</IfModule>
OS - Ubuntu 16.04
mod_wsgi was installed a few years ago by sudo apt-get install
Update Four
I changed WSGIDaemonProcess python-home as #Alasdair said to python-home=/var/www/venvdjang but it did not work out.
Now if I run in terminal source /var/www/venvdjang/bin/activate
(venvdjang) ivan#server:/var/www$ python
Python 3.5.2 (default, Oct 8 2019, 13:06:37)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> import sys
>>> sys.path
['', '/var/www/venvdjang/lib/python35.zip', '/var/www/venvdjang/lib/python3.5',
'/var/www/venvdjang/lib/python3.5/plat-x86_64-linux-gnu',
'/var/www/venvdjang/lib/python3.5/lib-dynload',
'/usr/lib/python3.5',
'/usr/lib/python3.5/plat-x86_64-linux-gnu',
'/var/www/venvdjang/lib/python3.5/site-packages']
>>>
But my wsgi.py after removing all sys.path.append() staff still returns after print(sys.path) this:
['/var/www/venvdjang',
'/usr/lib/python35.zip',
'/usr/lib/python3.5',
'/usr/lib/python3.5/plat-x86_64-linux-gnu',
'/usr/lib/python3.5/lib-dynload',
'/usr/local/lib/python3.5/dist-packages',
'/usr/lib/python3/dist-packages']
It is like he still goes to system interpreter...
Why I cannot refer to a correct virtualenv ?

Related

Internal Server Error using apache django mod_wsgi or 500 internal server error mod_wsgi apache

wsgi.py
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gis_api.settings')
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
httpd.conf
ServerName 127.0.0.1:81
LoadFile "C:/Users/test/AppData/Local/Programs/Python/Python310/python310.dll"
LoadModule wsgi_module "C:/Users/test/AppData/Local/Programs/Python/Python310/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd"
WSGIPythonHome "C:/Users/test/AppData/Local/Programs/Python/Python310"
WSGIPythonPath "C:/Users/test/AppData/Local/Programs/Python/Python310/lib/site-packages/"
<VirtualHost *:81>
WSGIScriptAlias / "D:/django_project/gis_api/gis_api/gis_api/wsgi.py"
<Directory "D:/django_project/gis_api/gis_api/gis_api/">
<Files wsgi.py>
Require all granted
</Files>
</Directory>
Alias /static "D:/django_project/gis_api/gis_api/static/"
<Directory "D:/django_project/gis_api/gis_api/static/">
Require all granted
</Directory>
Alias /media "D:/django_project/gis_api/gis_api/media/"
<Directory "D:/django_project/gis_api/gis_api/media/">
Require all granted
</Directory>
</VirtualHost>
error.log
mod_wsgi (pid=20212): Failed to exec Python script file 'D:/django_project/gis_api/gis_api/gis_api/wsgi.py'., referer: http://127.0.0.1:81/
mod_wsgi (pid=20212): Exception occurred processing WSGI script 'D:/django_project/gis_api/gis_api/gis_api/wsgi.py'., referer: http://127.0.0.1:81/
Traceback (most recent call last):\r, referer: http://127.0.0.1:81/
ModuleNotFoundError: No module named 'gis_api'\r, referer: http://127.0.0.1:81/
version :
Django 4.1.1
mod-wsgi 4.9.4
os window 10
I have try to all solution. But getting error. I am beginner to deployment in django apache. Pl guide me best path of deployment.
my project structure
WSGIPythonPath needs to point to your app directory like
WSGIPythonPath "D:/django_project/gis_api"
For the moment you are twice adding the environment path (WSGIPythonHome and ...Path) to the python search path but not your apps directory.

Forbidden 403 You don't have permission to access this resource. (mod_wsgi, wamp, apache2.4, django) on windows

i have installed everything properly and gone through all solutions related to this subject but still error remains, I'm new to Django and i would really appreciate your help
I get this error in my error log file:
[Fri Feb 14 21:52:16.916422 2020] [authz_core:error] [pid 4288:tid 1252] [client ::1:51391] AH01630: client denied by server configuration: E:/AppSource/eCommerce/src/ecommerce/wsgi_windows.py
and when i try to reach 127.0.0.1:80 i get: Forbidden 403
and this is my wsgi_windows.py configuration:
activate_this = 'CE:/AppSource/eCommerce/Scripts/activate_this.py'
exec(open(activate_this).read(),dict(__file__=activate_this))
import os
import sys
import site
from django.core.wsgi import get_wsgi_application
site.addsitedir("C:/Python37/Lib/site-packages")
sys.path.append('E:/AppSource/eCommerce')
sys.path.append('E:/AppSource/eCommerce/src')
sys.path.append('E:/AppSource/eCommerce/src/ecommerce')
os.environ['DJANGO_SETTINGS_MODULE'] = 'ecommerce.settings'
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ecommerce.settings")
application = get_wsgi_application()
and this is hhtpd-vhosts.conf configuration:
<VirtualHost *:80>
ServerName localhost
WSGIPassAuthorization On
ErrorLog "E:/appSource/eCommerce/eCommerce.error.log"
CustomLog "E:/appSource/eCommerce/eCommerce.access.log" combined
WSGIScriptAlias / "E:/appSource/eCommerce/src/ecommerce/wsgi_windows.py"
<Directory "E:/appSource/eCommerc/src/ecommerce/">
<Files wsgi_windows.py>
Require all granted
</Files>
</Directory>
Alias /static "E:/appSource/eCommerce/static_cdn/static_root"
<Directory "E:/appSource/eCommerce/static_cdn/static_root">
Require all granted
</Directory>
Alias /media "E:/appSource/eCommerce/static_cdn/media_root"
<Directory "E:/appSource/eCommerce/static_cdn/media_root">
Require all granted
</Directory>
</VirtualHost>
i have tried everything that i know
Please help to solve this
Thanks
I think the easiest way to achieve your goal is to change the port number of apache and start the apache again.

Error 403: Forbidden You don't have permission to access / on this server with apache, mod-wsgi and django

I am new in django and apache. I want to publish my django website by apache and mod-wsgi.
when I start httpd.exe, I recieve 403 forbidden error in my browser.
my apache config is here
LoadFile "c:/users/zharf/appdata/local/continuum/anaconda3/envs/django/python36.dll"
LoadModule wsgi_module "c:/users/zharf/appdata/local/continuum/anaconda3/envs/django/lib/site-packages/mod_wsgi/server/mod_wsgi.cp36-win_amd64.pyd"
WSGIPythonHome "c:/users/zharf/appdata/local/continuum/anaconda3/envs/django"
Alias /static/ /D:/user/JarfaSys/static/
<Directory D:/user/JarfaSys/static/>
AllowOverride none
Require all granted
</Directory>
WSGIScriptAlias / /D:/user/JarfaSys/JarfaSys/wsgi.py
WSGIPythonPath /D:/user/JarfaSys/
WSGIPassAuthorization On
<VirtualHost 127.0.0.1:443>
DocumentRoot D:/user/JarfaSys
Alias /favicon.ico D:/user/JarfaSys/JarfaSys/favicon.ico
Alias / /D:/user/JarfaSys/JarfaSys/wsgi.py
ServerName 127.0.0.1
SSLEngine on
SSLCertificateKeyFile C:/Users/zharf/TibiFiles/host.key
SSLCertificateFile C:/Users/zharf/TibiFiles/host.cert
SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown
<Directory D:/user/JarfaSys/JarfaSys/>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
</VirtualHost>
WSGIScriptAlias / /D:/user/JarfaSys/JarfaSys/wsgi.py
WSGIPythonPath /D:/user/JarfaSys/
WSGIPassAuthorization On
<Directory D:/user/JarfaSys/JarfaSys/>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
wsgi.py is :
import os
import sys
path = "D:/Ghanbari/JarfaSys/JarfaSys"
if path not in sys.path:
sys.path.append(path)
os.environ['PYTHON_EGG_CACHE'] = '/tmp/.python-eggs'
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "JarfaSys.settings")
#print os.getenv("DJANGO_SETTINGS_MODULE")
#print os.getenv("PYTHON_EGG_CACHE")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
error log file is here
[Fri Aug 23 16:29:26.827875 2019] [core:error] [pid 10784:tid 1092] (20024)The given path is misformatted or contained invalid characters: [client ::1:50025] AH00036: access to / failed (filesystem path 'C:/D:')
[Fri Aug 23 16:29:26.848875 2019] [core:error] [pid 10784:tid 1092] (20024)The given path is misformatted or contained invalid characters: [client ::1:50025] AH00036: access to /favicon.ico failed (filesystem path 'C:/D:'), referer: http://localhost/
Apache service user has access to my app directory.
I study many similar questions but the problem is not solved. any suggestions would be appreciated.
Here is an example of project setup in apache. You vhosts file has a few errors
Listen 443
<VirtualHost *:443>
ServerName localhost
ErrorLog "logs/logname-error.log"
CustomLog "logs/logname-access.log" common
WSGIScriptAlias / "C:\workspace\your_project_path\wsgi.py"
Alias /static/ C:/workspace/static/
<Directory C:\your_project_path>
<Files wsgi.py>
Order deny,allow
Allow from all
</Files>
</Directory>
</VirtualHost>
Remove the / Before the D:/... use the above as pattern.
and an example of a wsgi.py
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
activate_env = r"C:\your_virtual_environment_path\Scripts\activate_this.py"
with open(activate_env) as f:
exec(f.read(), {"__file__": activate_env})
from your_main import app as application

How to configure apache 2.4 VirtualHost with wordpress and django wsgi on debian?

I want to add a wordpress app at blog.mydomain.com but I already have a Django app at mydomain.com running with wsgi in deamon mode.
I work on a Linux server (debian) with apache2.4.10 and PHP 5.6
Here is my apache conf for mydomain.com (django.conf):
<VirtualHost 000.000.000.000:443> (my server ip)
ServerName mydomain.com
ServerAlias mydomain.com
ServerAlias www.mydomain.com
SSLEngine On
SSLCertificateFile /pathToSsl/ssl.crt
SSLCertificateKeyFile /pathToSsl/ssl.key
SSLCertificateChainFile /pathToSsl/ssl.pem
SSLVerifyClient None
WSGIDaemonProcess mydomain.com threads=4
WSGIProcessGroup mydomain.com
WSGIScriptAlias /path/to/settings/wsgi.py
# Aliases toward static data
Alias /media /pathToMedia/media/
Alias /static /pathToStatic/static/
Alias /log /var/www/html/
<Directory /path/to/settings>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access-mydomain.com.log combined
ErrorLog ${APACHE_LOG_DIR}/error-mydomain.com.log
ErrorDocument 500 "Oups something goes wrong."
</VirtualHost>
<VirtualHost *:80>
ServerName mydomain.com
ServerAlias mydomain.com
ServerAlias www.mydomain.com
Redirect / https:// mydomain.com/
</VirtualHost>
This one is working perfectly.
And now I add a new configuration for my wordpress blog (wordpress.conf):
<VirtualHost *:80>
ServerName blog.mydomain.com
DocumentRoot "/var/www/html/wordpress"
<Directory /var/www/html/wordpress>
AllowOverride all
Options Indexes FollowSymLinks
Require all granted
</Directory>
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access-blog.fr.log combined
ErrorLog ${APACHE_LOG_DIR}/error-blog.fr.log
</VirtualHost>
The problem is when i try to access to blog.mydomain.com, I am redirected to mydomain.com after few seconds.
At the beginning, I thought that was because my conf wordpress was not found but if I put
Redirect / stackoverflow.com
in wordpress.conf and it's working. So the issue is not here.
I find this in my apache error log for the wordpress blog :
[Mon Oct 24 13:15:55.829675 2016] [wsgi:error] [pid 16958] [client 000.000.000.000:38439] mod_wsgi (pid=16958): Exception occurred processing WSGI script '/path/to/settings/wsgi.py'., referer: http://blog.mydomain.com/
[Mon Oct 24 13:15:55.829844 2016] [wsgi:error] [pid 16958] [client 000.000.000.000:38439] IOError: failed to write data, referer: http://blog.mydomain.com/
In my opinion, the problem come from wsgi, but i don't know why and how to resolve it.
I don't understand why this conf go over wsgi.
I hope you can help me.
Thanks for reading.

End of script output before headers: wsgi.py

I am trying to install my django project with Apache, mod_wsgi and python3. but Apache still gives this error:
Exception ignored in: <module 'threading' from '/usr/lib/python3.4/threading.py'>
Traceback (most recent call last):
File "/usr/lib/python3.4/threading.py", line 1288, in _shutdown
assert tlock is not None
AssertionError:
End of script output before headers: wsgi.py
I lost two days trying to fix this problem, I know that this error can be produced by several reasons but I not find where the problem.
Here the wsgi.py content:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import site, sys
path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if path not in sys.path:
sys.path.append(path)
sys.path.append('/var/www/myproject/myproject_env/bin/python3.4/dist-packages')
site.addsitedir('/var/www/myproject/myproject_env/bin/python3.4/dist-packages')
os.environ["DJANGO_SETTINGS_MODULE"] = "myproject.settings"
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
The Apache configuration is as follows:
<VirtualHost *:80>
ServerName mydomain.com
ServerAlias www.mydomain.com
DocumentRoot /var/www
Alias /static/ /var/www/myproject/static/
Alias /static/admin/ /var/www/myproject/static/admin/
Alias /uploads/ /var/www/myproject/uploads/
WSGIDaemonProcess myproject lang='fr_FR.UTF-8' locale='fr_FR.UTF-8' python-path=/var/www/myproject:/var/www/myproject/myproject_env/bin/python3.4/dist-packages
WSGIProcessGroup myproject
WSGIScriptAlias / /var/www/myproject/myproject/wsgi.py
WSGIApplicationGroup %{GLOBAL}
<Directory "/var/www/myproject/myproject/">
Require all granted
</Directory>
<Directory "/var/www/myproject/myproject/wsgi.py">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Require all granted
</Directory>
<Directory /static/admin/>
Require all granted
</Directory>
<Location "/uploads/">
SetHandler None
</Location>
ErrorLog /var/log/apache2/myproject.log
CustomLog /var/log/apache2/myproject.access.log combined
</VirtualHost>
Please anyone helps me fix this?
Solved: I changed the location of my Django project to another folder in a new linux account. I think (and I'm not really sure) the error occurred because /var/www contains another python project using cgi-bin, this maybe creates conflict with my Django project.