LINUXQQ

八月 29, 2011

django 全局变量

Filed under: python — admin @ 10:07 上午

首先,request对象并不是自动作为可用的 Context 变量的。在 global_settings.py 中有一段 Context 处理器的定义:

# List of processors used by RequestContext to populate the context.
# Each one should be a callable that takes the request object as its
# only parameter and returns a dictionary to add to the context.
TEMPLATE_CONTEXT_PROCESSORS = (
    ‘django.core.context_processors.auth’,
    ‘django.core.context_processors.debug’,
    ‘django.core.context_processors.i18n’,
#    ‘django.core.context_processors.request’,
)

注意,这个Context处理器的配置只对RequestContext生效。request并不是缺省可用的。那么我现在就是需要增加一个自定义的SiteInfo处理器即可。

这个SiteInfo处理器很简单:

from apps.site.models import BlogSite

def siteinfo(request):
    sites = BlogSite.objects.all()
    if len(sites) > 0:
        site = sites[0]
    else:
        site = None
    return {’site’: site}

然后在 settings.py 中定义:

TEMPLATE_CONTEXT_PROCESSORS = (
    ‘django.core.context_processors.auth’,
    ‘django.core.context_processors.debug’,
    ‘django.core.context_processors.i18n’,
    ‘django.core.context_processors.request’,
    ‘utils.sitecontext.siteinfo’,
)

同时因为为了处理user,我的View中的Context基本上都是使用的 RequestContext,所以这块工作就省了。然后再在几个基础模板中增加 {{ site.othercode }} 这样就完成了。

整个处理还是比较简单。

八月 22, 2011

Django数据库模型的字段类型

Filed under: python — admin @ 1:38 下午

V=models.CharField(max_length=None[, **options])    #varchar

V=models.EmailField([max_length=75, **options])    #varchar
V=models.URLField([verify_exists=True, max_length=200, **options])    #varchar
V=models.FileField(upload_to=None[, max_length=100, **options])    #varchar
#upload_to指定保存目录可带格式,
V=models.ImageField(upload_to=None[, height_field=None, width_field=None, max_length=100, **options])
V=models.IPAddressField([**options])    #varchar
V=models.FilePathField(path=None[, match=None, recursive=False, max_length=100, **options]) #varchar
V=models.SlugField([max_length=50, **options])    #varchar,标签,内含索引
V=models.CommaSeparatedIntegerField(max_length=None[, **options])    #varchar

V=models.IntegerField([**options])    #int
V=models.PositiveIntegerField([**options])    #int 正整数
V=models.SmallIntegerField([**options])    #smallint
V=models.PositiveSmallIntegerField([**options])    #smallint 正整数
V=models.AutoField(**options)    #int;在Django代码内是自增
V=models.DecimalField(max_digits=None, decimal_places=None[, **options])    #decimal
V=models.FloatField([**options])    #real

V=models.BooleanField(**options)    #boolean或bit

V=models.NullBooleanField([**options])    #bit字段上可以设置上null值

V=models.DateField([auto_now=False, auto_now_add=False, **options])    #date
#auto_now最后修改记录的日期;auto_now_add添加记录的日期
V=models.DateTimeField([auto_now=False, auto_now_add=False, **options])    #datetime
V=models.TimeField([auto_now=False, auto_now_add=False, **options])    #time

V=models.TextField([**options])    #text
V=models.XMLField(schema_path=None[, **options])    #text

——————————————————————————–
V=models.ForeignKey(othermodel[, **options])    #外键,关联其它模型,创建关联索引
V=models.ManyToManyField(othermodel[, **options])    #多对多,关联其它模型,创建关联表
V=models.OneToOneField(othermodel[, parent_link=False, **options])    #一对一,字段关联表属性

