1. 先描述一下昨天遇到的問題
(1)裝了Django REST framework,運行django時,出現錯誤提示:
ImportError: cannot import name 'six' from 'django.utils'
(2)於是我import six,發覺有,猜想會不會是因為沒有放在django.utils下的緣故,於是復制了一份過去,還是出現了錯誤,好在不是上面的錯誤了:
ImportError: cannot import name 'moves' from 'django.utils'
於是我如法炮制,也把moves復制了一份到django.utils里面
(3)結果更奇葩的出現了,這次是沒有builtins。我心想,這個怎么可能沒有,但還是按照上面的做了。果然也沒有再報錯了,但又出現了其他的:
NameError: name 'python_2_unicode_compatible' is not defined
Ctrl+Enter點進去看了一下,是個裝飾器。不知道干嘛用的,但從名字猜,估計是把python2的__unicode__變成python3的__str__。既然我已經裝的python3了,用不着這個,於是注釋掉了。
(4)接下來的錯誤是:
TypeError: 'ellipsis' object is not iterable
這次不知道怎么辦了,於是放棄了。
2. 今天突然想到,會不會是因為版本不兼容的問題
於是把Django 3.0.dev卸載了,重裝了Django 2.2.2,然后再裝了Django REST framework,果然OK了。下面把整個裝載配置過程重述一遍:
(1)安裝Django 2.2.2
pip install Django==2.2.2
(2)運行自己的django項目,如果報錯:
mysqlclient 1.3.13 or newer is required; you have 0.9.3
這並不說明你的mysqlclient版本過低,因為我pip install mysqlclient了一下,提示自己的是1.4.2。點擊報錯文件,把下面代碼注釋掉:
if version < (1, 3, 3):
raise ImproperlyConfigured("mysqlclient 1.3.3 or newer is required; you have %s" % Database.__version__)
(3)接下來,如果報錯:
query = query.decode(errors='replace') AttributeError: 'str' object has no attribute 'decode'
點擊報錯文件,把下面代碼注釋掉:
if query is not None:
query = query.decode(errors='replace')
接下來就可以正常運行了。
3. 安裝和配置rest_framework
(1)安裝
pip install djangorestframework
pip install markdown
pip install django-filter
(2)settings.py
INSTALLED_APP里面添加:'rest_framework'
(3)項目urls.py
urlpatterns里面添加:url(r'^api/', include('app01.urls')),其中app01改為你自己的app名
(4)app01下的urls.py
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets
# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'is_staff')
# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
]
(5)url欄輸入http://127.0.0.1:8001/api/,ip和port改成你自己設置的。