wsgi django not working - python

im installing django,
the test for wsgi is ok, but when i point my default file to the django test, it doesnt work,
this is the test that works fine:
default: /etc/apache2/sites-available/default
<VirtualHost *:80>
ServerName www.example.com
ServerAlias example.com
ServerAdmin webmaster#example.com
DocumentRoot /var/www
<Directory /var/www/documents>
Order allow,deny
Allow from all
</Directory>
WSGIScriptAlias / /home/ubuntu/djangoProj/micopiloto/application.wsgi
<Directory /home/ubuntu/djangoProj/mysitio/wsgi_handler.py>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
application.wsgi:: ~/djangoProj/micopiloto
import os
import sys
sys.path.append('/srv/www/cucus/application')
os.environ['PYTHON_EGG_CACHE'] = '/srv/www/cucus/.python-egg'
def application(environ,
start_response):
status = '200 OK'
output = 'Hello World!MK SS9 tkt kkk'
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
but if I change the default to point to application_sa.wsgi the django test,
it doesnt work :(
application_sa.wsgi
import os, sys
sys.path.append('/home/ubuntu/djangoProj/micopiloto')
os.environ['DJANGO_SETTINGS_MODULE'] = 'micopiloto.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
I restart the apache server every time i change the wsgi to test,
so what im i missing?
thanks a lot!

Try changing your apache config to the following:
AddHandler wsgi-script .wsgi
WSGISocketPrefix /var/run/wsgi
WSGIRestrictEmbedded On
<VirtualHost *:80>
ServerName www.mydomain.com
WSGIDaemonProcess myprocess processes=2 threads=15
WSGIProcessGroup myprocess
WSGIScriptAlias / /home/ubuntu/djangoProj/micopiloto/application_sa.wsgi
</VirtualHost>
Then add the root folder of your project to sys.path as well in application_sa.wsgi:
sys.path.append('/home/ubuntu/djangoProj')
sys.path.append('/home/ubuntu/djangoProj/micopiloto')

Related

Django redirect from other domain gives Page Not Found error

When clicking on a url that points to my Django website, I get a Page Not Found error. When I look to the error with DEBUG=True, I see that the "current path" displayed in the error message is different from the actual url.
For example, take a look at the shared articles on linkedin: https://www.linkedin.com/company/huvepharma-nv/. When clicking on the first post I am redirected to my Django website: https://huvepharma.com/news/article/how-butyrate-producing-bacteria-can-support-food-safety/. This gives me a Page Not Found error, saying that the current path is company/huvepharma-nv/, which is the path on the LinkedIn website.
How can I fix this?
I added the following fix in the past but now I get ERR_TOO_MANY_REDIRECTS with DEBUG=False. So the quick fix is also not working anymore.
def handler404(request, exception, template_name='errorhandlers/handler404.html', *args, **kwargs):
if request.META.get('HTTP_SEC_FETCH_SITE') == 'cross-site':
return redirect(request.path)
response = render_to_response(template_name)
response.status_code = 404
return response
Apache2 configuration:
Port 80:
<VirtualHost *:80>
ServerAdmin frederik#adbuddy.be
ServerName huvepharma.com
ServerAlias www.huvepharma.com
ErrorLog "||/usr/bin/rotatelogs /home/ubuntu/websites/huvepharma/logs/error/error-%Y-%m-%d.log 86400"
CustomLog "||/usr/bin/rotatelogs /home/ubuntu/websites/huvepharma/logs/access/access-%Y-%m-%d.log 86400" combined
Alias /static /home/ubuntu/websites/huvepharma/static
<Directory /home/ubuntu/websites/huvepharma/static>
Require all granted
</Directory>
Alias /media /home/ubuntu/websites/huvepharma/media
<Directory /home/ubuntu/websites/huvepharma/media>
Require all granted
</Directory>
#WSGIDaemonProcess huvepharma.com python-home=/home/ubuntu/websites/huvepharma/venv python-path=/home/ubuntu/websites/huvepharma
#WSGIProcessGroup huvepharma.com
#WSGIScriptAlias / /home/ubuntu/websites/huvepharma/huvepharma/wsgi.py process-group=huvepharma.com
<Directory /home/ubuntu/websites/huvepharma/huvepharma>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
RewriteEngine on
RewriteCond %{SERVER_NAME} =huvepharma.com [OR]
RewriteCond %{SERVER_NAME} =www.huvepharma.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
Port 443:
<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerAdmin frederik#adbuddy.be
ServerName huvepharma.com
ServerAlias www.huvepharma.com
ErrorLog "||/usr/bin/rotatelogs /home/ubuntu/websites/huvepharma/logs/error/error-%Y-%m-%d.log 86400"
CustomLog "||/usr/bin/rotatelogs /home/ubuntu/websites/huvepharma/logs/access/access-%Y-%m-%d.log 86400" combined
Alias /static /home/ubuntu/websites/huvepharma/static
<Directory /home/ubuntu/websites/huvepharma/static>
Require all granted
</Directory>
Alias /media /home/ubuntu/websites/huvepharma/media
<Directory /home/ubuntu/websites/huvepharma/media>
Require all granted
</Directory>
WSGIDaemonProcess huvepharma.com python-home=/home/ubuntu/websites/huvepharma/venv python-path=/home/ubuntu/websites/huvepharma
WSGIProcessGroup huvepharma.com
WSGIScriptAlias / /home/ubuntu/websites/huvepharma/huvepharma/wsgi.py process-group=huvepharma.com
<Directory /home/ubuntu/websites/huvepharma/huvepharma>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /etc/letsencrypt/live/huvepharma.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/huvepharma.com/privkey.pem
</VirtualHost>
</IfModule>

Internal Server Error for Hello World django project in production

I have my apache server directing traffic from mysite.com/home to my wsgi.py file, but when get_wsgi_application() is called I get an internal server error.
Running apache2 on amazon linux EC2. In wsgi.py, I've replaced the line,
application = get_wsgi_application()
with the function,
def application(environ, start_response):
status = '200 OK'
output = b'sys.path = %s\n' % repr(sys.path).encode('UTF-8')
output += b'sys.version = %s\n' % repr(sys.version).encode('UTF-8')
output += b'sys.prefix = %s\n' % repr(sys.prefix).encode('UTF-8')
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
and the server error goes away. It shows that apache is using the correct python version (3.7) and doesn't return an error when I import get_wsgi_application() from django.core.wsgi. To my understanding this means apache is finding the access point to my django project just fine, and it has permission to look into the file and show its contents. What am I missing?
Other possibly relevant information I can think of:
user "apache" and group "apache" own the outer mysite directory and everything in it. I've set all the settings in settings.py for production according to the django deployment checklist. https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
wsgi.py:
import os, sys
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
sys.path.append('/usr/local/wsgi/django')
sys.path.append('/usr/local/wsgi/django/mysite')
application = get_wsgi_application()
httpd.conf:
<VirtualHost *:80>
ServerName www.mysite.com
Redirect permanent / httpswww.mysite.com
</VirtualHost>
<VirtualHost *:443>
ServerName httpswww.mysite.com
ServerAlias mysite.com
ServerAdmin person#gmail.com
DocumentRoot "/var/www/html/efs/Website"
WSGIDaemonProcess mysite
WSGIProcessGroup mysite
WSGIScriptAlias /home /usr/local/wsgi/django/mysite/mysite/wsgi.py
<Directory "/usr/local/wsgi/django/mysite/mysite">
<Files "wsgi.py">
Require all granted
</Files>
</Directory>
SSLEngine on
SSLCertificateFile "/crt/path.crt"
SSLCertificateKeyFile "/key/path.key"
</VirtualHost>
settings.py:
SECRET_KEY = 'string_I_havent_moved_yet'
DEBUG= False
ALLOWED_HOSTS = ['www.mysite.com', e2-serial-numbers.compute-1.amazonaws.com']

Images not showing over SSL on apache2 with python script

I know this question has been asked several times, but I am all out of ideas and have been reading everywhere about this.
I am running Ubuntu 17.04 and Apache 2.4.25 to host a web server. I have generated my own SSL certificate. Since doing this, I am unable to view any images over SSL. Currently, I can confirm the path is working, the file is in tact and URL is correct, as I can access this typing the http URL into my browser.
If I go to the web inspector whilst loading my site, if I click on any image it gives me a 404 error.
How do I get these images to load over SSL.
My apache2 config is:
<VirtualHost *:80>
ServerName localhost
ServerAdmin info#****.com
DocumentRoot /var/www/****.com/pay
Redirect /secure https://****.com/
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
<VirtualHost *:443>
SSLEngine On
SSLCertificateFile /etc/ssl/certs/****.com.crt
SSLCertificateKeyFile /etc/ssl/private/****.com.key
SSLCACertificateFile /etc/ssl/certs/ca-certificates.crt
SetEnv SECRET_KEY ****
SetEnv PUBLISHABLE_****
ServerAdmin info#****.com
ServerName www.****.com
DocumentRoot /var/www/****.com/pay/static
WSGIDaemonProcess webtool threads=5 python-path=/var/www/****.com/pay
WSGIScriptAlias / /var/www/****.com/pay/webtool.wsgi
EnableMMAP off
EnableSendfile off
<Directory /var/www/****.com/pay>
Options +ExecCGI
WSGIProcessGroup webtool
WSGIApplicationGroup %{GLOBAL}
WSGIScriptReloading On
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
and I have a python script running to do my routes:
import os
import stripe
import cgi
print "Context-type: text/html"
from flask import Flask, render_template, request, redirect, send_from_directory
from flask import request
from flask import json
stripe_keys = {
'secret_key': os.environ['SECRET_KEY'],
'publishable_key': os.environ['PUBLISHABLE_KEY']
}
stripe.api_key = stripe_keys['secret_key']
app = Flask(__name__, static_url_path='')
#app.route('/')
def index():
return render_template('index.html', key=stripe_keys['publishable_key'])
#app.route("/hello")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(host="127.0.0.1", port="5050")
#app.route("/charge", methods=['POST'])
def charge():
# Amount in cents
amount = 500
customer = stripe.Customer.create(
email=request.form['stripeEmail'],
source=request.form['stripeToken']
)
charge = stripe.Charge.create(
customer=customer.id,
receipt_email=request.form['stripeEmail'],
amount=amount,
currency='usd',
description='Donation'
)
return render_template('charge.html', amount=amount)
I cannot work out if I need to set a route in my python script to allow images to be fetched, or I am missing something else.
I am calling the image in my index.html file with:
with the 'img' folder being in the same location as index.html. Please help.
Your image requests are being sent to WSGI, if you want Apache to handle them, you'll have to "undo" the WSGIScriptAlias of /.
I'm not a WSGI user, but it seems like you could block this from
running conditionally by putting this in your vhost:
RewriteEngine ON
RewriteRule ^/img/ - [L]
Even though this is a no-op, it should block this part of WSGi from running.

How to reference Django Rest Framework Router URLs when Django is not serving the root of the web server

I had my API working well, but with DJango serving the entire document root, behind Apache. The team has decided they have some pieces that they want to serve out of the root (non-API) via apache directly, so I'm pushing the DJango WSGI reference from / to /api.
From:
WSGIScriptAlias / /opt/org/myproj/myapp/wsgi.py
To:
WSGIScriptAlias /api/ /opt/org/myproj/myapp/wsgi.py
The main urls.py went from:
urlpatterns = patterns('',
url(r'^api/', include(router.urls)),
to:
urlpatterns = patterns('',
url(r'^', include(router.urls)),
The problem is, when I hit the webserver at /api/ I do get the router URLs, but when I try to hit one of the actual URLs, I'm getting a 404. It's not actually dealing with any of the sub-URL references.
Hitting /api/ correctly gives:
{
address: "https://172.17.100.7/api/address/",
chassis: "https://172.17.100.7/api/chassis/",
configurationfile: "https://172.17.100.7/api/configurationfile/",
job: "https://172.17.100.7/api/job/",
node: "https://172.17.100.7/api/node/",
operatingsystem: "https://172.17.100.7/api/operatingsystem/"
}
Hitting /api/address gives:
Not Found
The requested URL /api/address/ was not found on this server.
Apache/2.2.22 (Debian) Server at 172.17.100.7 Port 443
Can someone provide some insight into how the URLs are supposed to be referenced in such a case? I thought this was going to be a pretty simple change, but I'm at a loss.
EDIT: Here's the full apache config.
WSGIScriptAlias /api/ /opt/org/myproj/myapp/wsgi.py
<VirtualHost *:80>
ServerAdmin webmaster#localhost
DocumentRoot /var/www
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</VirtualHost>
<VirtualHost *:443>
ServerAdmin webmaster#localhost
DocumentRoot /opt/org/myproj/root
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /opt/org/myproj/root/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
Alias /repo /opt/myorg/myproj/repo/
<Directory /opt/hp/moonshot/repo/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
ErrorLog /opt/myorg/myproj/logs/error.log
LogLevel warn
CustomLog /opt/myorg/myproj/logs/access.log combined
<Directory /opt/myorg/myproj/myapp>
<Files wsgi.py>
Order deny,allow
Allow from all
</Files>
</Directory>
# SSL Options
SSLEngine on
SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
<FilesMatch "\.(cgi|shtml|phtml|php)$">
SSLOptions +StdEnvVars
</FilesMatch>
BrowserMatch "MSIE [2-6]" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0
BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown
</VirtualHost>
From memory, use:
WSGIScriptAlias /api/ /opt/org/myproj/myapp/wsgi.py/api/
Put your Django stuff back to how it was.
This will only intercept sub url of '/api/' but the WSGI application will still think it is at the root of the site.

WSGIScriptAlias /wsgi/ does not work in Win7

Using Apache 2.2 / Win7
In httpd.conf:
LoadModule wsgi_module modules/mod_wsgi.so
....
WSGIScriptAlias /wsgi/ "J:/py.cherrypy/"
<Directory "J:/py.cherrypy">
Order allow,deny
Allow from all
<Files "*.*">
</Files>
</Directory>
In J:/py.cherrypy/test.wsgi :
def application(environ, start_response):
status = '200 OK'
output = 'Hello World!'
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
Pointing to
http://localhost:8080/wsgi/test.wsgi
returns The requested URL /wsgi/test.wsgi was not found on this server.
localhost:8080 is fine
With
WSGIScriptAlias /myapp j:/py.cherrypy/test.wsgi
<Directory j:/py.cherrypy>
Order allow,deny
Allow from all
</Directory>
wget 127.0.0.1:8080/myapp works fine

Categories