Serving static files for Django on Webfaction
In my last post I wrote about the setup of Django with virtualenv on the Webfaction hosts. The post did not cover the serving of static files and will be covered here. It's always better to serve static media through an extra HTTP server/container doing nothing but serving static media files for better scaling. Normally I use nginx for this as it is small and fast. For Webfaction hosting you have two possibilities:
You can add a "Static only" application that is an nginx, configure it for a separate (sub)domain and then configure your Django project to use this domain for serving the files. Wasn't that easy!
Or you can use the Apache for serving the files.
Create the "media" folder somewhere on your server (e.g. within the virtualenv folder: /home/<username>/webapps/<wsgi-app>/<virtualenv-dir>/media). Now adjust the apache.conf to load the modules required for serving the media and set some expiration time if you like (I used 12 hours as seen below). I'm only writing the updates to the apache.conf of the last post:
EDIT: had to temporarely disable the snippet, as the host does not answer. Please check for yourself: snipt.org/embed/wmkmm
Django with virtualenv on Webfaction
I really like the Django web framework and I like virtualenv enabling me to use different python configs and packages for different projects. And I have to say I like Webfaction, so easy, so good! (No, I don't get paid by them) This is a quick guide on how to setup Django in virtualenv using mod_wsgi with a Webfaction account.
- Create an "mod_wsgi" application and create a website to use this application
- connect to your accounts shell using ssh
- enable Python 2.6.x as default python (as written in the Webfaction documentation)
- run "vi ~/.bash_profile"
- append the line "alias python=python2.6" (navigate to the last line, push "i" for insertion, write the line, push escape)
- save the file and exit (enter ":wq")
- reload the bash profile "source ~/.bash_profile"
- ensure it worked by checking the Python version "python -V"
- install "pip" and "virtualenv" (be sure to use easy_install-2.6 to use the setuptools of Python 2.6.x):
- enter "easy_install-2.6 -U pip"
- enter "easy_install-2.6 -U virtualenv"
- I like yolk, that enables you to list the installed Python packages, install it using pip if you like
- "pip install yolk"
- Note that these packages (pip, virtualenv, yolk) are installed in your global Python. I recommend to not install any more packages to the global installation as virtualenv enables use to install all packages we need into the virtualenv Python lib.
- navigate to your recently create mod_wsgi webapp, there should be 2 folders, "apache2" and "htdocs"
- create the virtualenv for your project in the wenapp folder, name it like you want, I'll use "ve" here
- "virtualenv --no-site-packages --distribute ve"
- a new folder "ve" with the virtualenv was created. Please refer to the virualenv documentation for more information and usage of virtualenv.
- Now let's install yolk into the virtualenv to see which packages are in there
- either activate the virtualenv and install:
- "source ve/bin/activate"
- "pip install yolk"
- or use pip magic to install into an virtualenv without activating it:
- "pip -E ve install yolk"
- either activate the virtualenv and install:
- now you activate the virtualenv and execute yolk:
- "source ve/bin/activate"
- "yolk -l"
- "deactivate"
- Install Django and any requirements the same way as demonstrated for yolk.
- Assuming you installed Django into the virtualenv and created a Django project, we now must adjust the Apache config
- backup the httpd.conf from /webapps/<yourdjangoapp>/apache2/conf
- create a django.wsgi file somewhere in your webapp dirdctory (I use the conf folder of apache)
- scan the httpd.conf for "Listen XXX", XXX ist the webapp port
- remove the <Directory>...</Directory> segment
- append the following telling the Apache to use the wsgi config we create in the next step:
NameVirtualHost *:<webapp-port>
<VirtualHost *:<webapp-port>>
ServerName <SomeServerName>
WSGIScriptAlias / /home/<your-username>/webapps/<your-webapp-name>/apache2/conf/django.wsgi
</VirtualHost>
- Edit the django.wsgi file:
#!/usr/bin/python
import os, sys, site
# add virtualenv python libs
site.addsitedir('/home/<your-username>/webapps/<your-webapp-name>/ve/lib/python2.6/site-packages')
# append the project path to system path
sys.path.append(/home/<your-username>/webapps/<your-webapp-name>/ve/')
sys.path.append('/home/<your-username>/webapps/<your-webapp-name>/ve/<your-django-project-name>')
# set the settings module
os.environ['DJANGO_SETTINGS_MODULE'] = '<your-django-project-name>.settings'
# init the wsgi handler
from django.core.handlers.wsgi import WSGIHandler
application = WSGIHandler()
- Restart the Apache (/home/<your-username>/webappas/<your-webapp-name>/apache2/bin/restart) and everything should be fine!
Show Django AdminSite fields depending on the current user
Introduction
The auto-created AdminSite in Django is a nifty feature for creating an administrative view of your model classes. Somehow it is not perfect, even if you want to customized it. To guide you to my problem and solution you've to know, that I implemented the SoftDelete behaviour for model classes as described by Greg Allard. It simply adds a 'deleted' field to each model marking it as deleted if its deleted in the admin site (or in some application) but never really gets deleted from the database. So in the admin site there is this field 'deleted' displayed, if you have configured it.
The Problem
My project has 2 different 'usergroups', the editors and the superusers. Superusers should see the 'deleted' fields, the others not. Unfortunatly that is not possible out of the box with Django.
Simple MySQL Backup at Google Code
A while ago I wrote an article about a script I created to backup databases. Since then I had to make little changes and decided to put it to Google code as Open-Source-Project and released the new version 0.1.1 with some minor changes.
If you're interested in the script, head over to its project page and check the appropriate pages like the Changelog and the Installation and Requirements page. Feel free to download and comment it.
MySQL Backup Skript mit Emailversand.
A while ago I found a good script for backing up a MySQL database and sending it via email to a recipient here.
The script is cool, but I didn't like its structure and the fact, that you have to add the database values inline and that it can only backup a single database. For this reason I rewrote it a little and you can download it here.
Features:
- Backup of mutliple databases
- Sending of backups to multiple users
For every single database a mail is send and there is no file saved on the server. And wow: it's really easy to configure!
How do I use it?
- Download the current version (0.1)
- Adjust the backup.php (you're getting help by my wonderful comments)
- upload everything to a directory of your choice
- if applicable, create a cronjob to periodically execute the script
And here the backup.php that calls the appropriate classes and executes the backup (also included in the download):
ini_set('error_reporting', E_ALL); // include the files require_once 'MySQLConfig.php'; require_once 'MySQLBackup.php'; // add some databases to backup // the domain will be appended to the email subject and is also included within the sql file for identification. $cfgHost0 = new MySQLConfig('username0', 'password0', 'database_name0', 'domain0'); $cfgHost1 = new MySQLConfig('username1', 'password1', 'database_name1', 'domain1'); $backup = new MySQLBackup(); // the path to the directory where this script is resided $backup->setExecutionPath('/srv/domain/backup/'); // add the database configs to backup $backup->addDatabaseToBackup($cfgHost0); $backup->addDatabaseToBackup($cfgHost1); // the sender of the backup mail $backup->setSender('admin@yourdomain.com'); // add some people to receive the backup $backup->addRecipient('john@yourdomain.com'); $backup->addRecipient('frank@yourdomain.com'); // execute the whole thing $backup->backup();
If there are any problems or suggestions or feature wishes, please comment this post - thanks!
PS: to create a cronjob log into your server using SSH, then execute "crontab -e" to edit the crontab and insert for example "0 2 * * 0,3 wget http://yourdomain.com/backup/backup.php -nc -q -O /dev/null" for an execution on sunday and wednesday at 2 am. Save and close the whole thing with ":wq" and that's it
Meine Top3-Entwicklungstools
Blog-Parade! Das Ziel, ausgerufen von MSDN Deutschland, ist dabei heute, seine Lieblings-Entwickler-Tools vorzustellen. Da will ich sogleich starten:
Platz 3 nimmt das XAMPP Projekt ein. Mit dieser tollen Sammlung bekommt man alles, was man braucht, um lokal mehr oder minder schöne Webseiten zu entwickeln: Webserver, Datenbank und Emailversendeding. Und man kann es überall mit hin nehmen, z.B. auf den USB Stick.
In der goldenen Mitte steht SVN, die Open-Source-Lösung zur Softwareversionierung. Da ich ja ein alter Windows-Hase bin, nutze ich VisualSVN, den meiner Meinung nach besten und schönsten SVN-Server für Windows, und TortoiseSVN als Client. SVN hat mir schon mehrfach den Arsch gerettet, zum Glück committe ich immer relativ häfig. Auch unverzichtbar beim Entwickeln von TYPO3-Extensions.
Platz Numero Uno nimmt eindeutig die Eclipse IDE bei mir ein. Ohne dieses wertvolle Tool entsteht eigentlich keine Zeile Code. Die Vorteile liegen auf der Hand: kostet nix, zuverlässig, schier unendlich erweiterbar. Ich nutze dabei das Bundle "Eclipse IDE für Java EE Developers", welches zusätzlich mit PDT, Subclipse und dem Google Appengine SDK gepimpt ist. Damit ist eigentlich alles, was ich so programmiere, abgedeckt.
Ich könnte noch ein wenig weiter auflisten, aber das ist jetzt nicht Sinn der Sache. Also nochmal kurz:
1. Eclipse
2. SVN
3. XAMPP
So, und nun her mit meiner X-BOX!
TYPO3 Performance
There are a few nice tipps in the blog of Dmitry Dulepov to speed up the Typo3 performance you should have read. #2 was unknown to me so far.
FE-Plugin bei mehrsprachigem Typo3
Also jedes mal, wenn ich eine mehrsprachige Typo3-Seite erstellen, komme ich durcheinander mit den Sprachen. Und ich vergesse jedes mal, wie man einem Frontend-Plugin sagt, dass es die durch $this->pi_getLL($key) ausgegebenen Texte lokalisiert. Und das geht so:
class tx_extkey_piX extends tslib_pibase {
function main() {
$this->sys_language_uid = (int) t3lib_div::_GP('L');
...
}
}
TYPO3 und UTF-8 mySQL Datenbank
Manchmal ist es nötig, die Datenbank von Typo3 auf UTF-8 umzustellen, da man arabische Zeichen oder was auch immer speichern will, und wobei die Kollation der Datenbank latin1_swedish_ci, mit der sich Typo3 standardmäßig installiert, nicht taugt.
Dazu habe ich diesen nützlichen Blogeintrag von Markus Giesen gefunden: Typo3 mySQL-Datenbank auf UTF-8 umstellen bzw. konvertieren
Jedoch ist bei mir im Export nie die Kollation festgeschrieben, diesen Schritt konnte ich de facto überspringen. Auch hatte ich keinen phpMyAdmin, also mussten die Kommandos für die SQL-Konsole zum Anpassen der Kollation her:
Anzeigen der verfügbaren Kollationen auf dem Server:
SHOW COLLATION SHOW COLLATION LIKE 'utf%'
Ändern der Kollation der aktuellen Datenbank:
ALTER DATABASE DEFAULT COLLATE utf8_general_ci
Und danach weiter nach Markus Giesens Anleitung verfahren und alles wird gut
Symfony Latin – UTF-8 Problem
I'm currently getting into the Symfony framework and I can definitly say that I like it.
But as my site was finished after only some hours I had a problem concerning the display of special characters like the umlauts (ä, ö, ü) aso. I don't use a database created by SF/Propel but use an existing one with latin1_* encoding (the default TYPO3 db encoding). Unfortunatly all umlauts where displayed as questionmark so I started finding an solution. The characters are fuzzy because they were not correctly returned by propel. I tried all configuration directives I found (setting the encoding of the connection to utf-8 aso) but nothing worked.
Finally I found a snippet that fixes the problem for me: Setting UTF-8 for Propel with MySQL tables and now everything is just fine!
