Django project with fcgi - django

I am trying to deploy a second Django project on a dedicated server using fcgi. However if I run python manage.py runfcgiin my project I get the following output:
WSGIServer: missing FastCGI param SERVER_NAME required by WSGI!
WSGIServer: missing FastCGI param SERVER_PORT required by WSGI!
WSGIServer: missing FastCGI param SERVER_PROTOCOL required by WSGI!
Status: 500 INTERNAL SERVER ERROR
Vary: Accept-Language, Cookie
Content-Type: text/html; charset=utf-8
Content-Language: en-us
followed by the correct html output.
My .htaccess is like this:
RewriteEngine On
RewriteRule ^media/(.*)$ /home/username/public_html/my_project/media/$1 [L]
RewriteRule ^admin_media/(.*)$ /home/username/public_html/my_project/admin_media/$1 [L]
RewriteRule ^(django\.fcgi/.*)$ - [L]
RewriteRule ^(.*)$ cgi-bin/django.fcgi/$1 [L]
And my django.fcgi is:
#!/usr/local/bin/python2.6
import sys
import os
# insert PYTHONPATH values here, including the path to your application
sys.path.insert(0, '/home/darwinfo/lib/python/')
sys.path.insert(0, '/home/darwinfo/django-projects/my_project/')
# location of your application's settings file.
os.environ['DJANGO_SETTINGS_MODULE'] = 'my_project.settings'
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method = "threaded", daemonize = "false", maxchildren=3, minspare=0, maxspa
re=1)
And when I navigate to the url I get a 500 error. I don't believe this a Django error as my admin mail is configured correctly and I get no notifications.
Any suggestions what I can do to remedy this situation

Do you have a flup installed as suggested by: https://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/?from=olddocs ?
You have to have flup installed in virt_env for your new project.

Related

URL configuration issue with Django app using Bluehost

I'm in the process of deploying my Django app to a production server using Bluehost but keep seeing my site's 404 page. The issue seems to be my URL configuration. When I type http://www.example.com/ into my browser I receive the following :
Request URL: http://www.example.com/public_html/
^main/
^admin/
^accounts/
^media/(?P<path>.*)$
etc..
The current URL, public_html/, didn't match any of these
public_html/ is automatically added to the end of my URL I would like to eliminate the public_html/ entirely so my URL pattern will work as expected. For example
Request URL: http://www.example.com/
Which would then redirect to
Request URL: http://www.example.com/main/
How would I go about changing the default from http://www.example.com/public_html/ to http://www.example.com/ ?
My fcgi file:
AddHandler fcgid-script .fcgi
RewriteEngine on
RewriteBase /
RewriteRule ^(media/.*)$ - [L]
RewriteRule ^(adminmedia/.*)$ - [L]
RewriteCond %{REQUEST_URI} !(cgi-bin/mysite.fcgi)
RewriteRule ^(.*)$ cgi-bin/mysite.fcgi/$1 [L]
My .htaccess file:
#!/home/username/python/bin/python
import sys, os
sys.path.insert(0, "/home/username/python")
sys.path.insert(13, "/home/username/MySite")
os.environ['DJANGO_SETTINGS_MODULE'] = 'MySite.settings'
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")
Is there a possibility this could be an issue with where my files are located on my server? If anyone has experienced this kind of issue before I would greatly appreciate some advice. Thanks!
You have to define following url in your urls.py,
url(r'^$', 'views.home', name='home')
url(r'^main/$', 'views.main', name='main')
then in views.py
def home(request):
return HttpResponseRedirect('/main/')
def main(request):
#some code here.

Django Response Delay for every request

