python+django+rest框架配置创建方法
程序员文章站
2022-08-30 12:07:06
安装好所需要的插件和包:
python、django、pip等版本如下:
采用django rest框架3.0
1、在python文件夹下d:\python\li...
安装好所需要的插件和包:
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中逗号的三种作用实例分析