1.   from django.db.backends.creation import BaseDatabaseCreation
2.
3.   class DatabaseCreation(BaseDatabaseCreation):
4.       # This dictionary maps Field objects to their associated MySQL column
5.       # types, as strings. Column-type strings can contain format strings; they’ll
6.       # be interpolated against the values of Field.__dict__ before being output.
7.       # If a column type is set to None, it won’t be included in the output.
8.       data_types = {
9.           ’AutoField’:         ’integer AUTO_INCREMENT’,
10.           ’BooleanField’:      ’bool’,
11.           ’CharField’:         ’varchar(%(max_length)s)’,
12.           ’CommaSeparatedIntegerField’: ’varchar(%(max_length)s)’,
13.           ’DateField’:         ’date’,
14.           ’DateTimeField’:     ’datetime’,
15.           ’DecimalField’:      ’numeric(%(max_digits)s, %(decimal_places)s)’,
16.           ’FileField’:         ’varchar(%(max_length)s)’,
17.           ’FilePathField’:     ’varchar(%(max_length)s)’,
18.           ’FloatField’:        ’double precision’,
19.           ’IntegerField’:      ’integer’,
20.           ’BigIntegerField’:   ’bigint’,
21.           ’IPAddressField’:    ’char(15)’,
22.           ’NullBooleanField’:  ’bool’,
23.           ’OneToOneField’:     ’integer’,
24.           ’PositiveIntegerField’: ’integer UNSIGNED’,
25.           ’PositiveSmallIntegerField’: ’smallint UNSIGNED’,
26.           ’SlugField’:         ’varchar(%(max_length)s)’,
27.           ’SmallIntegerField’: ’smallint’,
28.           ’TextField’:         ’longtext’,

29.           ’TimeField’:         ’time’,
30.       }
31.
32.       def sql_table_creation_suffix(self):
33.           suffix = []
34.           if self.connection.settings_dict['TEST_CHARSET']:
35.               suffix.append(‘CHARACTER SET %s’ % self.connection.settings_dict['TEST_CHARSET'])
36.           if self.connection.settings_dict['TEST_COLLATION']:
37.               suffix.append(‘COLLATE %s’ % self.connection.settings_dict['TEST_COLLATION'])
38.           return ’ ’.join(suffix)
39.
40.       def sql_for_inline_foreign_key_references(self, field, known_models, style):
41.           ”All inline references are pending under MySQL”
42.           return [], True
43.
44.       def sql_for_inline_many_to_many_references(self, model, field, style):
45.           from django.db import models
46.           opts = model._meta
47.           qn = self.connection.ops.quote_name
48.
49.           table_output = [
50.               '    %s %s %s,' %
51.                   (style.SQL_FIELD(qn(field.m2m_column_name())),
52.                   style.SQL_COLTYPE(models.ForeignKey(model).db_type(connection=self.connection)),
53.                   style.SQL_KEYWORD('NOT NULL')),
54.               '    %s %s %s,' %
55.               (style.SQL_FIELD(qn(field.m2m_reverse_name())),
56.               style.SQL_COLTYPE(models.ForeignKey(field.rel.to).db_type(connection=self.connection)),
57.               style.SQL_KEYWORD('NOT NULL'))
58.           ]
59.           deferred = [
60.               (field.m2m_db_table(), field.m2m_column_name(), opts.db_table,
61.                   opts.pk.column),
62.               (field.m2m_db_table(), field.m2m_reverse_name(),
63.                   field.rel.to._meta.db_table, field.rel.to._meta.pk.column)
64.               ]
65.           return table_output, deferred
objects.values_list 查询列的数据

八月 12, 2011

apache django admin 配置

Filed under: python — admin @ 11:58 上午

我把我的配置直接COPY进来,下面是APACHE里面的配置

<VirtualHost 192.168.1.2>
    ServerAdmin linuxqq@linuxqq.net
    DocumentRoot “/var/mysite”
    ServerName py.linuxqq.net
ErrorLog “logs/py.linuxqq.net-error_log”
    CustomLog “logs/py.linuxqq.net_log” common
    <Directory “/var/mysite”>
            Options Indexes FollowSymLinks
            AllowOverride None
            Order allow,deny
            Allow from all
    </Directory>
    Alias /media /var/mysite/html/media/
    <Location “/”>
            SetHandler python-program
            PythonHandler django.core.handlers.modpython
            PythonPath “['/var/mysite','/usr/lib/python2.4/site-packages/django/']+sys.path”
            SetEnv DJANGO_SETTINGS_MODULE settings
            SetEnv PYTHON_EGG_CACHE /tmp/mysite
            PythonDebug On
    </Location>
    <Location “/media/”>
       SetHandler None
    </Location>
    <LocationMatch “(?i)\.(jpg|gif|png|txt|ico|pdf|css|jpeg)$”>
       SetHandler None
    </LocationMatch>
</VirtualHost>

下面是DJANGO的SETTING的配置

DEBUG = False
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # (‘Your Name’, ‘your_email@example.com’),
)

MANAGERS = ADMINS

DATABASES = {
    ‘default’: {
        ‘ENGINE’: ‘django.db.backends.mysql’, # Add ‘postgresql_psycopg2′, ‘postgresql’, ‘mysql’, ‘sqlite3′ or ‘oracle’.
        ‘NAME’: ‘python’,                      # Or path to database file if using sqlite3.
        ‘USER’: ‘root’,                      # Not used with sqlite3.
        ‘PASSWORD’: ’123456789′,                  # Not used with sqlite3.
        ‘HOST’: ‘localhost’,                      # Set to empty string for localhost. Not used with sqlite3.
        ‘PORT’: ’3306′,                      # Set to empty string for default. Not used with sqlite3.
    }
}

TIME_ZONE = ‘America/Chicago’

LANGUAGE_CODE = ‘zh-CN’

SITE_ID = 1

USE_I18N = True

USE_L10N = True

MEDIA_ROOT = ‘/var/mysite/html’

MEDIA_URL = ‘http://py.linuxqq.net/media/’

STATIC_ROOT = ‘/var/mysite/html/media/’

STATIC_URL = ‘http://py.linuxqq.net/media/’

ADMIN_MEDIA_PREFIX = ‘http://py.linuxqq.net/media/’

