├── calc ├── __init__.py ├── migrations │ └── __init__.py ├── models.py ├── tests.py ├── admin.py ├── apps.py ├── templates │ └── home.html └── views.py ├── learn ├── __init__.py ├── migrations │ └── __init__.py ├── templates │ └── home.html ├── models.py ├── tests.py ├── admin.py ├── apps.py └── views.py ├── meizi ├── __init__.py ├── migrations │ ├── __init__.py │ ├── 0001_initial.py │ └── 0002_auto_20180519_1737.py ├── tests.py ├── admin.py ├── apps.py ├── serializers.py ├── models.py └── views.py ├── people ├── __init__.py ├── migrations │ ├── __init__.py │ └── 0001_initial.py ├── admin.py ├── tests.py ├── apps.py ├── models.py └── views.py ├── tools ├── __init__.py ├── migrations │ └── __init__.py ├── forms.py ├── models.py ├── tests.py ├── admin.py ├── apps.py ├── templates │ └── index.html └── views.py ├── snippets ├── __init__.py ├── migrations │ ├── __init__.py │ └── 0001_initial.py ├── tests.py ├── admin.py ├── apps.py ├── urls.py ├── serializers.py ├── models.py └── views.py ├── mysite ├── __init__.py ├── wsgi.py ├── urls.py └── settings.py ├── db.sqlite3 └── manage.py /calc/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /learn/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /meizi/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /people/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tools/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /snippets/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /calc/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /learn/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /meizi/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tools/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /people/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /snippets/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /mysite/__init__.py: -------------------------------------------------------------------------------- 1 | import pymysql 2 | pymysql.install_as_MySQLdb() -------------------------------------------------------------------------------- /db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/peiniwan/mysite/HEAD/db.sqlite3 -------------------------------------------------------------------------------- /learn/templates/home.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 欢迎光临 5 | 6 | 7 | 欢迎光临新世界 8 | 9 | -------------------------------------------------------------------------------- /tools/forms.py: -------------------------------------------------------------------------------- 1 | from django import forms 2 | 3 | 4 | class AddForm(forms.Form): 5 | a = forms.IntegerField() 6 | b = forms.IntegerField() 7 | -------------------------------------------------------------------------------- /calc/models.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.db import models 5 | 6 | # Create your models here. 7 | -------------------------------------------------------------------------------- /calc/tests.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.test import TestCase 5 | 6 | # Create your tests here. 7 | -------------------------------------------------------------------------------- /learn/models.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.db import models 5 | 6 | # Create your models here. 7 | -------------------------------------------------------------------------------- /learn/tests.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.test import TestCase 5 | 6 | # Create your tests here. 7 | -------------------------------------------------------------------------------- /meizi/tests.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.test import TestCase 5 | 6 | # Create your tests here. 7 | -------------------------------------------------------------------------------- /tools/models.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.db import models 5 | 6 | # Create your models here. 7 | -------------------------------------------------------------------------------- /tools/tests.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.test import TestCase 5 | 6 | # Create your tests here. 7 | -------------------------------------------------------------------------------- /calc/admin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.contrib import admin 5 | 6 | # Register your models here. 7 | -------------------------------------------------------------------------------- /learn/admin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.contrib import admin 5 | 6 | # Register your models here. 7 | -------------------------------------------------------------------------------- /meizi/admin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.contrib import admin 5 | 6 | # Register your models here. 7 | -------------------------------------------------------------------------------- /people/admin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.contrib import admin 5 | 6 | # Register your models here. 7 | -------------------------------------------------------------------------------- /people/tests.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.test import TestCase 5 | 6 | # Create your tests here. 7 | -------------------------------------------------------------------------------- /snippets/tests.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.test import TestCase 5 | 6 | # Create your tests here. 7 | -------------------------------------------------------------------------------- /tools/admin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.contrib import admin 5 | 6 | # Register your models here. 7 | -------------------------------------------------------------------------------- /snippets/admin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.contrib import admin 5 | 6 | # Register your models here. 7 | -------------------------------------------------------------------------------- /calc/apps.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.apps import AppConfig 5 | 6 | 7 | class CalcConfig(AppConfig): 8 | name = 'calc' 9 | -------------------------------------------------------------------------------- /learn/apps.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.apps import AppConfig 5 | 6 | 7 | class LearnConfig(AppConfig): 8 | name = 'learn' 9 | -------------------------------------------------------------------------------- /meizi/apps.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.apps import AppConfig 5 | 6 | 7 | class MeiziConfig(AppConfig): 8 | name = 'meizi' 9 | -------------------------------------------------------------------------------- /people/apps.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.apps import AppConfig 5 | 6 | 7 | class PeopleConfig(AppConfig): 8 | name = 'people' 9 | -------------------------------------------------------------------------------- /tools/apps.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.apps import AppConfig 5 | 6 | 7 | class ToolsConfig(AppConfig): 8 | name = 'tools' 9 | -------------------------------------------------------------------------------- /snippets/apps.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.apps import AppConfig 5 | 6 | 7 | class SnippetsConfig(AppConfig): 8 | name = 'snippets' 9 | -------------------------------------------------------------------------------- /calc/templates/home.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 计算器 5 | 6 | 7 | 8 | {#计算 4+5#} 9 | link 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /tools/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 计算器 5 | 6 | 7 |
8 | {% csrf_token %} 9 | {{ form }} 10 | 11 |
12 | 13 | 14 | -------------------------------------------------------------------------------- /snippets/urls.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.conf.urls import url 3 | from snippets import views 4 | from rest_framework.urlpatterns import format_suffix_patterns 5 | 6 | urlpatterns = [ 7 | url(r'^snippets/$', views.snippet_list), 8 | url(r'^snippets/(?P[0-9]+)/$', views.snippet_detail), 9 | ] 10 | 11 | urlpatterns = format_suffix_patterns(urlpatterns) 12 | -------------------------------------------------------------------------------- /people/models.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.db import models 5 | 6 | 7 | # Create your models here. 8 | class Person(models.Model): 9 | name = models.CharField(max_length=30) 10 | age = models.IntegerField() 11 | 12 | def __unicode__(self): 13 | # 在Python3中使用 def __str__(self): 14 | return self.name 15 | -------------------------------------------------------------------------------- /learn/views.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.http import HttpResponse 3 | from django.shortcuts import render 4 | 5 | 6 | def index(request): 7 | return HttpResponse(u"欢迎光临") 8 | 9 | 10 | def home(request): 11 | # return render(request, 'home.html') 12 | string = u"我在学习Django,用它来建网站" 13 | # html里这样用{{string}} 14 | return render(request, 'home.html', {'string': string}) 15 | -------------------------------------------------------------------------------- /snippets/serializers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from rest_framework import serializers 3 | 4 | from snippets.models import Snippet 5 | 6 | 7 | class SnippetSerializer(serializers.ModelSerializer): 8 | # ModelSerializer和Django中ModelForm功能相似 9 | # Serializer和Django中Form功能相似 10 | class Meta: 11 | model = Snippet 12 | fields = ('id', 'title', 'code', 'linenos', 'language', 'style') 13 | -------------------------------------------------------------------------------- /mysite/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for mysite 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", "mysite.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /calc/views.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.http import HttpResponse 5 | from django.shortcuts import render 6 | 7 | 8 | # Create your views here. 9 | def add(request): 10 | a = request.GET.get('a', 0) 11 | b = request.GET.get('b', 0) 12 | c = int(a) + int(b) 13 | return HttpResponse(str(c)) 14 | 15 | 16 | def add2(request, a, b): 17 | c = int(a) + int(b) 18 | return HttpResponse(str(c)) 19 | 20 | def index(request): 21 | return render(request, 'home.html') 22 | -------------------------------------------------------------------------------- /meizi/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.11.13 on 2018-05-19 09:10 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | initial = True 11 | 12 | dependencies = [ 13 | ] 14 | 15 | operations = [ 16 | migrations.CreateModel( 17 | name='Meizis', 18 | fields=[ 19 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 20 | ], 21 | ), 22 | ] 23 | -------------------------------------------------------------------------------- /people/views.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.http import HttpResponse 5 | from django.shortcuts import render 6 | 7 | # Create your views here. 8 | from people.models import Person 9 | 10 | 11 | def create(request): 12 | # 新建一个对象的方法有以下几种: 13 | Person.objects.create(name='liu', age=18) 14 | # p = Person(name="WZ", age=23) 15 | # p = Person(name="TWZ") 16 | # p.age = 23 17 | # p.save() 18 | # 这种方法是防止重复很好的方法,但是速度要相对慢些,返回一个元组,第一个为Person对象, 19 | # 第二个为True或False, 新建时返回的是True, 已经存在时返回False 20 | # Person.objects.get_or_create(name="WZT", age=23) 21 | s = Person.objects.get(name='liu') 22 | return HttpResponse(str(s)) 23 | -------------------------------------------------------------------------------- /people/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.11.13 on 2018-05-17 07:15 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | initial = True 11 | 12 | dependencies = [ 13 | ] 14 | 15 | operations = [ 16 | migrations.CreateModel( 17 | name='Person', 18 | fields=[ 19 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 20 | ('name', models.CharField(max_length=30)), 21 | ('age', models.IntegerField()), 22 | ], 23 | ), 24 | ] 25 | -------------------------------------------------------------------------------- /meizi/serializers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from rest_framework import serializers 3 | 4 | from meizi.models import Meizis 5 | from snippets.models import Snippet 6 | 7 | 8 | class MeiziSerializer(serializers.ModelSerializer): 9 | # ModelSerializer和Django中ModelForm功能相似 10 | # Serializer和Django中Form功能相似 11 | class Meta: 12 | model = Meizis 13 | # 和"__all__"等价 14 | fields = ('mid', 'title', 'picname', 'page_url', 'img_url') 15 | 16 | 17 | # 自带的分页功能 18 | class ListSerialize(serializers.ModelSerializer): 19 | class Meta: 20 | model = Meizis 21 | # fields = "__all__" 22 | fields = ('mid', 'title') 23 | 24 | 25 | class ListPicSerialize(serializers.ModelSerializer): 26 | class Meta: 27 | model = Meizis 28 | fields = "__all__" 29 | -------------------------------------------------------------------------------- /tools/views.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.http import HttpResponse 5 | from django.shortcuts import render 6 | 7 | # Create your views here. 8 | # 引入我们创建的表单类 9 | from .forms import AddForm 10 | 11 | # 比如用户输入的不是数字,而是字母,就出错了,还有就是提交后再回来已经输入的数据也会没了。 12 | # 当然如果我们手动将输入之后的数据在 views 中都获取到再传递到网页,这样是可行的,但是很不方便, 13 | # 所以 Django 提供了更简单易用的 forms 来解决验证等这一系列的问题。 14 | def index(request): 15 | if request.method == 'POST': # 当提交表单时 16 | 17 | form = AddForm(request.POST) # form 包含提交的数据 18 | 19 | if form.is_valid(): # 如果提交的数据合法 20 | a = form.cleaned_data['a'] 21 | b = form.cleaned_data['b'] 22 | return HttpResponse(str(int(a) + int(b))) 23 | 24 | else: # 当正常访问时 25 | form = AddForm() 26 | return render(request, 'index.html', {'form': form}) 27 | -------------------------------------------------------------------------------- /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", "mysite.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 | -------------------------------------------------------------------------------- /meizi/models.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | import pymysql 5 | from django.db import models 6 | 7 | # Create your models here. 8 | from rest_framework.pagination import LimitOffsetPagination 9 | 10 | 11 | class Meizis(models.Model): 12 | mid = models.CharField(max_length=10) 13 | title = models.CharField(max_length=50, blank=True, null=True) 14 | picname = models.CharField(max_length=10, blank=True, null=True) 15 | page_url = models.CharField(max_length=50, blank=True, null=True) 16 | img_url = models.CharField(max_length=50, blank=True, null=True) 17 | 18 | class Meta: 19 | managed = False 20 | db_table = 'meizi_meizis' 21 | 22 | 23 | class StandardResultSetPagination(LimitOffsetPagination): 24 | # 默认每页显示的条数 25 | default_limit = 20 26 | # url 中传入的显示数据条数的参数 27 | limit_query_param = 'limit' 28 | # url中传入的数据位置的参数 29 | offset_query_param = 'offset' 30 | # 最大每页显示条数 31 | max_limit = None 32 | -------------------------------------------------------------------------------- /snippets/models.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | from django.db import models 4 | 5 | 6 | # Create your models here. 7 | 8 | # python manage.py shell 进入shell插入表 9 | # from snippets.models import Snippet 10 | # from snippets.serializers import SnippetSerializer 11 | # from rest_framework.renderers import JSONRenderer 12 | # from rest_framework.parsers import JSONParser 13 | # 14 | # # 创建数据 15 | # snippet = Snippet(code='foo = "bar"\n') 16 | # snippet.save() 17 | # 18 | # snippet = Snippet(code='print "hello, world"\n') 19 | # snippet.save() 20 | 21 | class Snippet(models.Model): 22 | created = models.DateTimeField(auto_now_add=True) 23 | title = models.CharField(max_length=100, blank=True, default='') 24 | code = models.TextField() 25 | linenos = models.BooleanField(default=False) 26 | language = models.CharField(default='python', max_length=100) 27 | style = models.CharField(default='friendly', max_length=100) 28 | 29 | class Meta: 30 | ordering = ('created',) 31 | -------------------------------------------------------------------------------- /snippets/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.11.13 on 2018-05-18 06:14 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | initial = True 11 | 12 | dependencies = [ 13 | ] 14 | 15 | operations = [ 16 | migrations.CreateModel( 17 | name='Snippet', 18 | fields=[ 19 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 20 | ('created', models.DateTimeField(auto_now_add=True)), 21 | ('title', models.CharField(blank=True, default='', max_length=100)), 22 | ('code', models.TextField()), 23 | ('linenos', models.BooleanField(default=False)), 24 | ('language', models.CharField(default='python', max_length=100)), 25 | ('style', models.CharField(default='friendly', max_length=100)), 26 | ], 27 | options={ 28 | 'ordering': ('created',), 29 | }, 30 | ), 31 | ] 32 | -------------------------------------------------------------------------------- /meizi/migrations/0002_auto_20180519_1737.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.11.13 on 2018-05-19 09:37 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | dependencies = [ 11 | ('meizi', '0001_initial'), 12 | ] 13 | 14 | operations = [ 15 | migrations.AddField( 16 | model_name='meizis', 17 | name='img_url', 18 | field=models.CharField(default='', max_length=50), 19 | ), 20 | migrations.AddField( 21 | model_name='meizis', 22 | name='mid', 23 | field=models.CharField(default='', max_length=10), 24 | ), 25 | migrations.AddField( 26 | model_name='meizis', 27 | name='page_url', 28 | field=models.CharField(default='', max_length=50), 29 | ), 30 | migrations.AddField( 31 | model_name='meizis', 32 | name='picname', 33 | field=models.CharField(default='', max_length=10), 34 | ), 35 | migrations.AddField( 36 | model_name='meizis', 37 | name='title', 38 | field=models.CharField(default='', max_length=50), 39 | ), 40 | ] 41 | -------------------------------------------------------------------------------- /mysite/urls.py: -------------------------------------------------------------------------------- 1 | """mysite 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 | from learn import views as learn_views # new 19 | from calc import views as calc_views 20 | from people import views as people_views 21 | from tools import views as tools_views 22 | from meizi import views as meizi_views 23 | 24 | urlpatterns = [ 25 | url(r'^getlistpic', meizi_views.getlispic, name='home'), 26 | url(r'^getlist', meizi_views.getlist, name='home'), 27 | # url(r'^', include('snippets.urls')), 28 | url(r'^$', tools_views.index, name='home'), 29 | url(r'^$', people_views.create, name='home'), 30 | url(r'^$', learn_views.home, name='home'), 31 | url(r'^$', calc_views.index, name='home'), 32 | url(r'^$', learn_views.index), # new 33 | url(r'^admin/', admin.site.urls), 34 | url(r'^new_add/(\d+)/(\d+)/$', calc_views.add2, name='add2'), 35 | url(r'^add/$', calc_views.add, name='add'), 36 | url(r'^add/(\d+)/(\d+)/$', calc_views.add2, name='add2'), 37 | ] 38 | -------------------------------------------------------------------------------- /meizi/views.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | import pymysql 5 | from django.http import HttpResponse 6 | from django.shortcuts import render 7 | 8 | # Create your views here. 9 | from rest_framework import status 10 | from rest_framework.decorators import api_view 11 | from rest_framework.response import Response 12 | 13 | from meizi.models import Meizis, StandardResultSetPagination 14 | from meizi.serializers import MeiziSerializer, ListSerialize, ListPicSerialize 15 | 16 | 17 | @api_view(['GET']) 18 | def getlist(request, format=None): 19 | if request.method == 'GET': 20 | meizis = Meizis.objects.values('mid','title').distinct() 21 | serializer = MeiziSerializer(meizis, many=True) 22 | # return Response(serializer.data) 23 | 24 | # http: // 127.0.0.1:8000 / getlist?limit = 20 25 | # http: // 127.0.0.1:8000 / getlist?limit = 20 & offset = 20 26 | # http: // 127.0.0.1:8000 / getlist?limit = 20 & offset = 40 27 | # 根据url参数 获取分页数据 28 | obj = StandardResultSetPagination() 29 | page_list = obj.paginate_queryset(meizis, request) 30 | # 对数据序列化 普通序列化 显示的只是数据 31 | ser = ListSerialize(instance=page_list, many=True) # 多个many=True # instance:把对象序列化 32 | 33 | response = obj.get_paginated_response(ser.data) 34 | return response 35 | 36 | 37 | @api_view(['GET', 'POST']) 38 | def getlispic(request, format=None): 39 | if request.method == 'GET': 40 | mid = request.GET['mid'] 41 | if mid is not None: 42 | # get是用来获取一个对象的,如果需要获取满足条件的一些人,就要用到filter 43 | meizis = Meizis.objects.filter(mid=mid) 44 | obj = StandardResultSetPagination() 45 | page_list = obj.paginate_queryset(meizis, request) 46 | ser = ListPicSerialize(instance=page_list, many=True) 47 | response = obj.get_paginated_response(ser.data) 48 | return response 49 | else: 50 | return Response(str('请传mid')) 51 | -------------------------------------------------------------------------------- /mysite/settings.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Django settings for mysite project. 4 | 5 | Generated by 'django-admin startproject' using Django 1.11.13. 6 | 7 | For more information on this file, see 8 | https://docs.djangoproject.com/en/1.11/topics/settings/ 9 | 10 | For the full list of settings and their values, see 11 | https://docs.djangoproject.com/en/1.11/ref/settings/ 12 | """ 13 | 14 | import os 15 | 16 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 17 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 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 = '%tso#mq=yyf$@*=6bd2-3-ttuar!(f_u#*avf0!hrfi#&)q%r1' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | # Application definition 31 | 32 | # Make sure you have rest_framework listed in your settings.py INSTALLED_APPS. 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 | 42 | 'learn', 43 | 'calc', 44 | 'people', 45 | 'tools', 46 | 'snippets', 47 | 'meizi', 48 | ] 49 | 50 | MIDDLEWARE = [ 51 | 'django.middleware.security.SecurityMiddleware', 52 | 'django.contrib.sessions.middleware.SessionMiddleware', 53 | 'django.middleware.common.CommonMiddleware', 54 | 'django.middleware.csrf.CsrfViewMiddleware', 55 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 56 | 'django.contrib.messages.middleware.MessageMiddleware', 57 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 58 | ] 59 | 60 | ROOT_URLCONF = 'mysite.urls' 61 | 62 | TEMPLATES = [ 63 | { 64 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 65 | 'DIRS': [], 66 | 'APP_DIRS': True, 67 | 'OPTIONS': { 68 | 'context_processors': [ 69 | 'django.template.context_processors.debug', 70 | 'django.template.context_processors.request', 71 | 'django.contrib.auth.context_processors.auth', 72 | 'django.contrib.messages.context_processors.messages', 73 | ], 74 | }, 75 | }, 76 | ] 77 | 78 | WSGI_APPLICATION = 'mysite.wsgi.application' 79 | 80 | 81 | # Database 82 | # https://docs.djangoproject.com/en/1.11/ref/settings/#databases 83 | 84 | DATABASES = { 85 | # 'default': { 86 | # 'ENGINE': 'django.db.backends.sqlite3', 87 | # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 88 | # } 89 | 'default': { 90 | 'ENGINE': 'django.db.backends.mysql', 91 | # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 92 | 'NAME': 'mysql', 93 | 'USER': 'root', 94 | 'HOST': '127.0.0.1', 95 | 'PASSWORD': '123', 96 | 'PORT': 3306, 97 | # show variables like 'character_set_database'; 98 | # 修改字段字符编码 99 | # alter table spiders_weibo modify text longtext charset utf8mb4 collate utf8mb4_unicode_ci; 100 | 'OPTIONS': {'charset': 'utf8mb4'}, 101 | } 102 | } 103 | 104 | # Password validation 105 | # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators 106 | 107 | AUTH_PASSWORD_VALIDATORS = [ 108 | { 109 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValid ator', 110 | }, 111 | { 112 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 113 | }, 114 | { 115 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 116 | }, 117 | { 118 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 119 | }, 120 | ] 121 | 122 | ALLOWED_HOSTS = ['*'] 123 | 124 | # Internationalization 125 | # https://docs.djangoproject.com/en/1.11/topics/i18n/ 126 | 127 | LANGUAGE_CODE = 'en-us' 128 | 129 | TIME_ZONE = 'UTC' 130 | 131 | USE_I18N = True 132 | 133 | USE_L10N = True 134 | 135 | USE_TZ = True 136 | 137 | # Static files (CSS, JavaScript, Images) 138 | # https://docs.djangoproject.com/en/1.11/howto/static-files/ 139 | 140 | STATIC_URL = '/static/' 141 | -------------------------------------------------------------------------------- /snippets/views.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | from django.http import HttpResponse, JsonResponse 4 | from django.views.decorators.csrf import csrf_exempt 5 | from rest_framework import status 6 | from rest_framework.decorators import api_view 7 | from rest_framework.renderers import JSONRenderer 8 | from rest_framework.parsers import JSONParser 9 | from rest_framework.response import Response 10 | 11 | from snippets.models import Snippet 12 | from snippets.serializers import SnippetSerializer 13 | from django.shortcuts import render 14 | import pdb; 15 | 16 | 17 | # Create your views here. 18 | # @csrf_exempt 19 | # def snippet_list(request): 20 | # """ 21 | # request.POST # 只能处理表单(form)数据,只能处理“POST”方法. 22 | # request.data # 处理任意数据.可以处理'POST', 'PUT' 和 'PATCH'方法. 23 | # List all code snippets, or create a new snippet. 24 | # """ 25 | # if request.method == 'GET': 26 | # snippets = Snippet.objects.all() 27 | # # 可以将queryset序列化。只需在序列器的参数中加入many = True 28 | # # 该代码是把刚刚保存的数据snippet对象,经过序列化保存成一个字典 29 | # serializer = SnippetSerializer(snippets, many=True) 30 | # return JsonResponse(serializer.data, safe=False) 31 | # 32 | # elif request.method == 'POST': 33 | # data = JSONParser().parse(request) 34 | # serializer = SnippetSerializer(data=data) 35 | # if serializer.is_valid(): # 验证数据是否符合要求 36 | # serializer.save() 37 | # # serializer.data 数据创建成功后所有数据 38 | # return JsonResponse(serializer.data, status=201) 39 | # # serializer.errors 错误信息 40 | # return JsonResponse(serializer.errors, status=400) 41 | 42 | 43 | # REST框架提供了两种编写API视图的封装。 44 | # 1.@api_view装饰器,基于方法的视图。 45 | # 2.继承APIView类,基于类的视图。 46 | # request.data会自行处理输入的json请求 47 | # 我们不再需要在views.py文件中使用JSONResponse类,所以可以删除它。然后,我们可以稍微重构我们的代码 48 | # 使用格式后缀明确的指向指定的格式,需要添加一个format关键字参数 49 | # http http://127.0.0.1:8000/snippets.json # JSON 后缀 50 | # http://127.0.0.1:8000/snippets.api # 可视化 API 后缀 51 | # http://127.0.0.1:8000/snippets/ code="print 123"post 52 | 53 | @api_view(['GET', 'POST']) 54 | def snippet_list(request, format=None): 55 | if request.method == 'GET': 56 | snippets = Snippet.objects.all() 57 | serializer = SnippetSerializer(snippets, many=True) 58 | return Response(serializer.data) 59 | 60 | elif request.method == 'POST': 61 | serializer = SnippetSerializer(data=request.data) 62 | if serializer.is_valid(): 63 | serializer.save() 64 | return Response(serializer.data, status=status.HTTP_201_CREATED) 65 | return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 66 | 67 | 68 | # @csrf_exempt 69 | # def snippet_detail(request, pk): 70 | # """ 71 | # Retrieve, update or delete a code snippet. 72 | # """ 73 | # try: 74 | # snippet = Snippet.objects.get(pk=pk) 75 | # except Snippet.DoesNotExist: 76 | # return HttpResponse(status=404) 77 | # if request.method == 'GET': 78 | # serializer = SnippetSerializer(snippet) 79 | # return JsonResponse(serializer.data) 80 | # elif request.method == 'PUT': 81 | # data = JSONParser().parse(request) 82 | # serializer = SnippetSerializer(snippet, data=data) 83 | # if serializer.is_valid(): 84 | # serializer.save() 85 | # return JsonResponse(serializer.data) 86 | # return JsonResponse(serializer.errors, status=400) 87 | # elif request.method == 'DELETE': 88 | # snippet.delete() 89 | # return HttpResponse(status=204) 90 | 91 | # 重构 92 | @api_view(['GET', 'PUT', 'DELETE']) 93 | def snippet_detail(request, pk, format=None): 94 | """ 95 | snippet的读取, 更新 或 删除 96 | """ 97 | try: 98 | snippet = Snippet.objects.get(pk=pk) 99 | except Snippet.DoesNotExist: 100 | return Response(status=status.HTTP_404_NOT_FOUND) 101 | 102 | if request.method == 'GET': 103 | serializer = SnippetSerializer(snippet) 104 | return Response(serializer.data) 105 | 106 | elif request.method == 'PUT': 107 | serializer = SnippetSerializer(snippet, data=request.data) 108 | if serializer.is_valid(): 109 | serializer.save() 110 | return Response(serializer.data) 111 | return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 112 | 113 | elif request.method == 'DELETE': 114 | snippet.delete() 115 | return Response(status=status.HTTP_204_NO_CONTENT) 116 | 117 | # @register.filter 118 | # def pdb(element): 119 | # pdb.set_trace() 120 | # return element 121 | # 122 | --------------------------------------------------------------------------------