Python's Archiver

為方便港臺同胞閱覽,Python中國特別推出簡繁體內容轉換功能

mountainhunter 发表于 2008-11-19 11:03

请教MySQLdb模块的字符集、校正的问题、django session

>>> conn = MySQLdb.connection(host ="",user = "root", passwd = "123456",  db = "django_test");
>>>
>>> charset = conn.character_set_name()
>>> charset
'latin1_swedish_ci'
---------------------------------------------------------
数据库的字符集明明是latin1,'latin1_swedish_ci'是相应的collation,这里字符集居然返回的是'latin1_swedish_ci',然后编码就出错
LookupError: unknown encoding: latin1_swedish_ci
晕啦
我是在用django的session的时候,需要创建相应的数据库表,操作如下命令
./manage.py syncdb
报错的,我跟踪了一下,发现在MySQLdb模块的cursors.py文件的第146-149行
        db = self._get_db()
        charset = db.character_set_name()
        if isinstance(query, unicode):
            query = query.encode(charset)
这里返回的charset就是'latin1_swedish_ci',然后用 query = query.encode('latin1_swedish_ci')编码,就报错啦!!

这是不是MySQLdb的bug阿????

哪位高人能给指点一二啊。

zjxplq 发表于 2008-11-19 11:08

把报错信息发上来看看

xieaotian 发表于 2008-11-19 11:30

django setting里需要设置编码,需要 符合数据库编码
也就是说,数据库为latin1,那么setting   也要一样

mountainhunter 发表于 2008-11-19 13:34

情况一:
[color=Blue]数据库字符集是latin1:[/color]
mysql> show create database django_test;
+-------------+------------------------------------------------------------------------+
| Database    | Create Database                                                        |
+-------------+------------------------------------------------------------------------+
| django_test | CREATE DATABASE `django_test` /*!40100 DEFAULT CHARACTER SET [color=Red]latin1[/color] */ |
+-------------+------------------------------------------------------------------------+
1 row in set (0.00 sec)
[color=Blue]django setting:[/color]
[root@vHost-RH9 newtest_django]# cat settings.py
# Django settings for newtest_django project.

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@domain.com'),
)

MANAGERS = ADMINS

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

[color=Red]DEFAULT_CHARSET = 'latin1'[/color]


# Local time zone for this installation. Choices can be found here:
# [url]http://en.wikipedia.org/wiki/List_of_tz_zones_by_name[/url]
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# [url]http://www.i18nguy.com/unicode/language-identifiers.html[/url]
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''

# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'

# Make this unique, and don't share it with anybody.
SECRET_KEY = '&yy&2wkg%g_@r^gf$za95-7a@#7t0j6t=(8h(^5*82+g@&d&s#'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.load_template_source',
    'django.template.loaders.app_directories.load_template_source',
#     'django.template.loaders.eggs.load_template_source',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
)

