6

我正在使用 Django 1.4 测试tastepie 1.9,以为我的网站创建一个基本的 REST API。我正在遵循文档中的初始步骤,但我遇到了困难。

我在全球范围内运行 Django,而不是为这个特定的实现使用 virtualenv。它在浏览器中显示A server error occurred. Please contact the administrator.。我只在 django 服务器上运行它。

这是我尝试访问终端时出现的错误消息http://127.0.0.1:8000/api/sessionuserround/?format=json

[20/Jun/2013 10:26:19] "GET /api/sessionuserround/?format=json HTTP/1.1" 500 99752
Traceback (most recent call last):
  File "/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 67, in __call__
    return self.application(environ, start_response)
  File "/usr/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 241, in __call__
    response = self.get_response(request)
  File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 146, in get_response
    response = debug.technical_404_response(request, e)
  File "/usr/local/lib/python2.7/site-packages/django/views/debug.py", line 443, in technical_404_response
    'reason': smart_str(exception, errors='replace'),
  File "/usr/local/lib/python2.7/site-packages/django/utils/encoding.py", line 116, in smart_str
    return str(s)
  File "/usr/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 235, in __repr__
    return smart_str(u'<%s %s (%s:%s) %s>' % (self.__class__.__name__, self.urlconf_name, self.app_name, self.namespace, self.regex.pattern))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcb in position 0: ordinal not in range(128)
[20/Jun/2013 10:26:40] "GET /api/sessionuserround/?format=json HTTP/1.1" 500 59
Traceback (most recent call last):
  File "/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 67, in __call__
    return self.application(environ, start_response)
  File "/usr/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 241, in __call__
    response = self.get_response(request)
  File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 146, in get_response
    response = debug.technical_404_response(request, e)
  File "/usr/local/lib/python2.7/site-packages/django/views/debug.py", line 443, in technical_404_response
    'reason': smart_str(exception, errors='replace'),
  File "/usr/local/lib/python2.7/site-packages/django/utils/encoding.py", line 116, in smart_str
    return str(s)
  File "/usr/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 235, in __repr__
    return smart_str(u'<%s %s (%s:%s) %s>' % (self.__class__.__name__, self.urlconf_name, self.app_name, self.namespace, self.regex.pattern))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcb in position 0: ordinal not in range(128)

这些是我的相关文件:

存在于 sal 中的 api.py(我的应用程序的名称):

from tastypie.resources import ModelResource
from sal.models import SessionUserRoundMap


class SessionUserRoundResource(ModelResource):

    class Meta:
        queryset = SessionUserRoundMap.objects.all()

这是 urls.py:

from django.conf.urls.defaults import *
from sal.api import SessionUserRoundResource

sessionuserround_resource = SessionUserRoundResource

urlpatterns = patterns('',
                      (r'ˆapi/', include(sessionuserround_resource.urls)),
                       )

models.py中的相关代码:

class SessionRoundMap(models.Model):

    session_id = models.ForeignKey(Session)
    num_of_rounds = models.IntegerField()

    def __unicode(self):
        text = "Session ID: " + str(self.session_id)
        return text

class SessionUserRoundMap(models.Model):
    user_id = models.ForeignKey(BssUser)
    session_id = models.ForeignKey(Session)
    round_no = models.IntegerField()

    def __unicode__(self):
        return self.user_id + ' ' + self.session_id + ' ' + round_no

settings.py中的相关代码:

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    'admin',
    'tastypie',
)

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',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

现在,我的 views.py 是空的。

这是requirements.txt:

Django==1.4.5
defusedxml==0.4.1
distribute==0.6.40
django-tastypie==0.9.15
dulwich==0.9.0
hg-git==0.4.0
lxml==3.2.1
mercurial==2.6.2
mimeparse==0.1.3
python-dateutil==1.5
python-mimeparse==0.1.4
vboxapi==1.0
virtualenv==1.9.1
wsgiref==0.1.2

我怎么解决这个问题?请帮忙!

4

4 回答 4

6

出现错误是因为我的模型中的某些模型在实例化时没有返回正确的 unicode 编码响应。

这是因为我的 models.py 中有错字:

class SessionRoundMap(models.Model):

    session_id = models.ForeignKey(Session)
    num_of_rounds = models.IntegerField()

    def __unicode(self):
        text = "Session ID: " + str(self.session_id)
        return text

它应该是这样的:

class SessionRoundMap(models.Model):

    session_id = models.ForeignKey(Session)
    num_of_rounds = models.IntegerField()

    def __unicode__(self):
        text = "Session ID: " + str(self.session_id)
        return text

unicode 方法未正确编写,导致此错误。

于 2013-06-20T09:29:52.313 回答
4

使用 ugettext 帮助程序向我的网站添加翻译后出现此错误,即

from django.utils.translation import ugettext as _

所以任何带有非 ascii 文本的东西都会抛出这些错误,即重音符号

messages.success(request, _('Location {0} was deleted.'.format(location_id)))

通过在它周围添加 u 来指定字符串是 unicode 来修复它:

messages.success(request, _(u'Location {0} was deleted.'.format(location_id)))
于 2014-03-12T20:38:45.063 回答
2

在您的数据库中的某处,您有奇怪的记录,其中包含一些非 ascii 代码。

试着写出你的记录,例如:

for item in .....all():
   print item.name (ect.)

如果仍然出现错误,请尝试使用此功能:

def strip_non_ascii(string):
''' Returns the string without non ASCII characters'''
  stripped = (c for c in string if 0 < ord(c) < 127)
  return ''.join(stripped)
于 2013-06-20T06:40:59.730 回答
1

添加到上面的答案:这可能发生的另一个原因是如果您有一个 HTTP 服务器正在运行并请求一个 https 连接。

于 2016-06-26T18:31:46.513 回答