• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

python 搞代码 4年前 (2022-01-09) 29次浏览 已收录 0个评论

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

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)
rou<strong style="color:transparent">本文来源gao@daima#com搞(%代@#码网@</strong>ter.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框架配置创建方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python+django+rest框架配置创建方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址