ROOT_URLCONF = 'newtest_django.urls'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
        './templates',

)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
)
[color=Blue]执行同步数据库命令出错结果:[/color]
[root@vHost-RH9 newtest_django]# ./manage.py syncdb
Traceback (most recent call last):
  File "./manage.py", line 11, in <module>
    execute_manager(settings)
  File "/usr/local/lib/python2.5/site-packages/django/core/management/__init__.py", line 340, in execute_manager
    utility.execute()
  File "/usr/local/lib/python2.5/site-packages/django/core/management/__init__.py", line 295, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.5/site-packages/django/core/management/base.py", line 77, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/usr/local/lib/python2.5/site-packages/django/core/management/base.py", line 96, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.5/site-packages/django/core/management/base.py", line 178, in handle
    return self.handle_noargs(**options)
  File "/usr/local/lib/python2.5/site-packages/django/core/management/commands/syncdb.py", line 101, in handle_noargs
    emit_post_sync_signal(created_models, verbosity, interactive)
  File "/usr/local/lib/python2.5/site-packages/django/core/management/sql.py", line 205, in emit_post_sync_signal
    interactive=interactive)
  File "/usr/local/lib/python2.5/site-packages/django/dispatch/dispatcher.py", line 148, in send
    response = receiver(signal=self, sender=sender, **named)
  File "/usr/local/lib/python2.5/site-packages/django/contrib/auth/management/__init__.py", line 25, in create_permissions
    ctype = ContentType.objects.get_for_model(klass)
  File "/usr/local/lib/python2.5/site-packages/django/contrib/contenttypes/models.py", line 28, in get_for_model
    defaults = {'name': smart_unicode(opts.verbose_name_raw)},
  File "/usr/local/lib/python2.5/site-packages/django/db/models/manager.py", line 96, in get_or_create
    return self.get_query_set().get_or_create(**kwargs)
  File "/usr/local/lib/python2.5/site-packages/django/db/models/query.py", line 326, in get_or_create
    return self.get(**kwargs), False
  File "/usr/local/lib/python2.5/site-packages/django/db/models/query.py", line 298, in get
    num = len(clone)
  File "/usr/local/lib/python2.5/site-packages/django/db/models/query.py", line 154, in __len__
    self._result_cache = list(self.iterator())
  File "/usr/local/lib/python2.5/site-packages/django/db/models/query.py", line 269, in iterator
    for row in self.query.results_iter():
  File "/usr/local/lib/python2.5/site-packages/django/db/models/sql/query.py", line 206, in results_iter
    for rows in self.execute_sql(MULTI):
  File "/usr/local/lib/python2.5/site-packages/django/db/models/sql/query.py", line 1700, in execute_sql
    cursor.execute(sql, params)
  File "/usr/local/lib/python2.5/site-packages/django/db/backends/util.py", line 19, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.5/site-packages/django/db/backends/mysql/base.py", line 83, in execute
    return self.cursor.execute(query, args)
  File "/usr/local/lib/python2.5/site-packages/MySQL_python-1.2.2-py2.5-linux-i686.egg/MySQLdb/cursors.py", line 166, in execute
  File "/usr/local/lib/python2.5/site-packages/MySQL_python-1.2.2-py2.5-linux-i686.egg/MySQLdb/connections.py", line 35, in defaulterrorhandler
[color=Red]_mysql_exceptions.OperationalError: (1267, "Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '='")[/color]

[[i] 本帖最后由 mountainhunter 于 2008-11-19 13:46 编辑 [/i]]

mountainhunter 发表于 2008-11-19 13:42

情况二:
[color=Blue]数据库字符集:[/color]
mysql> show create database django_test;
+-------------+----------------------------------------------------------------------+
| Database    | Create Database                                                      |
+-------------+----------------------------------------------------------------------+
| django_test | CREATE DATABASE `django_test` /*!40100 DEFAULT CHARACTER SET [color=Red]utf8[/color] */ |
+-------------+----------------------------------------------------------------------+
1 row in set (0.00 sec)
[color=Blue]django setting:[/color]
[root@vHost-RH9 newtest_django]# cat settings.py
# Django settings for newtest_django project.

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@domain.com'),
)

MANAGERS = ADMINS

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

[color=Red]DEFAULT_CHARSET = 'utf-8'[/color]


# Local time zone for this installation. Choices can be found here:
# [url]http://en.wikipedia.org/wiki/List_of_tz_zones_by_name[/url]
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# [url]http://www.i18nguy.com/unicode/language-identifiers.html[/url]
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''

# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'

# Make this unique, and don't share it with anybody.
SECRET_KEY = '&yy&2wkg%g_@r^gf$za95-7a@#7t0j6t=(8h(^5*82+g@&d&s#'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.load_template_source',
    'django.template.loaders.app_directories.load_template_source',
#     'django.template.loaders.eggs.load_template_source',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
)

ROOT_URLCONF = 'newtest_django.urls'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
        './templates',

)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
)

[color=Blue]错误输出:[/color]
[root@vHost-RH9 newtest_django]# ./manage.py syncdb
Creating table auth_permission
Creating table auth_group
Creating table auth_user
Creating table auth_message
Creating table django_content_type
Creating table django_session
Creating table django_site

