欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

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

时间:2020-10-16 21:54:55|栏目:Python代码|点击:

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

python、django、pip等版本如下:

采用Django REST框架3.0

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

mkdir tutorial
cd tutorial
virtualenv env
source env/bin/activate 
pip install django
pip install djangorestframework
django-admin startproject tutorial . 
cd tutorial
django-admin startapp quickstart
cd ../

2、

python manage.py migrate
python manage.py createsuperuser

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

from django.contrib.auth.models import User, Group
from rest_framework import serializers
class 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, Group
from rest_framework import viewsets
from tutorial.quickstart.serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
  """
  API endpoint that allows users to be viewed or edited.
  """
  queryset = User.objects.all().order_by('-date_joined')
  serializer_class = UserSerializer
class 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, include
from rest_framework import routers
from tutorial.quickstart import views
router = 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 在threading中如何处理主进程和子线程的关系

栏    目:Python代码

下一篇:anaconda中更改python版本的方法步骤

本文标题:python+django+rest框架配置创建方法

本文地址:http://www.codeinn.net/misctech/12475.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有