currently, I move my Django application on a production server. The problem is that each request to the server is slower by 1 second, then locallhost. (I don't mean static files. For testing I made ​​a simple VIEW, that not access the database and not contain python code only return string) I did get this values(delay 1 second) ​​of Chrome / Network/ Property - request - Waiting. Property Sending/receiving is normal (cca 1-10ms)
My .htaccess:
AuthType none
Satisfy Any
Allow from All
AddHandler fast-script .fcgi
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /mysite.cgi/$1 [QSA,L]
My mysite.cgi:
#!/usr/bin/python
# -*- coding: utf8 -*-
import sys, os
# to suppress browser output, you should explicitly say so.
import cgitb
cgitb.enable(display=True)
# Add a custom Python path.
# Set the DJANGO_SETTINGS_MODULE environment variable.
os.environ.setdefault("DJANGO_SETTINGS_MODULE","Web.settings")
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="False")
I'm not server admin, so haven´t permission for setting Apache etc.
It is possible that the application not uses FastCGI but CGI? Or something like that?
Thanks
Problem solved by server admin, the server has not installed mod_fcgid.

Setting Django on Shared Host with FastCGI

I know this might be a question often asked, but I tried my best for almost a day to launch my first django website with no results, so please anyone experienced with shared hosting and django to help. Here is any relevant info:
python 2.6 installed on the remote machine at $HOME/.local/lib/
flup and django at same place, all is done by setup.py install --user.
my django project file structure:
$HOME/
projects/django/bw_python/
manage.py
bw_python/
__init__.py
settings.py
urls.py
wsgi.py
site_main/
django app with urls,models, etc...
In $HOME/.bashrc I have the following lines:
export PATH=$HOME/.local/bin:$HOME/.local/usr/bin:$PATH
export PYTHONPATH=$HOME/projects/django:$HOME/projects/django/bw_python:$HOME/projects/django/bw_python/bw_python:$HOME/projects/django/bw_python/site_main:$PYTHONPATH
If I run python interpreter django and flup are working, manage.py runserver works without any errors.
Now in the public_html I have the following bw_python.fcgi script:
#!/usr/bin/env python
import sys, os
# Add a custom Python path.
sys.path.insert(0, "/home5/bwinnova/.local/lib/python")
# Switch to the directory of your project. (Optional.)
os.chdir("/home5/bwinnova/projects/django/bw_python")
# Set the DJANGO_SETTINGS_MODULE environment variable.
os.environ['DJANGO_SETTINGS_MODULE'] = "bw_python.settings"
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")
If I execute ./bw_python.fcgi I get:
WSGIServer: missing FastCGI param REQUEST_METHOD required by WSGI!
WSGIServer: missing FastCGI param SERVER_NAME required by WSGI!
WSGIServer: missing FastCGI param SERVER_PORT required by WSGI!
WSGIServer: missing FastCGI param SERVER_PROTOCOL required by WSGI!
Status: 301 MOVED PERMANENTLY
Content-Type: text/html; charset=utf-8
Location: http://localhost/home/
The .htaccess:
AddHandler fcgid-script .fcgi
RewriteEngine On
RewriteCond %{REQUEST_URI} !-f
RewriteRule ^(.*)$ bw_python.fcgi/$1 [QSA,L]
The chmod on both of these files and including the $HOME/projects/django/bw_python is 755.
And sorry but from the tutorial I'm stuck here? What is the next step to be done? I always get a 500 server error and on the server error log it is only this:
[Fri Jul 27 19:29:14 2012] [warn] RewriteCond: NoCase option for non-regex pattern '-f' is not supported and will be ignored.
Thanks in advance for any help or guidance from here.

How do I redirect domain.com to WWW.domain.com under Django?