You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (Leave blank to use 'root'):
E-mail address: [email]adaa@163.com[/email]
Password:
Password (again):
Traceback (most recent call last):
  File "./manage.py", line 11, in <module>
    execute_manager(settings)
  File "/usr/local/lib/python2.5/site-packages/django/core/management/__init__.py", line 340, in execute_manager
    utility.execute()
  File "/usr/local/lib/python2.5/site-packages/django/core/management/__init__.py", line 295, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.5/site-packages/django/core/management/base.py", line 77, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/usr/local/lib/python2.5/site-packages/django/core/management/base.py", line 96, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.5/site-packages/django/core/management/base.py", line 178, in handle
    return self.handle_noargs(**options)
  File "/usr/local/lib/python2.5/site-packages/django/core/management/commands/syncdb.py", line 101, in handle_noargs
    emit_post_sync_signal(created_models, verbosity, interactive)
  File "/usr/local/lib/python2.5/site-packages/django/core/management/sql.py", line 205, in emit_post_sync_signal
    interactive=interactive)
  File "/usr/local/lib/python2.5/site-packages/django/dispatch/dispatcher.py", line 148, in send
    response = receiver(signal=self, sender=sender, **named)
  File "/usr/local/lib/python2.5/site-packages/django/contrib/auth/management/__init__.py", line 44, in create_superuser
    call_command("createsuperuser", interactive=True)
  File "/usr/local/lib/python2.5/site-packages/django/core/management/__init__.py", line 158, in call_command
    return klass.execute(*args, **options)
  File "/usr/local/lib/python2.5/site-packages/django/core/management/base.py", line 96, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 131, in handle
    User.objects.create_superuser(username, email, password)
  File "/usr/local/lib/python2.5/site-packages/django/contrib/auth/models.py", line 122, in create_superuser
    u.save()
  File "/usr/local/lib/python2.5/site-packages/django/db/models/base.py", line 307, in save
    self.save_base(force_insert=force_insert, force_update=force_update)
  File "/usr/local/lib/python2.5/site-packages/django/db/models/base.py", line 354, in save_base
    manager.filter(pk=pk_val).extra(select={'a': 1}).values('a').order_by())):
  File "/usr/local/lib/python2.5/site-packages/django/db/models/query.py", line 185, in __nonzero__
    iter(self).next()
  File "/usr/local/lib/python2.5/site-packages/django/db/models/query.py", line 179, in _result_iter
    self._fill_cache()
  File "/usr/local/lib/python2.5/site-packages/django/db/models/query.py", line 612, in _fill_cache
    self._result_cache.append(self._iter.next())
  File "/usr/local/lib/python2.5/site-packages/django/db/models/query.py", line 653, in iterator
    for row in self.query.results_iter():
  File "/usr/local/lib/python2.5/site-packages/django/db/models/sql/query.py", line 206, in results_iter
    for rows in self.execute_sql(MULTI):
  File "/usr/local/lib/python2.5/site-packages/django/db/models/sql/query.py", line 1700, in execute_sql
    cursor.execute(sql, params)
  File "/usr/local/lib/python2.5/site-packages/django/db/backends/util.py", line 19, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.5/site-packages/django/db/backends/mysql/base.py", line 83, in execute
    return self.cursor.execute(query, args)
  File "/usr/local/lib/python2.5/site-packages/MySQL_python-1.2.2-py2.5-linux-i686.egg/MySQLdb/cursors.py", line 149, in execute
[color=Red]LookupError: unknown encoding: latin1_swedish_ci[/color]

[[i] 本帖最后由 mountainhunter 于 2008-11-19 13:45 编辑 [/i]]

mountainhunter 发表于 2008-11-19 13:47

多谢楼上二位

zjxplq 发表于 2008-11-19 14:12

我建议你找一下limodou,他是python牛人,django也深有研究的。他的邮箱等网上搜一下就行

页: [1]

Powered by Discuz! Archiver 6.1.0  © 2001-2007 Comsenz Inc.