STATICFILES_DIRS = (
    # Put strings here, like “/home/html/static” or “C:/www/django/static”.
    # Always use forward slashes, even on Windows.
    # Don’t forget to use absolute paths, not relative paths.
)

STATICFILES_FINDERS = (
    ‘django.contrib.staticfiles.finders.FileSystemFinder’,
    ‘django.contrib.staticfiles.finders.AppDirectoriesFinder’,

)

SECRET_KEY = ’8*v*#(wuh)g%#5ms-ytp%)apkadu508_9&8n2$b8&xdm^hn7xx’

TEMPLATE_LOADERS = (
    ‘django.template.loaders.filesystem.Loader’,
    ‘django.template.loaders.app_directories.Loader’,
)

MIDDLEWARE_CLASSES = (
    ‘django.middleware.common.CommonMiddleware’,
    ‘django.contrib.sessions.middleware.SessionMiddleware’,
    ‘django.middleware.csrf.CsrfViewMiddleware’,
    ‘django.contrib.auth.middleware.AuthenticationMiddleware’,
    ‘django.contrib.messages.middleware.MessageMiddleware’,
)

ROOT_URLCONF = ‘urls’

TEMPLATE_DIRS = (
           ‘/var/mysite/html’,
)

INSTALLED_APPS = (
    ‘django.contrib.auth’,
    ‘django.contrib.contenttypes’,
   ‘django.contrib.sessions’,
     ‘django.contrib.admin’,
     ‘books’,
)

LOGGING = {
    ‘version’: 1,
    ‘disable_existing_loggers’: False,
    ‘handlers’: {
        ‘mail_admins’: {
            ‘level’: ‘ERROR’,
            ‘class’: ‘django.utils.log.AdminEmailHandler’
        }
    },
    ‘loggers’: {
        ‘django.request’: {
            ‘handlers’: ['mail_admins'],
            ‘level’: ‘ERROR’,
            ‘propagate’: True,
        },
    }
}

下面是模型的步骤的步骤

首先在修改MODEL.PY 建立模型

from django.db import models
class BlogPost(models.Model):
    title = models.CharField(max_length=150)
    body = models.TextField()
    timestamp = models.DateTimeField()

然后去admin.py里面注册下

rom django.contrib import admin
from books.models import BlogPost

admin.site.register(BlogPost)

八月 11, 2011

apache加载python

Filed under: python — admin @ 11:15 上午

前一篇文章写的在APACHE安装MOD_PYTHON的经过,其实挺简单,就是版本不兼容的问题.这次我大概说下部署DJANGO的过程.

先修改APACHE配置文件,使其加载mod_python模块

LoadModule python_module libexec/mod_python.so

运行命令查看

bin/httpd -M可以看到

 python_module (shared)
Syntax OK

说明apache已经成功加载mod_python.

下面我说下我的实际的环境和项目情况:

/infoware/xx/web是django程序目录

/infoware/_conf/xx/是控制django的程序还有一些配置(有些配置变量没有写在settings),这一步可以不需要,因为大多数人会直接配置settings文件的.我是在虚拟主机上操作.

–CENTOS5.2+APACHE2.2.11+PYTHON 2.4.3+MOD_PYTHON3.3.1+DJANGO 0.96

下面是apache配置文件

—————————————————-

<VirtualHost *:80>
        ServerAdmin webmaster@xxcom
        DocumentRoot “/infoware/xx/web”
        ServerName www1.xx.com
        ServerAlias www1.xx.com
        ErrorLog “/var/log/apache/xx/xx_error_log”
        CustomLog “/var/log/apache/xx/xx_access_log” common
        <Directory “/infoware/xx/web”>
            Options Indexes FollowSymLinks
            AllowOverride None
            Order allow,deny
            Allow from all

        </Directory>
        <Location “/”>
            SetHandler python-program
            PythonHandler django.core.handlers.modpython
            PythonPath “['/infoware/xx/web']+['/infoware/_conf/xx] + sys.path”
            SetEnv DJANGO_SETTINGS_MODULE settings
            SetEnv PYTHON_EGG_CACHE /tmp/cucrm//这儿是加个变量,会在下面说明
            PythonDebug On
        </Location>
</VirtualHost>

——————————————————————

以上配置一定要注意环境变量的配置,否则会出错!

我在配置前出现了以下错误,##################################################################
Can’t extract file(s) to egg cache The following error occurred while trying to extract file(s) to the Python egg cache: [Errno 13] Permission denied: ‘/root/.python-eggs’ The Python egg cache directory is currently set to: /root/.python-eggs Perhaps your account does not have write access to this directory? You can change the cache directory by setting the PYTHON_EGG_CACHE environment variable to point to an accessible directory.
#################################################################

解决方法就是加环境变量

SetEnv PYTHON_EGG_CACHE /tmp/cucrm//这个目录的权限属主一定要设为APACHE指定的用户,要不就777

大概就这样,仅供参考,如果觉得麻烦的话建议FASTCGI,这个简单点.

Powered by LINUXQQ   ICP 10203065