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

yipeiwu_com5年前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+django+rest框架配置创建方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python九九乘法表的实例

python九九乘法表的实例

python2.7 for i in range(1,10): for j in range(1,i+1): print j,'x',i,'=',j*i,'\t', prin...

python脚本当作Linux中的服务启动实现方法

脚本服务化目的: python 在 文本处理中有着广泛的应用,为了满足文本数据的获取,会每天运行一些爬虫抓取数据。但是网上买的服务器会不定时进行维护,服务器会被重启。这样我们的爬虫服务就...

python 读取视频,处理后,实时计算帧数fps的方法

实时计算每秒的帧数 cap = cv2.VideoCapture("DJI_0008.MOV") #cap = cv2.VideoCapture(0) # Define the...

python入门:这篇文章带你直接学会python

python入门:这篇文章带你直接学会python

初试牛刀 假设你希望学习Python这门语言,却苦于找不到一个简短而全面的入门教程。那么本教程将花费十分钟的时间带你走入Python的大门。本文的内容介于教程(Toturial)和速查手...

Python+OpenCV实现将图像转换为二进制格式

在学习tensorflow的过程中,有一个问题,tensorflow在训练的过程中读取的是二进制图像数据库文件,而不是图像文件,因此 在进行训练、测试之前需要将图像文件转换为二进制格式。...