Posts Tagged ‘Django’

Gentoo下Nginx使用GeoIP模块为Django提供GEO信息

Tuesday, July 27th, 2010

首先要在Gentoo下安装编译Nginx,需要加入GeoIP模块,请参考另一篇文章《Gentoo 安装编译Nginx》。在安装的过程中应该是会自动安装dev-libs/geoip这个包,如果没有的话使用emerge安装:

emerge -avt dev-libs/geoip

下载MaxMind的GEO数据,解压缩放在/etc/nginx目录下:

#Get the free database of geo_city
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
gunzip GeoLiteCity.dat.gz
mv GeoLiteCity.dat /etc/nginx
#Get the free database of geo_coundty
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
gunzip GeoIP.dat.gz
mv GeoIP.dat /etc/nginx

编辑/etc/nginx/nginx.con文件,加入GeoIP的支持:

http {
    geoip_country  /etc/nginx/GeoIP.dat;
    geoip_city     /etc/nginx/GeoLiteCity.dat;
}

编辑django的fastcgi_param:

fastcgi_param GEOIP_COUNTRY_CODE $geoip_city_country_code;
fastcgi_param GEOIP_COUNTRY_CODE3 $geoip_country_code3;
fastcgi_param GEOIP_COUNTRY_NAME $geoip_country_name;
fastcgi_param GEOIP_CITY_COUNTRY_CODE $geoip_city_country_code;
fastcgi_param GEOIP_CITY_COUNTRY_CODE3 $geoip_city_country_code3;
fastcgi_param GEOIP_CITY_COUNTRY_NAME $geoip_city_country_name;
fastcgi_param GEOIP_REGION $geoip_region;
fastcgi_param GEOIP_CITY $geoip_city;
fastcgi_param GEOIP_POSTAL_CODE $geoip_postal_code;
fastcgi_param GEOIP_CITY_CONTINENT_CODE $geoip_city_continent_code;
fastcgi_param GEOIP_LAT $geoip_latitude;
fastcgi_param GEOIP_LNG $geoip_longitude;

在Django的使用方法:

def index(request):
    return HttpResponse(request.META['GEOIP_COUNTRY_CODE'])

[Django] settings.py 中设置访问 MySQL 数据库

Sunday, January 10th, 2010

Django访问数据库的设置是在settings.py中写入数据库的engine、用户名和密码,默认的写法是:

DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 
DATABASE_NAME = 'xxx' # Or path to database file if using sqlite3. 
DATABASE_USER = 'root' # Not used with sqlite3. 
DATABASE_PASSWORD = 'xxx' # Not used with sqlite3. 
DATABASE_HOST = 'localhost' # Set to empty string for localhost. Not used with sqlite3. 
DATABASE_PORT = '3306' # Set to empty string for default. Not used with sqlite3.

数据库的关键信息都写在settings.py中,这样做是非常不安全的。现在可以在settings.py里面使用DATABASE项代替以上的配置项,username和password可以写在配置文件中。下面是把username和password放到MySQL数据库的配置文件中,由DATABASE项读取的示例:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '/etc/mysql/my.cnf',
        },
    }
}
# my.cnf
[client]
database = xxx
user = xxx
password = xxxxxx
default-character-set = utf8

也可以在DATABASES中加入NAME来指定数据库名,client中去除database选项,HOST和PORT这些也都可以写在my.cnf文件中。

Django Template使用相对目录

Saturday, November 7th, 2009

在Django中Template目录要求使用绝对路径,但是这样的配置不便于开发,在settings.py文件中也是可以使用相对目录的配置:

import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
 
TEMPLATE_DIRS = (
    BASE_DIR + '/templates',
)