标签:framework mode def 需求 open glob 何事 也会 cli
# 定义两个变量 a = 1 b = 2 # 判断a的真假值,如果为True,则将判断表达式的前面的值赋给c,否则将判断表达式后面的值赋给c c = a if a else b print(c) # 1 # 因为a的真假值判断为True,所以c为1 # 定义两个变量 a = 0 b = 2 # 判断a的真假值,如果为True,则将判断表达式的前面的值赋给c,否则将判断表达式后面的值赋给c c = a if a else b print(c) # 2 # 因为a的真假值判断为False,所以c为2
li = [1, 2, 3, 4] # 方式一:使用普通for循环 new_list = list() for item in li: new_list.append(item * 2) # 方式二:使用列表推导式 li = [ x * 2 for x in li]
class Father(object): country = "china" class Person(Father): def __init__(self, name, age): self.name = name self.age = age p = Person("pizza", 18) print(p.__dict__) # {‘name‘: ‘pizza‘, ‘age‘: 18} print(Person.__dict__) # {‘__module__‘: ‘__main__‘, ‘__init__‘: <function Person.__init__ at 0x103f132f0>, ‘__doc__‘: None} print(p.name) # pizza print(p.age) # 18 print(p.country) # china 如果对象不存在这个属性,则会到其父类中查找这个属性 print(p.hobby) # 如果在父类中也找不到这个属性,则会报错:AttributeError: ‘Person‘ object has no attribute ‘hobby‘
class Father(object): country = "china" class Person(Father): def __init__(self, name, age): self.name = name self.age = age def __getattr__(self, value): raise ValueError("属性%s不存在" % value) p = Person("pizza", 18) print(p.hobby) # ValueError: 属性hobby不存在
>>> from drf_server import settings >>> print(settings.NAME) # Pizza
>>> from django.conf import settings >>> print(settings.NAME)
>>> from django.conf import settings >>> print(settings.NAME) # Pizza
from django.db import models # Create your models here. class Courses(models.Model): title = models.CharField(max_length=32) description = models.CharField(max_length=128)
class CoursesView(View): def get(self, request): courses = list() for item in Courses.objects.all(): course = { "title": item.title, "description": item.description } courses.append(course) return HttpResponse(json.dumps(courses, ensure_ascii=False))
from django.core.serializers import serialize class StudentView(APIView): def get(self, request): origin_students = Student.objects.all() serialized_students = serialize("json", origin_students) return HttpResponse(serialized_students)
from django.http import JsonResponse from rest_framework.views import APIView from rest_framework.parsers import JSONParser, FormParser # Create your views here. class LoginView(APIView): parser_classes = [FormParser] def get(self, request): return render(request, ‘parserver/login.html‘) def post(self, request): # request是被drf封装的新对象,基于django的request # request.data是一个property,用于对数据进行校验 # request.data最后会找到self.parser_classes中的解析器 # 来实现对数据进行解析 print(request.data) # {‘username‘: ‘alex‘, ‘password‘: 123} return JsonResponse({"status_code": 200, "code": "OK"})
@classonlymethod def as_view(cls, **initkwargs): """Main entry point for a request-response process.""" for key in initkwargs: if key in cls.http_method_names: raise TypeError("You tried to pass in the %s method name as a " "keyword argument to %s(). Don‘t do that." % (key, cls.__name__)) if not hasattr(cls, key): raise TypeError("%s() received an invalid keyword %r. as_view " "only accepts arguments that are already " "attributes of the class." % (cls.__name__, key)) def view(request, *args, **kwargs): self = cls(**initkwargs) if hasattr(self, ‘get‘) and not hasattr(self, ‘head‘): self.head = self.get self.request = request self.args = args self.kwargs = kwargs return self.dispatch(request, *args, **kwargs) view.view_class = cls view.view_initkwargs = initkwargs # take name and docstring from class update_wrapper(view, cls, updated=()) # and possible attributes set by decorators # like csrf_exempt from dispatch update_wrapper(view, cls.dispatch, assigned=()) return view
@classonlymethod def as_view(cls, **initkwargs): """Main entry point for a request-response process.""" for key in initkwargs: if key in cls.http_method_names: raise TypeError("You tried to pass in the %s method name as a " "keyword argument to %s(). Don‘t do that." % (key, cls.__name__)) if not hasattr(cls, key): raise TypeError("%s() received an invalid keyword %r. as_view " "only accepts arguments that are already " "attributes of the class." % (cls.__name__, key)) def view(request, *args, **kwargs): if request.content_type == "application/json": import json return HttpResponse(json.dumps({"error": "Unsupport content type!"})) self = cls(**initkwargs) if hasattr(self, ‘get‘) and not hasattr(self, ‘head‘): self.head = self.get self.request = request self.args = args self.kwargs = kwargs return self.dispatch(request, *args, **kwargs) view.view_class = cls view.view_initkwargs = initkwargs # take name and docstring from class update_wrapper(view, cls, updated=()) # and possible attributes set by decorators # like csrf_exempt from dispatch update_wrapper(view, cls.dispatch, assigned=()) return view
from django.db import models # Create your models here. class Publish(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) city = models.CharField(max_length=32) email = models.EmailField() def __str__(self): return self.name class Author(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) age = models.IntegerField() def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=32) publishDate = models.DateField() price = models.DecimalField(max_digits=5, decimal_places=2) publish = models.ForeignKey(to="Publish", to_field="nid", on_delete=models.CASCADE) authors = models.ManyToManyField(to="Author") def __str__(self): return self.title
from django.urls import re_path from serializers import views urlpatterns = [ re_path(r‘books/$‘, views.BookView.as_view()) ]
# -*- coding: utf-8 -*- from rest_framework import serializers from .models import Book class BookSerializer(serializers.Serializer): title = serializers.CharField(max_length=128) publish_date = serializers.DateTimeField() price = serializers.DecimalField(max_digits=5, decimal_places=2) publish = serializers.CharField(max_length=32) authors = serializers.CharField(max_length=32)
# -*- coding: utf-8 -*- from rest_framework.views import APIView from rest_framework.response import Response # 当前app中的模块 from .models import Book from .app_serializer import BookSerializer # Create your views here. class BookView(APIView): def get(self, request): origin_books = Book.objects.all() serialized_books = BookSerializer(origin_books, many=True) return Response(serialized_books.data)
class BookSerializer(serializers.Serializer): BookTitle = serializers.CharField(max_length=128, source="title") publishDate = serializers.DateTimeField() price = serializers.DecimalField(max_digits=5, decimal_places=2) # source也可以用于ForeignKey字段 publish = serializers.CharField(max_length=32, source="publish.name") authors = serializers.CharField(max_length=32)
[ { "title": "Python入门", "publishDate": null, "price": "119.00", "publish": "浙江大学出版社", "authors": "serializers.Author.None" }, { "title": "Python进阶", "publishDate": null, "price": "128.00", "publish": "清华大学出版社", "authors": "serializers.Author.None" } ]
class BookSerializer(serializers.Serializer): title = serializers.CharField(max_length=32) price = serializers.DecimalField(max_digits=5, decimal_places=2) publishDate = serializers.DateField() publish = serializers.CharField() publish_name = serializers.CharField(max_length=32, read_only=True, source=‘publish.name‘) publish_email = serializers.CharField(max_length=32, read_only=True, source=‘publish.email‘) # authors = serializers.CharField(max_length=32, source=‘authors.all‘) authors_list = serializers.SerializerMethodField() def get_authors_list(self, authors_obj): authors = list() for author in authors_obj.authors.all(): authors.append(author.name) return authors
# -*- coding: utf-8 -*- from rest_framework.views import APIView from rest_framework.response import Response # 当前app中的模块 from .models import Book from .app_serializer import BookSerializer # Create your views here. class BookView(APIView): def get(self, request): origin_books = Book.objects.all() serialized_books = BookSerializer(origin_books, many=True) return Response(serialized_books.data) def post(self, request): verified_data = BookSerializer(data=request.data) if verified_data.is_valid(): book = verified_data.save() # 可写字段通过序列化添加成功之后需要手动添加只读字段 authors = Author.objects.filter(nid__in=request.data[‘authors‘]) book.authors.add(*authors) return Response(verified_data.data) else: return Response(verified_data.errors)
# 第二步, 创建一个序列化类,字段类型不一定要跟models的字段一致 class BookSerializer(serializers.Serializer): # nid = serializers.CharField(max_length=32) title = serializers.CharField(max_length=128) price = serializers.DecimalField(max_digits=5, decimal_places=2) publish = serializers.CharField() # 外键字段, 显示__str__方法的返回值 publish_name = serializers.CharField(max_length=32, read_only=True, source=‘publish.name‘) publish_city = serializers.CharField(max_length=32, read_only=True, source=‘publish.city‘) # authors = serializers.CharField(max_length=32) # book_obj.authors.all() # 多对多字段需要自己手动获取数据,SerializerMethodField() authors_list = serializers.SerializerMethodField() def get_authors_list(self, book_obj): author_list = list() for author in book_obj.authors.all(): author_list.append(author.name) return author_list def create(self, validated_data): # {‘title‘: ‘Python666‘, ‘price‘: Decimal(‘66.00‘), ‘publish‘: ‘2‘} validated_data[‘publish_id‘] = validated_data.pop(‘publish‘) book = Book.objects.create(**validated_data) return book def update(self, instance, validated_data): # 更新数据会调用该方法 instance.title = validated_data.get(‘title‘, instance.title) instance.publishDate = validated_data.get(‘publishDate‘, instance.publishDate) instance.price = validated_data.get(‘price‘, instance.price) instance.publish_id = validated_data.get(‘publish‘, instance.publish.nid) instance.save() return instance
class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = (‘title‘, ‘price‘, ‘publish‘, ‘authors‘, ‘author_list‘, ‘publish_name‘, ‘publish_city‘ ) extra_kwargs = { ‘publish‘: {‘write_only‘: True}, ‘authors‘: {‘write_only‘: True} } publish_name = serializers.CharField(max_length=32, read_only=True, source=‘publish.name‘) publish_city = serializers.CharField(max_length=32, read_only=True, source=‘publish.city‘) author_list = serializers.SerializerMethodField() def get_author_list(self, book_obj): # 拿到queryset开始循环 [{}, {}, {}, {}] authors = list() for author in book_obj.authors.all(): authors.append(author.name) return authors
标签:framework mode def 需求 open glob 何事 也会 cli
原文地址:https://www.cnblogs.com/qicun/p/10105204.html