python+django+rest框架配置创建方法

时间:2021-05-22

安装好所需要的插件和包:

python、django、pip等版本如下:

采用Django REST框架3.0

1、在python文件夹下D:\python\Lib\site-packages\django\bin打开cmd命令工具,本人将python文件夹名字改为了wwj,请注意:

mkdir tutorialcd tutorialvirtualenv envsource env/bin/activate pip install djangopip install djangorestframeworkdjango-admin startproject tutorial . cd tutorialdjango-admin startapp quickstartcd ../

2、

python manage.py migratepython manage.py createsuperuser

3、在tutorial\quickstart创建文件serializers.py,并写入一下内容:

from django.contrib.auth.models import User, Groupfrom rest_framework import serializersclass UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'groups')class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ('url', 'name')

3、tutorial\quickstart\views.py中写入:

from django.contrib.auth.models import User, Groupfrom rest_framework import viewsetsfrom tutorial.quickstart.serializers import UserSerializer, GroupSerializerclass UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializerclass GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = Group.objects.all() serializer_class = GroupSerializer

4、tutorial\urls.py中写入:

from django.conf.urls import url, includefrom rest_framework import routersfrom tutorial.quickstart import viewsrouter = routers.DefaultRouter()router.register(r'users', views.UserViewSet)router.register(r'groups', views.GroupViewSet)# Wire up our API using automatic URL routing.# Additionally, we include login URLs for the browsable API.urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))]

5、添加'rest_framework'到INSTALLED_APPS。设置模块将处于tutorial/settings.py

6、通过python manage.py runserver启动框架

7、通过http://localhost:8000/在浏览器里打开

以上这篇python+django+rest框架配置创建方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章