How do I go about redirecting all requests for domain.com/... to www.domain.com/... with a 301 in a django site?
Obviously this can't be done in urls.py because you only get the path part of the URL in there.
I can't use mod rewrite in .htaccess, because .htaccess files do nothing under Django (I think).
I'm guessing something in middleware or apache conf?
I'm running Django on a Linux server with Plesk, using mod WSGI
The WebFaction discussion someone pointed out is correct as far as the configuration, you just have to apply it yourself rather than through a control panel.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
Put in .htaccess file, or in main Apache configuration in appropriate context. If inside of a VirtualHost in main Apache configuration, your would have ServerName be www.example.com and ServerAlias be example.com to ensure that virtual host handled both requests.
If you don't have access to any Apache configuration, if need be, it can be done using a WSGI wrapper around the Django WSGI application entry point. Something like:
import django.core.handlers.wsgi
_application = django.core.handlers.wsgi.WSGIHandler()
def application(environ, start_response):
if environ['HTTP_HOST'] != 'www.example.com':
start_response('301 Redirect', [('Location', 'http://www.example.com/'),])
return []
return _application(environ, start_response)
Fixing this up to include the URL within the site and dealing with https is left as an exercise for the reader. :-)
The PREPEND_WWW setting does just that.
There is a lightweight way to do that involving VirtualHosts and mod_alias Redirect directive. You can define two VirtualHosts, one holding the redirect and another holding the site configuration:
<VirtualHost *:80>
ServerName example.com
Redirect permanent / http://www.example.com/
</VirtualHost>
<VirtualHost *:80>
ServerName www.example.com
# real site configuration
</VirtualHost>
And that will do the job.
This also can be done with a middleware.
Some examples:
http://eikke.com/django-domain-redirect-middleware/
https://djangosnippets.org/snippets/510/
https://djangosnippets.org/snippets/434/
This is a better version of snippet-510:
class UrlRedirectMiddleware(object):
"""
This middleware lets you match a specific url and redirect the request to a
new url. You keep a tuple of (regex pattern, redirect) tuples on your site
settings, example:
URL_REDIRECTS = (
(r'(https?)://(www\.)?sample\.com/(.*)$', r'\1://example.com/\3'),
)
"""
def process_request(self, request):
full_url = request.build_absolute_uri()
for url_pattern, redirect in settings.URL_REDIRECTS:
match = re.match(url_pattern, full_url)
if match:
return HttpResponsePermanentRedirect(match.expand(redirect))

WSGIServer errors when trying to run Django app

Firstly, here's my script:
#!/usr/bin/python
import sys, os
sys.path.append('/home/username/python')
sys.path.append("/home/username/python/flup")
sys.path.append("/home/username/python/django")
# more path stuff
os.environ['DJANGO_SETTINGS_MODULE'] = "project.settings"
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")
As was described here.
And here's the error I get when trying to run it from shell:
WSGIServer: missing FastCGI param REQUEST_METHOD required by WSGI!
WSGIServer: missing FastCGI param SERVER_NAME required by WSGI!
WSGIServer: missing FastCGI param SERVER_PORT required by WSGI!
WSGIServer: missing FastCGI param SERVER_PROTOCOL required by WSGI!
Status: 404 NOT FOUND
Content-Type: text/html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<!-- more html which looks to be the correct output -->
My question is, why aren't those params passed automatically by FastCGI? What am I doing wrong? Running the script from my web server just gives me an internal server error.
Instead of the last two lines of my script, I can use
from flup.server.fcgi import WSGIServer
from django.core.handlers.wsgi import WSGIHandler
WSGIServer(WSGIHandler()).run()
But I still get the exact same error...
Solved it. This .htaccess file did the trick, for whatever reason. I swear I tried all this before...
AddHandler fcgid-script .fcgi
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteRule ^(media/.*)$ - [L]
RewriteRule ^(adminmedia/.*)$ - [L]
RewriteCond %{REQUEST_URI} !(cgi-bin/myproject.fcgi)
RewriteRule ^(.*)$ cgi-bin/myproject.fcgi/$1 [L]
The script expects those params to be passed as environment variables. Since they are not present in your shell environment, and the script is not running in the apache fastcgi environment (which provides them), it complains.
Do you have access to apache error logs? What do they say?
Does your host have mod_wsgi support? If so, you could use Django's wsgi handler:
import sys
import os
base = os.path.dirname(os.path.abspath(__file__)) + '/..'
sys.path.append(base)
os.environ['DJANGO_SETTINGS_MODULE'] = 'yourproject.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
Further instructions can be found on the modwsgi wiki, and the Django docs.