标签:合规 选项 增加 解析 传递 script ajax 标准 load
{ "error": "Invalid API key" }
from django.urls import path from classbasedview import views urlpatterns = [ path(‘login/‘, views.LoginView.as_view()), ]
from django.shortcuts import render, HttpResponse from django.views import View # Create your views here. class LoginView(View): def get(self, request): return render(request, ‘classbasedview/login.html‘) def post(self, request): return HttpResponse("post")
# -*- coding: utf-8 -*- from django.utils.decorators import classonlymethod class Person(object): def __init__(self, name, age): self.name = name self.age = age def show_info(self): print("show info method been executed") @classmethod def show_info2(cls): print("show info2 method been executed") @classonlymethod def show_info3(cls): print("show info3 method been executed") p1 = Person("pizza", 18) # 普通方法可以通过实例对象和类调用 # 通过实例调用时默认传入self作为第一个参数,不需要手动传入参数 # 通过类调用时,必须手动指定实例对象传递给该方法 p1.show_info() Person.show_info(p1) # 被classmethod装饰器装饰后的方法可以通过实例对象和类直接调用 # 默认传入类名作为第一个参数 p1.show_info2() Person.show_info2() p1.show_info3() # 报错,Django框架实现了classonlymethd,不再允许实例对象调用被该装饰器装饰的方法 Person.show_info3()
class Person(object): def __init__(self, name, age): self.name = name self.age = age self._hobby = ‘girls‘ def show_info(self): print("show info method been executed") p1 = Person("pizza", 18) # 查看该对象是否有show_info方法 print(hasattr(p1, "show_info")) # 查看该对象是否有age属性 print(hasattr(p1, "age")) print(hasattr(p1, "hahaha")) greeting = "Hello World" # 设置属性 setattr(p1, "hahaha", greeting) print(hasattr(p1, "hahaha")) func = getattr(p1, "show_info") print(func) # <bound method Person.show_info of <__main__.Person object at 0x102219d68>> # 注意:直接调用,不需要传入self,getattr时已经绑定self到func了 func() print(hasattr(Person, "show_info")) # True print(hasattr(Person, "name")) # False print(hasattr(Person, "country")) # False # 给Person类设置属性 setattr(Person, "country", "china") print(hasattr(Person, "country")) # True print(hasattr(p1, "country")) # True
# -*- coding: utf-8 -*- class Request(object): def show_request(self): print(self) class NewRequest(Request): def show_request(self): print(self) request = NewRequest() # 调用方法的实例对象是哪个,self就指向哪个对象 request.show_request()
POST /classbasedview/login/ HTTP/1.1 Host: 127.0.0.1:9001 Connection: keep-alive Content-Length: 114 Cache-Control: max-age=0 Origin: http://127.0.0.1:9001 Upgrade-Insecure-Requests: 1 Content-Type: application/x-www-form-urlencoded User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 Referer: http://127.0.0.1:9001/classbasedview/login/ Accept-Encoding: gzip, deflate, br Accept-Language: zh-CN,zh;q=0.9,en;q=0.8 Cookie: csrftoken=xPHeedcs8duBuCv031bCvsG1zMX1aGNpKlsPdCkhQHICd4lvMeHIEwkpJUQbLiOl; is_login=True; username=alex; last_time="2018-11-24 13:37:33"; fruit=xiangjiao
csrfmiddlewaretoken=EqHslTSOeI6TWMXwmFCTuLLeflkjWSJTgUdLeFw1Xtxp5S1ea8vYo3IOX7DEPnO4&username=pizzali&password=aaa
>>> dict_data = { "name": "Pizza", "age": 18 } >>> import json # 通过json模块的json.dumps(data)方式将Python中的字典类型转换为json类型 >>> json_data = json.dumps(di) >>> print(type(json_data)) <class ‘str‘>
# 通过json.loads(data)可以将json数据转换为Python中的字典类型 >>> dict_data2 = json.loads(json_data) >>> print(type(dict_data2)) <class ‘dict‘>
REST是一种软件架构设计风格,不是标准,也不是具体的技术实现,只是提供了一组设计原则和约束条件。是目前最流行的 API 设计规范,用于 Web 数据接口的设计。2000年,由Roy Fielding在他的博士论文中提出,Roy Fielding是HTTP规范的主要编写者之一。
那么,我们所要讲的Django RestFramework与rest有什么关系呢?
其实,DRF(Django RestFramework)是一套基于Django开发的、帮助我们更好的设计符合REST规范的Web应用的一个Django App,所以,本质上,它是一个Django App。
class CoursesView(View): def get(self, request): courses = list() for item in Courses.objects.all(): course = { "title": item.title, "price": item.price, "publish_date": item.publish_date, "publish_id": item.publish_id } courses.append(course) return HttpResponse(json.dumps(courses, ensure_ascii=False))
>>> pip install django
>>> pip install djangorestframework
def outer(func): def inner(*args, **kwargs): import time start_time = time.time() ret = func(*args, **kwargs) end_time = time.time() print("This function elapsed %s" % str(end_time - start_time)) return ret return inner @outer def add(x, y): return x + y
class Person(object): def show(self): print("Person‘s show method executed!") class MyPerson(Person): def show(self): print("MyPerson‘s show method executed") super().show() mp = MyPerson() mp.show()
from django.shortcuts import HttpResponse import json from .models import Courses # 引入APIView from rest_framework.views import APIView # Create your views here. class CoursesView(APIView): # 继承APIView而不是原来的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))
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script src="/static/jquery-1.10.2.min.js"></script> </head> <body> <form action="" method="post" enctype="application/x-www-form-urlencoded"> {% csrf_token %} 用户名: <input type="text" name="username"/> 密码: <input type="password" name="password"/> 提交: <input type="submit" value="提交"/> </form> <hr> <button class="btn">点击发送Ajax请求</button> <script> $(".btn").click(function () { $.ajax({ url: ‘‘, type: ‘post‘, contentType: ‘application/json‘, data: JSON.stringify({ username: "alex", password: 123 } ), success: function (data) { console.log(data); } }) }) </script> </body> </html>
if self.content_type == ‘multipart/form-data‘: if hasattr(self, ‘_body‘): # Use already read data data = BytesIO(self._body) else: data = self try: self._post, self._files = self.parse_file_upload(self.META, data) except MultiPartParserError: # An error occurred while parsing POST data. Since when # formatting the error the request handler might access # self.POST, set self._post and self._file to prevent # attempts to parse POST data again. # Mark that an error occurred. This allows self.__repr__ to # be explicit about it instead of simply representing an # empty POST self._mark_post_parse_error() raise elif self.content_type == ‘application/x-www-form-urlencoded‘: self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict() else: self._post, self._files = QueryDict(encoding=self._encoding), MultiValueDict()
class LoginView(View): def get(self, request): return render(request, ‘classbasedview/login.html‘) def post(self, request): print(request.POST) # <QueryDict: {}> print(request.body) # b‘{"username":"alex","password":123}‘ data = request.body.decode(‘utf-8‘) dict_data = json.loads(data) username = dict_data[‘username‘] password = dict_data[‘password‘] return HttpResponse(json.dumps(dict_data))
如图所示,在下拉框中选择GET方式发送请求,在地址栏输入请求url,然后点击send发送即可发送GET请求到后端服务器。
请看下图:
标签:合规 选项 增加 解析 传递 script ajax 标准 load
原文地址:https://www.cnblogs.com/qicun/p/10104852.html