├── .gitignore ├── README.md └── django_rest ├── .DS_Store ├── api ├── __init__.py ├── admin.py ├── apps.py ├── migrations │ ├── 0001_initial.py │ └── __init__.py ├── models.py ├── rest_test.py ├── serializers.py ├── tests.py └── views.py ├── django_rest ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py └── manage.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # QCDjango-REST 2 | web服务器接口 3 | -------------------------------------------------------------------------------- /django_rest/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/canwhite/QCDjango-REST/44c18fc8c3e103ec7af6018a7096a4c76fdca1f0/django_rest/.DS_Store -------------------------------------------------------------------------------- /django_rest/api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/canwhite/QCDjango-REST/44c18fc8c3e103ec7af6018a7096a4c76fdca1f0/django_rest/api/__init__.py -------------------------------------------------------------------------------- /django_rest/api/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /django_rest/api/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class ApiConfig(AppConfig): 5 | name = 'api' 6 | -------------------------------------------------------------------------------- /django_rest/api/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.11.4 on 2018-03-10 08:47 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations, models 6 | import django.db.models.deletion 7 | 8 | 9 | class Migration(migrations.Migration): 10 | 11 | initial = True 12 | 13 | dependencies = [ 14 | ] 15 | 16 | operations = [ 17 | migrations.CreateModel( 18 | name='Event', 19 | fields=[ 20 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 21 | ('name', models.CharField(max_length=100)), 22 | ('limit', models.IntegerField()), 23 | ('status', models.BooleanField()), 24 | ('address', models.CharField(max_length=200)), 25 | ('start_time', models.DateTimeField(verbose_name='events time')), 26 | ('create_time', models.DateTimeField(auto_now=True)), 27 | ], 28 | ), 29 | migrations.CreateModel( 30 | name='Guest', 31 | fields=[ 32 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 33 | ('realname', models.CharField(max_length=64)), 34 | ('phone', models.CharField(max_length=16)), 35 | ('email', models.EmailField(max_length=254)), 36 | ('sign', models.BooleanField()), 37 | ('create_time', models.DateTimeField(auto_now=True)), 38 | ('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.Event')), 39 | ], 40 | ), 41 | migrations.AlterUniqueTogether( 42 | name='guest', 43 | unique_together=set([('phone', 'event')]), 44 | ), 45 | ] 46 | -------------------------------------------------------------------------------- /django_rest/api/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/canwhite/QCDjango-REST/44c18fc8c3e103ec7af6018a7096a4c76fdca1f0/django_rest/api/migrations/__init__.py -------------------------------------------------------------------------------- /django_rest/api/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | 5 | #发布会 6 | class Event(models.Model): 7 | """docstring for Event""" 8 | '''__str__ 类实例字符串化函数''' 9 | name = models.CharField(max_length = 100) 10 | limit = models.IntegerField() 11 | status = models.BooleanField() 12 | address = models.CharField(max_length = 200) 13 | #修改DateTimeField返回字段默认值为 events time 14 | start_time = models.DateTimeField('events time') 15 | create_time = models.DateTimeField(auto_now = True) 16 | 17 | def __str__(self): 18 | return self.name 19 | 20 | 21 | #嘉宾 22 | 23 | class Guest(models.Model): 24 | """docstring for Guest""" 25 | #建一个外键,通过它可以获得所对应的所有信息 26 | event = models.ForeignKey(Event) 27 | realname = models.CharField(max_length = 64) 28 | phone = models.CharField(max_length = 16) 29 | email = models.EmailField() 30 | sign = models.BooleanField() 31 | create_time = models.DateTimeField(auto_now = True) 32 | 33 | #页面中需要展示的元属性 34 | class Meta: 35 | unique_together = ('phone','event') 36 | 37 | #类实例字符串化函数 38 | def __str__(self): 39 | return self.realname 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /django_rest/api/rest_test.py: -------------------------------------------------------------------------------- 1 | #rest_test.py 2 | import unittest 3 | import requests 4 | 5 | '''唯一需要注意的是,接口的访问需要签名,在发送get()请求时需要制定auth参数''' 6 | 7 | class UserTest(unittest.TestCase): 8 | """用户查询测试""" 9 | def setUp(self): 10 | self.base_url = "http://127.0.0.1:8000/users" 11 | #admin 12 | def test_user1(self): 13 | '''test user 1''' 14 | r = requests.get(self.base_url + '/1/',auth = ('admin','admin12345')) 15 | result = r.json() 16 | self.assertEqual(result['username'],'admin') 17 | self.assertEqual(result['email'],'admin@mail.com') 18 | 19 | #tom 20 | def test_user2(self): 21 | 22 | '''test user 2''' 23 | r = requests.get(self.base_url + '/2/',auth = ('admin','admin12345')) 24 | result = r.json() 25 | self.assertEqual(result['username'],'tom') 26 | self.assertEqual(result['email'],'tom@mail.com') 27 | 28 | 29 | #jack 30 | def test_user3(self): 31 | '''test user 3''' 32 | r = requests.get(self.base_url + '/3/',auth = ('admin','admin12345')) 33 | result = r.json() 34 | self.assertEqual(result['username'],'jack') 35 | self.assertEqual(result['email'],'jack@mail.com') 36 | 37 | 38 | class GroupsTest(unittest.TestCase): 39 | """docstring for GroupsTest""" 40 | def setUp(self): 41 | #base链接地址 42 | self.base_url = 'http://127.0.0.1:8000/groups' 43 | 44 | def test_groups1(self): 45 | '''test group 1''' 46 | r = requests.get(self.base_url + '/1/',auth = ('admin','admin12345')) 47 | result = r.json() 48 | self.assertEqual(result['name'],'test') 49 | 50 | def test_groups2(self): 51 | 52 | '''test group 2''' 53 | r = requests.get(self.base_url + '/2/',auth = ('admin','admin12345')) 54 | result = r.json() 55 | self.assertEqual(result['name'],'developer') 56 | 57 | 58 | if __name__ == '__main__': 59 | unittest.main() 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /django_rest/api/serializers.py: -------------------------------------------------------------------------------- 1 | #serializers.py 2 | from django.contrib.auth.models import User,Group 3 | from api.models import Event,Guest 4 | from rest_framework import serializers 5 | 6 | #序列化 (Serialization)将对象的状态信息转换为可以存储或传输的形式的过程。 7 | #在序列化期间,对象将其当前状态写入到临时或持久性存储区。 8 | #以后,可以通过从存储区中读取或反序列化对象的状态,重新创建该对象。 9 | class UserSerializer(serializers.HyperlinkedModelSerializer): 10 | """docstring for UserSerializer""" 11 | #Meta 元素可提供相关页面的元信息 12 | class Meta: 13 | model = User 14 | fields = ('url','username','email','groups') 15 | 16 | 17 | 18 | class GroupSerializer(serializers.HyperlinkedModelSerializer): 19 | """docstring for ClassName""" 20 | #Meta 元素可提供相关页面的元信息 21 | class Meta: 22 | """docstring for Meta""" 23 | model = Group 24 | fields = ('url','name') 25 | 26 | #添加发布会序列化 27 | 28 | class EventSerializer(serializers.HyperlinkedModelSerializer): 29 | """docstring for EventSerializer""" 30 | class Meta: 31 | """docstring for Meta:""" 32 | model = Event 33 | fields = ('url','name','address','start_time','limit','status') 34 | 35 | 36 | class GuestSerializer(serializers.HyperlinkedModelSerializer): 37 | class Meta: 38 | """docstring for Meta""" 39 | model = Guest 40 | fields = ('url','realname','phone','email','sign','event') 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /django_rest/api/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /django_rest/api/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | from django.contrib.auth.models import User,Group 3 | from rest_framework import viewsets 4 | from api.serializers import UserSerializer,GroupSerializer,EventSerializer,GuestSerializer 5 | from api.models import Event,Guest 6 | 7 | 8 | # Create your views here. 9 | class UserViewSet(viewsets.ModelViewSet): 10 | """API endpoint that allows users to be viewed or edited.""" 11 | #order_by 根据指定的列对结果集进行排序 12 | queryset = User.objects.all().order_by('-date_joined') 13 | #将写好的序列化类赋值给serializer_class, 14 | serializer_class = UserSerializer 15 | #使用queryset和serializer_class使我们能更好的控制api行为,这是我们推荐的使用方式 16 | #另外django_rest_framework中,所有常见的行为都被归到ViewSets中 17 | 18 | 19 | class GroupViewSet(viewsets.ModelViewSet): 20 | """docstring for GroupViewSet""" 21 | queryset = Group.objects.all() 22 | serializer_class = GroupSerializer 23 | 24 | #viewSets define the view behavior 25 | class EventViewSet(viewsets.ModelViewSet): 26 | """api 端点允许事件查看和编辑""" 27 | queryset = Event.objects.all() 28 | serializer_class = EventSerializer 29 | 30 | 31 | class GuestViewSet(viewsets.ModelViewSet): 32 | """api 端点允许事件查看和编辑""" 33 | queryset = Guest.objects.all() 34 | serializer_class = GuestSerializer 35 | 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /django_rest/django_rest/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/canwhite/QCDjango-REST/44c18fc8c3e103ec7af6018a7096a4c76fdca1f0/django_rest/django_rest/__init__.py -------------------------------------------------------------------------------- /django_rest/django_rest/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for django_rest project. 3 | 4 | Generated by 'django-admin startproject' using Django 1.11.4. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.11/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/1.11/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = '*%+!%!pzf79o&pxkc1q_o$2ta2ucfhr)$_ne^q44ib^(^0kp(p' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | #引入rest_framework 41 | 'rest_framework', 42 | 'api', 43 | 44 | 45 | ] 46 | 47 | MIDDLEWARE = [ 48 | 'django.middleware.security.SecurityMiddleware', 49 | 'django.contrib.sessions.middleware.SessionMiddleware', 50 | 'django.middleware.common.CommonMiddleware', 51 | #'django.middleware.csrf.CsrfViewMiddleware', 52 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 53 | 'django.contrib.messages.middleware.MessageMiddleware', 54 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 55 | ] 56 | 57 | ROOT_URLCONF = 'django_rest.urls' 58 | 59 | TEMPLATES = [ 60 | { 61 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 62 | 'DIRS': [], 63 | 'APP_DIRS': True, 64 | 'OPTIONS': { 65 | 'context_processors': [ 66 | 'django.template.context_processors.debug', 67 | 'django.template.context_processors.request', 68 | 'django.contrib.auth.context_processors.auth', 69 | 'django.contrib.messages.context_processors.messages', 70 | ], 71 | }, 72 | }, 73 | ] 74 | 75 | WSGI_APPLICATION = 'django_rest.wsgi.application' 76 | 77 | 78 | # Database 79 | # https://docs.djangoproject.com/en/1.11/ref/settings/#databases 80 | 81 | DATABASES = { 82 | 'default': { 83 | 'ENGINE': 'django.db.backends.sqlite3', 84 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 85 | } 86 | } 87 | 88 | 89 | # Password validation 90 | # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators 91 | 92 | AUTH_PASSWORD_VALIDATORS = [ 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 101 | }, 102 | { 103 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 104 | }, 105 | ] 106 | 107 | 108 | # Internationalization 109 | # https://docs.djangoproject.com/en/1.11/topics/i18n/ 110 | 111 | LANGUAGE_CODE = 'en-us' 112 | 113 | TIME_ZONE = 'UTC' 114 | 115 | USE_I18N = True 116 | 117 | USE_L10N = True 118 | 119 | USE_TZ = True 120 | 121 | 122 | # Static files (CSS, JavaScript, Images) 123 | # https://docs.djangoproject.com/en/1.11/howto/static-files/ 124 | 125 | STATIC_URL = '/static/' 126 | 127 | 128 | #在文件末尾添加rest_framework的设置 129 | REST_FRAMEWORK = { 130 | 131 | 'DEFAULT_PERMISSION_CLASSES':('rest_framework.permissions.IsAdminUser',), 132 | 'PAGE_SIZE':10 133 | 134 | } 135 | -------------------------------------------------------------------------------- /django_rest/django_rest/urls.py: -------------------------------------------------------------------------------- 1 | """django_rest URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/1.11/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.conf.urls import url, include 14 | 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 15 | """ 16 | from django.conf.urls import url,include 17 | from django.contrib import admin 18 | #因为我们使用的是viewset,所以我们可以使用路由器类自动生成 URL conf 19 | from rest_framework import routers 20 | from api import views 21 | 22 | '''路由器提供了一种简单的方法自动确定URL配置。''' 23 | #初始化路由器 24 | router = routers.DefaultRouter() 25 | #确定URL配置 26 | router.register(r'users',views.UserViewSet) 27 | router.register(r'groups',views.GroupViewSet) 28 | router.register(r'event',views.EventViewSet) 29 | router.register(r'guest',views.GuestViewSet) 30 | 31 | urlpatterns = [ 32 | url(r'^admin/', admin.site.urls), 33 | #把我们注册的东西拿出来 34 | url(r'^',include(router.urls)), 35 | #此外,我们为可浏览的api导入登陆用url 36 | url(r'^api-auth/',include('rest_framework.urls',namespace = 'rest_framework')) 37 | 38 | ] 39 | -------------------------------------------------------------------------------- /django_rest/django_rest/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for django_rest project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_rest.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /django_rest/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_rest.settings") 7 | try: 8 | from django.core.management import execute_from_command_line 9 | except ImportError: 10 | # The above import may fail for some other reason. Ensure that the 11 | # issue is really that Django is missing to avoid masking other 12 | # exceptions on Python 2. 13 | try: 14 | import django 15 | except ImportError: 16 | raise ImportError( 17 | "Couldn't import Django. Are you sure it's installed and " 18 | "available on your PYTHONPATH environment variable? Did you " 19 | "forget to activate a virtual environment?" 20 | ) 21 | raise 22 | execute_from_command_line(sys.argv) 23 | --------------------------------------------------------------------------------