【问题标题】:UnicodeDecodeError: 'utf8' codec can't decode byte 0xc7 in position 27: invalid continuation byte djangoUnicodeDecodeError:“utf8”编解码器无法解码位置 27 中的字节 0xc7:无效的延续字节 django
【发布时间】:2018-05-11 13:45:55
【问题描述】:

我正在尝试将我的 django 项目上传到 Google Cloud Platform。

当我跑步时

python manage.py runserver

发生错误。

直到不久前,它运作良好。

仅修复一个文件“setting.py”的代码后发生错误。

这是下面的屏幕截图。

C:\Users\sgc109\PycharmProjects\pyproj\djenv\Scripts\python.exe C:/Users/sgc109/PycharmProjects/pyproj/my_project/manage.py runserver
Traceback (most recent call last):
  File "C:/Users/sgc109/PycharmProjects/pyproj/my_project/manage.py", line 24, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\core\management\__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\core\management\commands\runserver.py", line 62, in execute
    super(Command, self).execute(*args, **options)
  File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\core\management\base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\core\management\commands\runserver.py", line 101, in handle
    self.run(**options)
  File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in run
    autoreload.main(self.inner_run, None, options)
  File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\utils\autoreload.py", line 341, in main
    reloader(wrapped_main_func, args, kwargs)
  File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\utils\autoreload.py", line 312, in python_reloader
    exit_code = restart_with_reloader()
  File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\utils\autoreload.py", line 294, in restart_with_reloader
    str_value = force_bytes(new_environ[key], encoding=encoding)
  File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\site-packages\django\utils\encoding.py", line 124, in force_bytes
    return s.decode('utf-8', errors).encode(encoding, errors)
  File "C:\Users\sgc109\PycharmProjects\pyproj\djenv\lib\encodings\utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xc7 in position 27: invalid continuation byte

Process finished with exit code 1

我已尽力在 Google 和 Stackoverflow 上找到解决方案,并且

我努力想在我的代码中找到错误,但我找不到任何东西。

下面是我的目录结构、主要代码和项目解释器设置。 (因为我从来没有改变过其他的

我的项目代码太多,代码量太多,就不全部上传了

我的 django 项目中的代码。)

views.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.


def home(request):
    return HttpResponse("Hello, world!")

urls.py

from django.conf.urls import url
from django.contrib import admin
from my_app import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.home)
]

settings.py

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'secret key'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'my_app',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'my_project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'my_project.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'):
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'HOST': '/cloudsql/DB Project',
            'NAME': 'db-project-185409:asia-northeast1:sgc109',
            'USER': 'user',
            'PASSWORD': 'password',
        }
    }
else:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }

# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'

STATIC_ROOT = 'static'

ma​​nage.py

#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError:
        # The above import may fail for some other reason. Ensure that the
        # issue is really that Django is missing to avoid masking other
        # exceptions on Python 2.
        try:
            import django
        except ImportError:
            raise ImportError(
                "Couldn't import Django. Are you sure it's installed and "
                "available on your PYTHONPATH environment variable? Did you "
                "forget to activate a virtual environment?"
            )
        raise
    execute_from_command_line(sys.argv)

我认为我犯了一个错误的一件事是

我为安装 Django 和 MySQL-python 执行了“pip install”

不在虚拟环境中,又在虚拟环境中做了。

但我不确定它是否会影响错误。

感谢大家阅读我的问题。

已添加

我调试了我的代码,发现一些包含韩语单词的目录名已被传递给某个函数,但我不知道为什么在世界上传递了目录名。我认为传递的目录与我的 django 项目的目录没有关系。下面是截图。

已添加2

我发现该目录是包含在

中的目录之一

环境变量。所以我从环境变量中删除了那个目录

然后重新启动我的电脑,然后它工作了!!

【问题讨论】:

  • 你能把你的manager.py文件放在这里吗?
  • 当然,我现在在我的问题中添加了它。
  • 尝试在您的manage.py 顶部添加# -*- coding: utf-8 -*-
  • 好的,我试过了,还是不行
  • 您应该通过Error information 而不是图片来搜索您的问题! https://stackoverflow.com/questions/30900294/django-unicodedecodeerror-in-model-object/30900564#30900564 这里也许是你要去的地方!

标签: python mysql django utf-8


【解决方案1】:

那C7 应该是Ç 吗?如果是这样,您将 latin1 字节视为 utf8。它不起作用。

另一方面,如果你指定你有 latin1 字节,mysql 很乐意转换为 utf8。

请参阅Trouble with UTF-8 characters; what I see is not what I stored 中的“最佳实践” 这里有一些关于 python 的随机注释:http://mysql.rjweb.org/doc.php/charcoll#python 超出了coding: 子句。并在该文章中搜索“Django”以了解如何设置 OPTIONS 子句。

【讨论】:

  • 您是否偶然阅读了我的整篇文章?我自己解决了我的问题,并编辑了我的问题以帮助其他会遇到我遇到的问题的人。
猜你喜欢
  • 1970-01-01
  • 2013-04-04
  • 1970-01-01
  • 2014-04-08
  • 2013-10-02
  • 2016-11-25
  • 2016-11-15
  • 2019-01-04
  • 1970-01-01
相关资源
最近更新 更多