第六模块:WEB框架开发 第1章·Django框架开发1~50
- 01-Django基础介绍
- 02-Web应用程序1
- 03-Web应用程序2
- 04-http请求协议1
- 05-http请求协议2
- 06-http协议之响应协议
- 07-wsgire模块1
- 08-wsgire模块2
- 09-DIY一个Web框架1
- 10-DIY一个Web框架2
- 11-DIY一个Web框架3
- 12-框架的简单使用
- 13-扩展框架关于数据库的操作
- 14-Django简介
- 15-Django的下载与基本命令
- 16-Django简单实例
- 17-静态文件配置1
- 18-静态文件配置2
- 19-路由控制之“简单配置”
- 20-路由控制之“有名分组”
- 21-路由控制之“分发”
- 22-路由控制之登录验证示例
- 23-路由控制之反向解析1
- 24-流程控制之反向解析2
- 25-路由控制之名称空间1
- 26-路由控制之名称空间2
- 27-url控制器之path方法
- 28-path的自定义转换器
- 29-url控制总结
- 30-视图层之请求对象
- 31-视图响应对象
- 32-模版语法之变量
- 33-过滤器
- 34-模版语法之标签
- 35-模版语法之自定义标签与过滤器
- 36-模版语法之继承
- 37-ORM简介
- 38-单表操作之生成表模型
- 39-单表操作之添加记录
- 40-单表操作之查询API-1
- 41-单表操作之查询API-2
- 42-单表操作之查询API-3
- 43-单表操作之模糊查询
- 44-单表查询之删除与修改操作
- 45-单表操作章节作业
- 46-单表操作章节作业讲解
- 47-图书管理系统之添加页面
- 48-图书管理系统之查看书籍
- 49-图书管理系统之删除数据
- 50-图书管理系统之编辑功能
01-Django基础介绍
1、什么是Django?
Python中最强大的Web开发框架;
2、Web框架是什么?(Web应用框架);
什么是Web应用?
欲知后事如何请听下回分解;
3、客户端和服务端;
- 发送请求的一端;
- 接受请求并作出响应的一端;
4、请求过程和相应过程;
- 向服务端发送字符串的过程;
- 解析来自客户端的数据,并返回数据的过程;
5、开发的是服务端;
Server.py;
6、成熟的客户端;
- Chrome;
- Firefox;
- IE;
- Safari;
- Opera;
- 其他第三方浏览器,如360极速浏览器、QQ浏览器、搜狗极速浏览器;
02-Web应用程序1
1、开发简单的server.py;
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/14 12:05
import socket sock = socket.socket()
sock.bind(("127.0.0.1",8800))
sock.listen(5) #进入通信循环;
while True:
print("JDServer is waiting....")
conn,addr = sock.accept()
data = conn.recv(1024)
print("data",data)
#conn.send(b"Hello LuffyCity!")
conn.send(b"HTTP/1.1 200 OK\r\n\r\nHello LuffyCity!")
conn.close()
03-Web应用程序2
1、server.py;
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/14 12:05
import socket sock = socket.socket()
sock.bind(("127.0.0.1",8800))
sock.listen(5) #进入通信循环;
while True:
print("JDServer is waiting....")
conn,addr = sock.accept()
data = conn.recv(1024)
print("data",data)
#conn.send(b"Hello LuffyCity!")
with open("index.html","rb") as f:
data = f.read()
conn.send(("HTTP/1.1 200 OK\r\n\r\n%s"%data).encode("gbk"))
conn.close()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>03-Web应用程序02</title>
<style type="text/css"> </style>
</head>
<body>
<h1>Hello LuffyCity!</h1>
<img src='https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534231128705&di=067e25afed9b53931f6cfc95485c880a&imgtype=0&src=http%3A%2F%2Fimg5.duitang.com%2Fuploads%2Fitem%2F201609%2F12%2F20160912220442_yQCLi.jpeg'>
<a href="http://www.luffycity.com">路飞学城</a>
</body>
</html>
index.html
04-http请求协议1
1、HTTP协议初识;
1)HTTP协议是Hyper Text Transfer Protocol(超文本传输协议)的缩写,是用于万维网(WWW:World Wide Web )服务器与本地浏览器之间传输超文本的传送协议;
2)HTTP是一个属于应用层的面向对象的协议,由于其简捷、快速的方式,适用于分布式超媒体信息系统,它于1990年提出,经过几年的使用与发展,得到不断地完善和扩展,HTTP协议工作于客户端-服务端架构之上;
3)浏览器作为HTTP客户端通过URL向HTTP服务端即WEB服务器发送所有请求,Web服务器根据接收到的请求后,向客户端发送响应信息;
2、HTTP协议是基于TCP/IP协议之上的“应用层协议”;
3、HTTP协议是基于“请求<--->响应”模式;
HTTP协议规定,请求从客户端发出,最后服务器端响应该请求并返回。换句话说,肯定是先从客户端开始建立通信的,服务器端在没有接收到请求之前不会发送响应;
4、HTTP协议“无状态保存”;
HTTP是一种不保存状态,即无状态(stateless)协议。HTTP协议自身不对请求和响应之间的通信状态进行保存。也就是说在HTTP这个级别,协议对于发送过的请求或响应都不做持久化处理;
5、HTTP协议“无连接”;
无连接的含义是限制每次连接只处理一个请求。服务器处理完客户的请求,并收到客户的应答后,即断开连接。采用这种方式可以节省传输时间;
6、请求格式;
7、请求方式:GET和POST请求;
- GET请求提交的数据会放在URL之后,以?分割URL的传输的数据,参数之间使用&相连接,比如?name=cuixiaozhao&age=26,POST方法是把提交的数据放在HTTP包的“请求体”中;
- GET提交的数据大小有限制(因为浏览器对URL的长度有限制),而POST方法提交的数据没有限制;
- GET与POST请求在服务端获取请求数据方式不同;
操作日志:
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/14 17:04 import socket sock = socket.socket()
sock.bind(("127.0.0.1",8800))
sock.listen(5) #进入通信循环;
while 1:
print("JDServer is waiting123....")
conn,addr = sock.accept()
data = conn.recv(1024)
print("data",data)
#conn.send(b"Hello LuffyCity!")
#读取html文件;
with open("index.html","rb") as f:
data = f.read()
#conn.send(b"HTTP/1.1 200 OK\r\n\r\n%s"%data)
conn.send((b"HTTP/1.1 200 OK\r\n\r\n%s"%data))
conn.close()
'''
请求首行:
请求头:
请求头:
请求头:
请求头:
请求头:
请求头:
请求体:(name=cuixiaozhao&age=26),注意只有POST请求才有"请求体"! data b'GET / HTTP/1.1\r\n
Host: 127.0.0.1:8800\r\n
Connection: keep-alive\r\n
Cache-Control: max-age=0\r\n
Upgrade-Insecure-Requests: 1\r\n
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.12 Safari/537.36\r\n
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\n
Accept-Encoding: gzip, deflate, br\r\n
Accept-Language: zh-CN,zh;q=0.9\r\n
Cookie: csrftoken=V87q4DAWGWiZjGlroQ26elLbUtzrzIaxPS3zy6t8Hn71BCTQBTXM4UVqoMNB4sf8; sessionid=7b47t1sqsplymr83a167lt1c6y2pa0kq\r\n
\r\n'
JDServer is waiting123....
''' """ data b'GET /tqtl?name=cuixiaozhao&age=26 HTTP/1.1\r\n
Host: 127.0.0.1:8800\r\n
Connection: keep-alive\r\n
Upgrade-Insecure-Requests: 1\r\n
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.12 Safari/537.36\r\n
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\n
Accept-Encoding: gzip, deflate, br\r\n
Accept-Language: zh-CN,zh;q=0.9\r\n
Cookie: csrftoken=V87q4DAWGWiZjGlroQ26elLbUtzrzIaxPS3zy6t8Hn71BCTQBTXM4UVqoMNB4sf8; sessionid=7b47t1sqsplymr83a167lt1c6y2pa0kq\r\n
\r\n'
JDServer is waiting123....
"""
05-http请求协议2
1、http请求协议之post请求;
操作日志:
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/14 17:04 import socket sock = socket.socket()
sock.bind(("127.0.0.1",8800))
sock.listen(5) #进入通信循环;
while 1:
print("JDServer is waiting123....")
conn,addr = sock.accept()
data = conn.recv(1024)
print("data",data)
#读取html文件;
with open("login.html","rb") as f:
data = f.read()
conn.send((b"HTTP/1.1 200 OK\r\n\r\n%s"%data))
conn.close()
"""
data b'POST / HTTP/1.1\r\n
Host: 127.0.0.1:8800\r\n
Connection: keep-alive\r\n
Content-Length: 36\r\n
Cache-Control: max-age=0\r\n
Origin: http://127.0.0.1:8800\r\n
Upgrade-Insecure-Requests: 1\r\n
Content-Type: application/x-www-form-urlencoded\r\n
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.12 Safari/537.36\r\n
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\n
Referer: http://127.0.0.1:8800/\r\n
Accept-Encoding: gzip, deflate, br\r\n
Accept-Language: zh-CN,zh;q=0.9\r\n
Cookie: csrftoken=V87q4DAWGWiZjGlroQ26elLbUtzrzIaxPS3zy6t8Hn71BCTQBTXM4UVqoMNB4sf8; sessionid=7b47t1sqsplymr83a167lt1c6y2pa0kq\r\n
\r\nusername=cuixiaozhao&password=Ab123.'
JDServer is waiting123....
"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>03-Web应用程序02</title>
<style type="text/css"> </style>
</head>
<body>
<form action="http://127.0.0.1:8800" method="post">
用户名:<input type="text" name="username" >
密码:<input type="password" name="password" >
<input type="submit"></input>
</form>
</body>
</html>
06-http协议之响应协议
1、get与post的使用场景;
- get即获取的意思,比如对数据库的查询操作;
- post即提交的意思,比如增、删和改等操作;
另外补充:
- GET方式提交数据,会带来安全问题,比如一个登录页面,通过GET方式提交数据时,用户名和密码将出现在URL上,如果页面可以被缓存或者其他人可以访问这台机器,就可以从历史记录获得该用户的账号和密码;
2、http协议之响应协议初识;
3、响应的状态码;
状态码指的是当客户端向服务器端发送请求时, 返回的请求结果,借助状态码,用户可以知道服务器端是正常处理了请求,还是出现异常了 。
操作日志:
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/14 17:44
import socket sock = socket.socket()
sock.bind(("127.0.0.1",8800))
sock.listen(5) #进入通信循环;
while 1:
print("JDServer is waiting123....")
conn,addr = sock.accept()
data = conn.recv(1024)
print("data",data)
#读取html文件;
with open("login.html","rb") as f:
data = f.read()
conn.send((b"HTTP/1.1 200 OK\r\nContent-Type:text\r\n\r\n%s"%data))
conn.close()
07-wsgire模块1
1、Web应用;
1)Web应用程序是一种可以通过Web访问的应用程序,程序的最大好处是用户很容易访问应用程序,用户只需要有浏览器即可,不需要再安装其他软件;
2)应用程序有两种模式C/S、B/S。C/S是客户端/服务器端程序,也就是说这类程序一般独立运行。而B/S就是浏览器/服务器端应用程序,这类应用程序一般借助谷歌,火狐等浏览器来运行;
3)Web应用程序一般是B/S模式。Web应用程序首先是“应用程序”,和用标准的程序语言,如java,python等编写出来的程序没有什么本质上的不同。
4) 在网络编程的意义下,浏览器是一个socket客户端,服务器是一个socket服务端;
2、Web框架;
Web框架(Web framework)是一种开发框架,用来支持动态网站、网络应用和网络服务的开发。这大多数的Web框架提供了一套开发和部署网站的方式,也为Web行为提供了一套通用的方法;
Web框架已经实现了很多功能,开发人员使用框架提供的方法并且完成自己的业务逻辑,就能快速开发Web应用了。浏览器和服务器的是基于HTTP协议进行通信的。也可以说Web框架就是在以上十几行代码基础张扩展出来的,有很多简单方便使用的方法,大大提高了开发的效率;
3、wsgiref模块初识;
最简单的Web应用就是先把HTML用文件保存好,用一个现成的HTTP服务器软件,接收用户请求,从文件中读取HTML,返回;
如果要动态生成HTML,就需要把上述步骤自己来实现。不过,接受HTTP请求、解析HTTP请求、发送HTTP响应都是苦力活,如果我们自己来写这些底层代码,还没开始写动态HTML呢,就得花个把月去读HTTP规范;
正确的做法是底层代码由专门的服务器软件实现,我们用Python专注于生成HTML文档。因为我们不希望接触到TCP连接、HTTP原始请求和响应格式,所以,需要一个统一的接口协议来实现这样的服务器软件,让我们专心用Python编写Web业务。这个接口就是WSGI:Web Server Gateway Interface,而wsgiref模块就是python基于wsgi协议开发的服务模块;
操作日志:
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/14 17:44
import socket sock = socket.socket()
sock.bind(("127.0.0.1",8800))
sock.listen(5) #进入通信循环;
while 1:
print("JDServer is waiting123....")
conn,addr = sock.accept()
data = conn.recv(1024)#------------------dict/obj d={"path":"/login"}
print("data",data)
#读取html文件;
with open("login.html","rb") as f:
data = f.read()
conn.send((b"HTTP/1.1 200 OK\r\nContent-Type:text\r\n\r\n%s"%data))
conn.close() '''
1、按照HTTP请求协议解析数据;
#专注于Web的业务开发;
path = d.get("path")
if path == "/login":
return login.html
2、按照HTTP响应协议封装数据;
'''
08-wsgire模块2
1、Web框架代码演示:
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/14 20:52
from wsgiref.simple_server import make_server print("is starting")
def application(environ, start_response):
#按照http协议解析数据:environ;
#按照http协议进行组装数据:start_response;
print(environ)
print(type(environ))
#当前的请求路径;
path = environ.get("PATH_INFO")
start_response('200 OK',[])
if path == "/login":
with open("login.html","r") as f:
data = f.read()
return [data]
elif path == "/index":
with open("index.html","r") as f:
data = f.read()
return [data]# start_response('200 OK',[])
return [b"<h1>Hello Web</h1>"] # 已经封装了socket模块的前三步;
httpd = make_server("",8800,application)#封装了socket;
#等待用户连接:conn,addr = sock.accept()
httpd.serve_forever()#application(environ,start_response)
"""
{'ALLUSERSPROFILE': 'C:\\ProgramData', 'APPDATA': 'C:\\Users\\TQTL911\\AppData\\Roaming', 'CLASSPATH': '.;C:\\Program Files\\Java\\jdk1.7.0_80\\lib;C:\\Program Files\\Java\\jdk1.7.0_80\\lib\\tools.jar', 'COMMONPROGRAMFILES': 'C:\\Program Files\\Common Files', 'COMMONPROGRAMFILES(X86)': 'C:\\Program Files (x86)\\Common Files', 'COMMONPROGRAMW6432': 'C:\\Program Files\\Common Files', 'COMPUTERNAME': 'DESKTOP-U8JDGPP', 'COMSPEC': 'C:\\Windows\\system32\\cmd.exe', 'DRIVERDATA': 'C:\\Windows\\System32\\Drivers\\DriverData', 'FPS_BROWSER_APP_PROFILE_STRING': 'Internet Explorer', 'FPS_BROWSER_USER_PROFILE_STRING': 'Default', 'HOMEDRIVE': 'C:', 'HOMEPATH': '\\Users\\TQTL911', 'JAVA_HOME': 'C:\\Program Files\\Java\\jdk1.7.0_80', 'LOCALAPPDATA': 'C:\\Users\\TQTL911\\AppData\\Local', 'LOGONSERVER': '\\\\DESKTOP-U8JDGPP', 'NUMBER_OF_PROCESSORS': '8', 'OS': 'Windows_NT', 'PATH': 'C:\\Program Files\\Python36\\;C:\\Program Files\\Python36\\Scripts\\;C:\\Program Files\\Python27\\;C:\\Program Files\\Python27\\Scripts;D:\\Program\\Anaconda3;D:\\Program\\Anaconda3\\Library\\mingw-w64\\bin;D:\\Program\\Anaconda3\\Library\\usr\\bin;D:\\Program\\Anaconda3\\Library\\bin;D:\\Program\\Anaconda3\\Scripts;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Windows\\System32\\OpenSSH\\;C:\\Program Files\\MySQL\\MySQL Utilities 1.6\\;C:\\Program Files (x86)\\NVIDIA Corporation\\PhysX\\Common;C:\\Program Files\\MySQL\\MySQL Server 5.7\\bin;C:\\Program Files\\Java\\jdk1.7.0_80\\bin;C:\\Program Files (x86)\\Windows Kits\\8.1\\Windows Performance Toolkit\\;D:\\Program\\Redis3.2.10\\;D:\\Program\\Tesseract-OCR;;D:\\Program\\WinMerge;C:\\Users\\TQTL911\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\TQTL911\\PycharmProjects\\Web开发\\venv\\Scripts', 'PATHEXT': '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW', 'PROCESSOR_ARCHITECTURE': 'AMD64', 'PROCESSOR_IDENTIFIER': 'Intel64 Family 6 Model 94 Stepping 3, GenuineIntel', 'PROCESSOR_LEVEL': '6', 'PROCESSOR_REVISION': '5e03', 'PROGRAMDATA': 'C:\\ProgramData', 'PROGRAMFILES': 'C:\\Program Files', 'PROGRAMFILES(X86)': 'C:\\Program Files (x86)', 'PROGRAMW6432': 'C:\\Program Files', 'PROMPT': '(venv) $P$G', 'PSMODULEPATH': 'C:\\Program Files\\WindowsPowerShell\\Modules;C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules', 'PUBLIC': 'C:\\Users\\Public', 'PYCHARM_HOSTED': '1', 'PYCHARM_MATPLOTLIB_PORT': '50456', 'PYTHONIOENCODING': 'UTF-8', 'PYTHONPATH': 'D:\\Program\\PyCharm 2018.1.4\\helpers\\pycharm_matplotlib_backend;C:\\Users\\TQTL911\\PycharmProjects\\Web开发', 'PYTHONUNBUFFERED': '1', 'SESSIONNAME': 'Console', 'SYSTEMDRIVE': 'C:', 'SYSTEMROOT': 'C:\\Windows', 'TEMP': 'C:\\Users\\TQTL911\\AppData\\Local\\Temp', 'TESSDATA_PREFIX': 'D:\\Program\\Tesseract-OCR\\tessdata', 'TMP': 'C:\\Users\\TQTL911\\AppData\\Local\\Temp', 'USERDOMAIN': 'DESKTOP-U8JDGPP', 'USERDOMAIN_ROAMINGPROFILE': 'DESKTOP-U8JDGPP', 'USERNAME': 'TQTL911', 'USERPROFILE': 'C:\\Users\\TQTL911', 'VIRTUAL_ENV': 'C:\\Users\\TQTL911\\PycharmProjects\\Web寮�鍙慭venv', 'VS140COMNTOOLS': 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\Tools\\', 'WINDIR': 'C:\\Windows', '_OLD_VIRTUAL_PATH': 'C:\\Program Files\\Python36\\;C:\\Program Files\\Python36\\Scripts\\;C:\\Program Files\\Python27\\;C:\\Program Files\\Python27\\Scripts;D:\\Program\\Anaconda3;D:\\Program\\Anaconda3\\Library\\mingw-w64\\bin;D:\\Program\\Anaconda3\\Library\\usr\\bin;D:\\Program\\Anaconda3\\Library\\bin;D:\\Program\\Anaconda3\\Scripts;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Windows\\System32\\OpenSSH\\;C:\\Program Files\\MySQL\\MySQL Utilities 1.6\\;C:\\Program Files (x86)\\NVIDIA Corporation\\PhysX\\Common;C:\\Program Files\\MySQL\\MySQL Server 5.7\\bin;C:\\Program Files\\Java\\jdk1.7.0_80\\bin;C:\\Program Files (x86)\\Windows Kits\\8.1\\Windows Performance Toolkit\\;D:\\Program\\Redis3.2.10\\;D:\\Program\\Tesseract-OCR;;D:\\Program\\WinMerge;C:\\Users\\TQTL911\\AppData\\Local\\Microsoft\\WindowsApps', '_OLD_VIRTUAL_PROMPT': '$P$G', 'SERVER_NAME': 'DESKTOP-U8JDGPP', 'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_PORT': '18080', 'REMOTE_HOST': '', 'CONTENT_LENGTH': '', 'SCRIPT_NAME': '', 'SERVER_PROTOCOL': 'HTTP/1.1', 'SERVER_SOFTWARE': 'WSGIServer/0.2', 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/2321', 'QUERY_STRING': '', 'REMOTE_ADDR': '127.0.0.1', 'CONTENT_TYPE': 'text/plain', 'HTTP_HOST': '127.0.0.1:18080', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_UPGRADE_INSECURE_REQUESTS': '1', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.12 Safari/537.36', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate, br', 'HTTP_ACCEPT_LANGUAGE': 'zh-CN,zh;q=0.9', 'HTTP_COOKIE': 'csrftoken=V87q4DAWGWiZjGlroQ26elLbUtzrzIaxPS3zy6t8Hn71BCTQBTXM4UVqoMNB4sf8; sessionid=7b47t1sqsplymr83a167lt1c6y2pa0kq', 'wsgi.input': <_io.BufferedReader name=436>, 'wsgi.errors': <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>, 'wsgi.version': (1, 0), 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.multithread': True, 'wsgi.multiprocess': False, 'wsgi.file_wrapper': <class 'wsgiref.util.FileWrapper'>}
<class 'dict'>
"""
09-DIY一个Web框架
1、DIY一个Web框架01;
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/14 22:11
from wsgiref.simple_server import make_server def application(environ, start_response):
start_response('200 OK',[('Content-Type', 'text/html')])
print('PATH',environ.get('PATH_INFO'))
path = environ.get('PATH_INFO')
if path == "/favicon.ico":
with open("favicon.ico","rb") as f:
data = f.read()
return [data]
return [b'<h1>Hello,World!</h1>'] httpd = make_server('', 8080, application)
print('Server HTTP on port 8080')
#开始监听HTTP请求;
httpd.serve_forever()
10-DIY一个Web框架2
1、DiY一个Web框架2;
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/14 22:11
from wsgiref.simple_server import make_server def login(environ):
with open("login.html","rb")as f:
data = f.read()
return data
def index(environ):
with open("index.html","rb")as f:
data = f.read()
return data
def fav(environ):
with open("favicon.ico","rb")as f:
data = f.read()
return data
def reg(environ):
with open("reg.html","rb")as f:
data = f.read()
return data def application(environ, start_response):
start_response('200 OK',[('Content-Type', 'text/html'),("Charset","utf8")])
print('PATH',environ.get('PATH_INFO'))
path = environ.get('PATH_INFO')
# #方案1:
# if path == "/favicon.ico":
# with open("favicon.ico","rb") as f:
# data = f.read()
# return [data]
# elif path =="/login":
# with open("login.html","rb")as f:
# data = f.read()
# return [data]
# elif path =="/index":
# with open("index.html","rb")as f:
# data = f.read()
# return [data]
# elif path =="/reg":
# with open("reg.html","rb")as f:
# data = f.read()
# return [data]
# #方案2:
url_patterns = [
("/login",login),
("/index",index),
("/favicon.ico",fav),
("/reg",reg)
] func = None
for item in url_patterns:
if path == item[0]:
func = item[1]
break
if func:
return [func(environ)]
else:
return [b""] httpd = make_server("", 19988, application)
print('Server HTTP on port 19988')
#开始监听HTTP请求;
httpd.serve_forever()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>03-Web应用程序02</title>
<style type="text/css"> </style>
</head>
<body>
<h1>Hello LuffyCity!</h1>
<img src='https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534231128705&di=067e25afed9b53931f6cfc95485c880a&imgtype=0&src=http%3A%2F%2Fimg5.duitang.com%2Fuploads%2Fitem%2F201609%2F12%2F20160912220442_yQCLi.jpeg'>
<a href="http://www.luffycity.com">路飞学城</a>
</body>
</html>
index
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>03-Web应用程序02</title>
<style type="text/css"> </style>
</head>
<body>
<form action="http://127.0.0.1:19988" method="post">
用户名:<input type="text" name="username" >
密码:<input type="password" name="password" >
<input type="submit"></input>
</form>
</body>
</html>
login
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body> <h4>注册页面</h4> </body>
</html>
reg
11-DIY一个Web框架3
1、DIY一个Web框架3;
程序解耦合操作,提高层次结构。
12-框架的简单使用
1、在自己或者其他人写好的基础(重复复用的代码)代码之上,进行新功能拓展的packages就叫做Web框架;
2、Web框架是用来进行Web应用开发的一个软件架构,主要用于动态网络开发,开发者在基于Web框架实现自己的业务逻辑。Web框架实现了很多功能,为实现业务逻辑提供了一套通用方法;
13-扩展框架关于数据库的操作
1、自行开发的Web框架的目录结构;
2、代码目录;
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/15 10:31
from wsgiref.simple_server import make_server def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html'),('Charset','utf8')])
print("PATH",environ.get("PATH_INFO"))
path = environ.get("PATH_INFO") from urls import url_patterns
func = None for item in url_patterns:
if path == item[0]:
func = item[1]
break
if func:
return [func(environ)]
else:
return [b'404 not find pages'] httpd = make_server("",9988, application) #开始监听HTTP请求;
httpd.serve_forever()
main.py
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/15 10:34
#在数据库中,生成用户表; import pymysql
#连接MySQL数据库;
conn=pymysql.connect(host='localhost',user='root',password='Tqtl911!@#)^',database='django',charset='utf8')
#创建游标;
cursor=conn.cursor() #执行完毕返回的结果集默认以元组显示 #执行sql语句;
sql='''
create table userinfo(
id int primary key,
name varchar (32),
password varchar (32)
)
'''
print(sql)
res=cursor.execute(sql) #执行sql语句,返回sql查询成功的记录数目
print(res) #提交
conn.commit()
#关闭指针对象
cursor.close()
#关闭连接对象
conn.close() """
main.py:启动文件,封装了socket;
独立开发的Web框架总结:
1、urls.py:路径与视图函数的对应关系,------url控制器;
2、views.py:整个视图函数,固定有一个形式参数-environ,------视图函数;
3、templates目录:html文件, ---------模板部分;
4、models:在项目启动前,在数据库中创建表结构,-------与数据库相关;
"""
models.py
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/15 10:33 from views import * url_patterns = [
('/login',login),
('/index',index),
('/favicon.ico',fav),
('/timer',timer),
('/auth',auth),
('/reg',reg),
]
urls.py
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/15 10:33
def login(environ):
with open("templates/login.html","rb") as f:
data =f.read()
return data from urllib.parse import parse_qs def index(environ):
with open("templates/index.html","rb") as f:
data = f.read()
return data def fav(environ):
with open("templates/favicon.ico","rb") as f:
data = f.read()
return data def reg(environ):
with open("templates/reg.html","rb") as f:
data = f.read()
return data def timer(environ):
import datetime
now = datetime.datetime.now().strftime("%y-%m-%d %X")
return now.encode("utf8") def auth(request):
try:
request_body_size = int(request.get('CONTENT_LENGTH', 0))
except (ValueError):
request_body_size = 0 request_body = request['wsgi.input'].read(request_body_size)
data = parse_qs(request_body) user = data.get(b"user")[0].decode("utf8")
pwd = data.get(b"pwd")[0].decode("utf8") #连接MySQL数据库;
import pymysql
conn = pymysql.connect(host = "127.0.0.1",port = 3306,user = "root",passwd = "Tqtl911!@#)^",db = "django")
#创建游标;
cursor = conn.cursor()
SQL = "select * from userinfo where name = '%s' and password = '%s' "%(user,pwd)
cursor.execute(SQL)
if cursor.fetchone():
with open("templates/backend.html","rb") as f:
data = f.read()
data = data.decode("utf8")
return data.encode("utf8")
else:
return b"user or pwd is wrong."
views.py
3、小结:
"""
main.py:启动文件,封装了socket;
独立开发的Web框架总结:
1、urls.py:路径与视图函数的对应关系,------url控制器;
2、views.py:整个视图函数,固定有一个形式参数-environ,------视图函数;
3、templates目录:html文件, ---------模板部分;
4、models:在项目启动前,在数据库中创建表结构,-------与数据库相关;
"""
14-Django简介
1、什么是MVC模型?
Web服务器开发领域里著名的MVC模式,所谓MVC就是把Web应用分为模型(Mondel),控制器(Controller)和视图(View)三层,他们之间以一种插件式的、松耦合的方式连接在一起,模型负责业务对象与数据库的映射(ORM),视图负责与用户的交互(页面),控制器接受用户的输入调用模型和视图完成用户的请求,其示意图如下所示:
2、什么是MTV模型?
Django的MTV模式本质上和MVC是一样的,也是为了各组件间保持松耦合关系,只是定义上有些许不同,Django的MTV分别是值:
- M代表模型(Model):负责业务对象和数据库的关系映射(ORM);
- T代表模板(Template):负责如何把页面展示给用户(html);
- V代表视图(View):负责业务逻辑,并在适当时候调用Model和Template;
除了以上三层之外,还需要一个URL分发器,它的作用是将一个个URL的页面请求分发给不同的View处理,View再调用相应的Model和Template,MTV的响应模式如下所示:
一般是用户通过浏览器向我们的服务器发起一个请求(request),这个请求回去访问视图函数,(如果不涉及到数据调用,那么这个时候视图函数返回一个模板也就是一个网页给用户),视图函数调用模型,模型去数据库查找数据,然后逐级返回,视图函数把返回的数据填充到模板中空格中,最后返回网页给用户。
15-Django的下载与基本命令
1、下载并安装Django;
pip3 install django==2.0.1
1) Django官网:https://www.djangoproject.com/
2) 亦可使用编译安装(不推荐);
2、创建一个Django project——mysite;
django-admin startproject mysite(mysite为项目名称,自行自定义!)
3、在项目下创建应用——blog、app01(app名称自行定义);
python manage.py startapp blog
python manage.py startapp app01
4、启动Django项目;
相对路径:先进入django项目的主目录再进行启动;
python manage.py runserver 19939(可以不指定端口,默认为8000,建议使用大于10000的端口号)
5、查看Django项目的启动效果;
操作日志:
Microsoft Windows [版本 10.0.17134.1]
(c) 2018 Microsoft Corporation。保留所有权利。 (venv) C:\Users\TQTL911\PycharmProjects\LFXC2018>dir
驱动器 C 中的卷没有标签。
卷的序列号是 B2D2-AA19 C:\Users\TQTL911\PycharmProjects\LFXC2018 的目录 2018/08/11 12:45 <DIR> .
2018/08/11 12:45 <DIR> ..
2018/08/15 15:06 <DIR> .idea
2018/07/29 15:52 <DIR> data
2018/07/16 13:49 <DIR> homework
2018/08/14 09:59 <DIR> myblog
2018/07/18 21:39 <DIR> mysite
2018/07/29 16:07 <DIR> Python3网络爬虫实战
2018/07/29 15:51 <DIR> venv
2018/06/30 17:51 <DIR> 第1模块开发基础
2018/07/03 16:16 <DIR> 第2模块函数编程
2018/07/14 16:11 <DIR> 第3模块面向对象&网络编程基础
2018/07/27 18:06 <DIR> 第4模块网络编程进阶&数据库开发
2018/08/01 11:07 <DIR> 第5模块WEB开发基础
2018/07/17 17:37 <DIR> 考核目录
0 个文件 0 字节
15 个目录 86,502,342,656 可用字节 (venv) C:\Users\TQTL911\PycharmProjects\LFXC2018>cd .. (venv) C:\Users\TQTL911\PycharmProjects>ll
'll' 不是内部或外部命令,也不是可运行的程序
或批处理文件。 (venv) C:\Users\TQTL911\PycharmProjects>dir
驱动器 C 中的卷没有标签。
卷的序列号是 B2D2-AA19 C:\Users\TQTL911\PycharmProjects 的目录 2018/08/14 12:05 <DIR> .
2018/08/14 12:05 <DIR> ..
2018/08/11 12:45 <DIR> LFXC2018
2018/08/15 14:46 <DIR> Web开发
0 个文件 0 字节
4 个目录 86,502,252,544 可用字节 (venv) C:\Users\TQTL911\PycharmProjects>cd We
系统找不到指定的路径。 (venv) C:\Users\TQTL911\PycharmProjects>cd Web开发 (venv) C:\Users\TQTL911\PycharmProjects\Web开发>django-admin.py startproject tqtl
Traceback (most recent call last):
File "C:\Users\TQTL911\PycharmProjects\LFXC2018\venv\Scripts\django-admin.py", line 2, in <module>
from django.core import management
ImportError: No module named django.core (venv) C:\Users\TQTL911\PycharmProjects\Web开发>django-admin startproject tqtl (venv) C:\Users\TQTL911\PycharmProjects\Web开发>django-admin startproject tqtl911 (venv) C:\Users\TQTL911\PycharmProjects\Web开发>django-admin startproject mysite (venv) C:\Users\TQTL911\PycharmProjects\Web开发>dir
驱动器 C 中的卷没有标签。
卷的序列号是 B2D2-AA19 C:\Users\TQTL911\PycharmProjects\Web开发 的目录 2018/08/15 15:11 <DIR> .
2018/08/15 15:11 <DIR> ..
2018/08/15 11:15 <DIR> .idea
2018/08/14 16:45 <DIR> 02-web应用程序1
2018/08/15 09:37 <DIR> 03-web应用程序2
2018/08/15 09:37 <DIR> 04-http请求协议1
2018/08/15 09:37 <DIR> 05-http请求协议2
2018/08/15 09:37 <DIR> 06-http协议之响应协议
2018/08/15 09:37 <DIR> 07-wsgiref模块1
2018/08/15 10:01 <DIR> 08-wsgiref模块2
2018/08/15 08:43 <DIR> 09-DIY一个web框架
2018/08/15 09:51 <DIR> 10-DIY一个web框架2
2018/08/15 11:58 <DIR> 11-DIY一个web框架3
2018/08/15 10:23 <DIR> 12-框架的简单使用
2018/08/15 11:59 <DIR> 13-扩展框架关于数据库的操作
2018/08/15 14:46 <DIR> 14-Django简介
2018/08/15 15:11 <DIR> mysite
2018/08/15 15:10 <DIR> tqtl911
2018/08/14 12:05 <DIR> venv
0 个文件 0 字节
19 个目录 86,498,488,320 可用字节 (venv) C:\Users\TQTL911\PycharmProjects\Web开发>cd mysite (venv) C:\Users\TQTL911\PycharmProjects\Web开发\mysite>dir
驱动器 C 中的卷没有标签。
卷的序列号是 B2D2-AA19 C:\Users\TQTL911\PycharmProjects\Web开发\mysite 的目录 2018/08/15 15:11 <DIR> .
2018/08/15 15:11 <DIR> ..
2018/08/15 15:11 553 manage.py
2018/08/15 15:11 <DIR> mysite
1 个文件 553 字节
3 个目录 86,498,291,712 可用字节 (venv) C:\Users\TQTL911\PycharmProjects\Web开发\mysite>python3 manage.py startapp blog
Traceback (most recent call last):
File "manage.py", line 8, in <module>
from django.core.management import execute_from_command_line
ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last):
File "manage.py", line 14, in <module>
) from exc
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? (venv) C:\Users\TQTL911\PycharmProjects\Web开发\mysite>python manage.py startapp blog (venv) C:\Users\TQTL911\PycharmProjects\Web开发\mysite>python manage.py startapp app01 (venv) C:\Users\TQTL911\PycharmProjects\Web开发\mysite>python manage.py runserver 127.0.0.1:19939
Performing system checks... System check identified no issues (0 silenced). You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
August 15, 2018 - 15:21:06
Django version 2.1, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:19939/
Quit the server with CTRL-BREAK.
[15/Aug/2018 15:21:21] "GET / HTTP/1.1" 200 16348
[15/Aug/2018 15:21:21] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423
[15/Aug/2018 15:21:21] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 82564
[15/Aug/2018 15:21:21] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 80304
[15/Aug/2018 15:21:21] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 81348
Not Found: /favicon.ico
[15/Aug/2018 15:21:21] "GET /favicon.ico HTTP/1.1" 404 1973 (venv) C:\Users\TQTL911\PycharmProjects\Web开发\mysite>pip3 uninstall django
Uninstalling Django-2.1:
Would remove:
c:\users\tqtl911\pycharmprojects\lfxc2018\venv\lib\site-packages\django-2.1.dist-info\*
c:\users\tqtl911\pycharmprojects\lfxc2018\venv\lib\site-packages\django\*
c:\users\tqtl911\pycharmprojects\lfxc2018\venv\scripts\django-admin.exe
c:\users\tqtl911\pycharmprojects\lfxc2018\venv\scripts\django-admin.py
Proceed (y/n)? y
Successfully uninstalled Django-2.1
You are using pip version 10.0.1, however version 18.0 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command. (venv) C:\Users\TQTL911\PycharmProjects\Web开发\mysite>pip3 install django==2.0.1
Collecting django==2.0.1
Downloading https://files.pythonhosted.org/packages/21/2a/3a0ec97b18d6e8d295142228f03604ac78ea6de05cf9bc3773a74f0b58bb/Django-2.0.1-py3-none-any.whl (
7.1MB)
100% |████████████████████████████████| 7.1MB 4.5MB/s
Requirement already satisfied: pytz in c:\users\tqtl911\pycharmprojects\lfxc2018\venv\lib\site-packages (from django==2.0.1) (2018.5)
abakus-status-checks 0.0.1 has requirement requests[security]==2.8.1, but you'll have requests 2.19.1 which is incompatible.
Installing collected packages: django
Successfully installed django-2.0.1
You are using pip version 10.0.1, however version 18.0 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command. (venv) C:\Users\TQTL911\PycharmProjects\Web开发\mysite>pip show django
Name: Django
Version: 2.0.1
Summary: A high-level Python Web framework that encourages rapid development and clean, pragmatic design.
Home-page: https://www.djangoproject.com/
Author: Django Software Foundation
Author-email: foundation@djangoproject.com
License: BSD
Location: c:\users\tqtl911\pycharmprojects\lfxc2018\venv\lib\site-packages
Requires: pytz
Required-by:
You are using pip version 10.0.1, however version 18.0 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command. (venv) C:\Users\TQTL911\PycharmProjects\Web开发\mysite>python manage.py runserver 19939
Performing system checks... System check identified no issues (0 silenced). You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
August 15, 2018 - 15:27:18
Django version 2.0.1, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:19939/
Quit the server with CTRL-BREAK.
[15/Aug/2018 15:27:23] "GET / HTTP/1.1" 200 16559
[15/Aug/2018 15:27:24] "GET / HTTP/1.1" 200 16559
[15/Aug/2018 15:27:24] "GET / HTTP/1.1" 200 16559
[15/Aug/2018 15:27:24] "GET / HTTP/1.1" 200 16559
[15/Aug/2018 15:27:25] "GET / HTTP/1.1" 200 16559
[15/Aug/2018 15:27:25] "GET / HTTP/1.1" 200 16559
[15/Aug/2018 15:27:25] "GET / HTTP/1.1" 200 16559 (venv) C:\Users\TQTL911\PycharmProjects\Web开发\mysite>pip3 uninstall django==2.0.1
Uninstalling Django-2.0.1:
Would remove:
c:\users\tqtl911\pycharmprojects\lfxc2018\venv\lib\site-packages\django-2.0.1.dist-info\*
c:\users\tqtl911\pycharmprojects\lfxc2018\venv\lib\site-packages\django\*
c:\users\tqtl911\pycharmprojects\lfxc2018\venv\scripts\django-admin.exe
c:\users\tqtl911\pycharmprojects\lfxc2018\venv\scripts\django-admin.py
Proceed (y/n)? y
Successfully uninstalled Django-2.0.1
You are using pip version 10.0.1, however version 18.0 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command. (venv) C:\Users\TQTL911\PycharmProjects\Web开发\mysite>from django.shortcuts import render
'from' 不是内部或外部命令,也不是可运行的程序
或批处理文件。 (venv) C:\Users\TQTL911\PycharmProjects\Web开发\mysite>from django.shortcuts import render
'from' 不是内部或外部命令,也不是可运行的程序
或批处理文件。 (venv) C:\Users\TQTL911\PycharmProjects\Web开发\mysite>pip3 install Django==2.1
Collecting Django==2.1
Using cached https://files.pythonhosted.org/packages/51/1a/e0ac7886c7123a03814178d7517dc822af0fe51a72e1a6bff26153103322/Django-2.1-py3-none-any.whl
Requirement already satisfied: pytz in c:\users\tqtl911\pycharmprojects\lfxc2018\venv\lib\site-packages (from Django==2.1) (2018.5)
abakus-status-checks 0.0.1 has requirement requests[security]==2.8.1, but you'll have requests 2.19.1 which is incompatible.
Installing collected packages: Django
Successfully installed Django-2.1
You are using pip version 10.0.1, however version 18.0 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command. (venv) C:\Users\TQTL911\PycharmProjects\Web开发\mysite>python manage.py runserver 19939
Performing system checks... System check identified no issues (0 silenced). You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
August 15, 2018 - 15:31:21
Django version 2.1, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:19939/
Quit the server with CTRL-BREAK.
16-Django简单实例
1、通过Pycharm创建Django项目并配置应用app01;
17-静态文件配置1
1、在Django的settings.py中配置STATICFILES_DIRS;
#此处不修改,约定俗成!
STATIC_URL = '/static/' #必须叫做这个名称STATICFILES_DIRS,是一个列表;
STATICFILES_DIRS = [
os.path.join(BASE_DIR,"statics")
]
2、在新增目录statics中引入jQuery等静态文件,static目录必须放在公共区域,即Django项目的第一层目录下;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
h4{
color: red;
}
</style>
<script src="/static/jquery-3.3.1.js"></script>
</head>
<body>
<h4>Hi,{{ctime}}</h4>
<script>
$("h4").click(function () {
$(this).css('color','green')
})
</script>
</body>
</html>
18-静态文件配置2
1、修改应用app01的路径至statics;
2、将timer.css以及timer.js文件分离出timer.html,添加至app01目录下,然后进行引用;
PS:独立的js文件,默认添加分号但css文件末尾不需要添加分号,否则报错;
$("h4").click(function () {
$(this).css('color','green')
});
timer.js
h4{
color: red;
}
timer.css
3、timer.html的文件内容如下(注意js文件与body中html代码的先后顺序):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title> <script src="/static/jquery-3.3.1.js"></script>
<link rel="stylesheet" href="/static/app01/timer.css"> </head>
<body>
<h4>Hi,{{ctime}}</h4>
<script src="/static/app01/timer.js"></script>
</body>
</html>
19-路由控制之简单配置
1、Django中的路由概述;
URL配置(URLconf)就像Django所支撑网站的目录,它的本质是URL与要为该URL调用的视图函数之间的映射表,我们就是以这种方式告诉Django,对于客户端发来的某个URL调用哪一段逻辑代码对应执行;
2、简单的路由配置;
urls.py;
"""demo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,re_path
from statics.app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('timer/', views.timer), #简单的路由配置:路径------>视图函数;从上至下进行判断;
re_path(r'^articles/2003/$',views.special_case_2003),#special_case_2003(request)
re_path(r'^articles/([0-9]{4})/$',views.year_archive),#此处分组之后,相当于传入了两个参数;year_archive(request,2009)
re_path(r'^articles/([0-9]{4})/([0-9]{2})/$',views.month_archive),#此处分组之后,相当于传入了两个参数;month_archive(request,2009,11)
re_path(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$',views.article_detail)#掺入3个参数;
] """
一些请求的例子:
articles/2005/03/ 请求将匹配列表中的第三个模式。Django 将调用函数views.month_archive(request, '2005', '03');
/articles/2005/3/ 不匹配任何URL 模式,因为列表中的第三个模式要求月份应该是两个数字;
/articles/2003/ 将匹配列表中的第一个模式不是第二个,因为模式按顺序匹配,第一个会首先测试是否匹配。请像这样自由插入一些特殊的情况来探测匹配的次序;
/articles/2003 不匹配任何一个模式,因为每个模式要求URL 以一个反斜线结尾;
/articles/2003/03/03/ 将匹配最后一个模式。Django 将调用函数views.article_detail(request, '2003', '03', '03');
"""
views.py
from django.shortcuts import render,HttpResponse # Create your views here. def timer(request):
import time
ctime = time.time() return render(request, "time.html", {"ctime":ctime}) def special_case_2003(request):
return HttpResponse("special_case_2003") def year_archive(request,year):
return HttpResponse(year,"year.....") def month_archive(request,year,month):
return HttpResponse(year+"-"+month) def article_detail(request,year,month,detail):
return HttpResponse(year+"-"+month+"-"+detail)
3、路由配置的注意事项;
- 如若从URL中捕获一个值,只需要在它周围放置一对圆括号;
- 不需要添加一个前导的反斜杠,因为每个URL都有,例如应该是^articles,而不是^/articles;
- 每个正则表达式前面的"r"是可选的,但是建议加上,它告诉Python解释器,该字符串是“原始的”---字符串中任何字符都不应该转义;
20-路由控制之有名分组
1、有名分组;
在Python 正则表达式中,命名正则表达式组的语法是(?P<name>pattern)
,其中name
是组的名称,pattern
是要匹配的模式;
下面是以上URLconf 使用命名组的重写:
注意:views中的函数的顺序与urls匹配规则中的的顺序要一致,否则报错!
from django.shortcuts import render,HttpResponse # Create your views here. def timer(request):
import time
ctime = time.time() return render(request, "time.html", {"ctime":ctime}) def special_case_2003(request):
return HttpResponse("special_case_2003") def year_archive(request,year):
return HttpResponse(year,"year.....") #def month_archive(request,year,month):
#def month_archive(request,y,m):
def month_archive(request,m,y):
return HttpResponse(y+"-"+m) def article_detail(request,year,month,detail):
return HttpResponse(year+"-"+month+"-"+detail)
"""demo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,re_path
from statics.app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('timer/', views.timer), #简单的路由配置:路径------>视图函数;从上至下进行判断;
re_path(r'^articles/2003/$',views.special_case_2003),#special_case_2003(request)
re_path(r'^articles/([0-9]{4})/$',views.year_archive),#此处分组之后,相当于传入了两个参数;year_archive(request,2009)
#re_path(r'^articles/([0-9]{4})/([0-9]{2})/$',views.month_archive),#此处分组之后,相当于传入了两个参数;month_archive(request,2009,11)
re_path(r'^articles/(?P<y>[0-9]{4})/(?P<m>[0-9]{2})/$',views.month_archive),#此处分组之后,相当于传入了两个参数;month_archive(request,y=2009,m=11)
re_path(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$',views.article_detail)#掺入3个参数;
] """
一些请求的例子:
articles/2005/03/ 请求将匹配列表中的第三个模式。Django 将调用函数views.month_archive(request, '2005', '03');
/articles/2005/3/ 不匹配任何URL 模式,因为列表中的第三个模式要求月份应该是两个数字;
/articles/2003/ 将匹配列表中的第一个模式不是第二个,因为模式按顺序匹配,第一个会首先测试是否匹配。请像这样自由插入一些特殊的情况来探测匹配的次序;
/articles/2003 不匹配任何一个模式,因为每个模式要求URL 以一个反斜线结尾;
/articles/2003/03/03/ 将匹配最后一个模式。Django 将调用函数views.article_detail(request, '2003', '03', '03');
"""
21-路由控制之分发
1、Django路由控制之分发urls.py中include引入阐述(类似于nginx.conf中的自定义文件被nginx的主配置文件nginx.conf使用include进行引入,建立映射关系);
"""demo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,re_path,include from statics.app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('timer/', views.timer), #简单的路由配置:路径------>视图函数;从上至下进行判断;
# re_path(r'^articles/2003/$',views.special_case_2003),#special_case_2003(request)
# re_path(r'^articles/([0-9]{4})/$',views.year_archive),#此处分组之后,相当于传入了两个参数;year_archive(request,2009)
# #re_path(r'^articles/([0-9]{4})/([0-9]{2})/$',views.month_archive),#此处分组之后,相当于传入了两个参数;month_archive(request,2009,11)
# re_path(r'^articles/(?P<y>[0-9]{4})/(?P<m>[0-9]{2})/$',views.month_archive),#此处分组之后,相当于传入了两个参数;month_archive(request,y=2009,m=11)
# re_path(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$',views.article_detail)#掺入3个参数; #分发:注意添加上statics,因为app01当前位于statics目录下!!!
re_path(r'^',include("statics.app01.urls")),
#re_path(r'app01/',include("statics.app01.urls")),
#re_path(r'app02/',include("app02.urls")),
] """
一些请求的例子:
articles/2005/03/ 请求将匹配列表中的第三个模式。Django 将调用函数views.month_archive(request, '2005', '03');
/articles/2005/3/ 不匹配任何URL 模式,因为列表中的第三个模式要求月份应该是两个数字;
/articles/2003/ 将匹配列表中的第一个模式不是第二个,因为模式按顺序匹配,第一个会首先测试是否匹配。请像这样自由插入一些特殊的情况来探测匹配的次序;
/articles/2003 不匹配任何一个模式,因为每个模式要求URL 以一个反斜线结尾;
/articles/2003/03/03/ 将匹配最后一个模式。Django 将调用函数views.article_detail(request, '2003', '03', '03');
"""
2、app01下的urls.py;
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/15 18:10 """demo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,re_path from statics.app01 import views urlpatterns = [ #简单的路由配置:路径------>视图函数;从上至下进行判断;
re_path(r'^articles/2003/$',views.special_case_2003),#special_case_2003(request)
re_path(r'^articles/([0-9]{4})/$',views.year_archive),#此处分组之后,相当于传入了两个参数;year_archive(request,2009)
re_path(r'^articles/([0-9]{4})/([0-9]{2})/$',views.month_archive),#此处分组之后,相当于传入了两个参数;month_archive(request,2009,11)
#re_path(r'^articles/(?P<y>[0-9]{4})/(?P<m>[0-9]{2})/$',views.month_archive),#此处分组之后,相当于传入了两个参数;month_archive(request,y=2009,m=11)
re_path(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$',views.article_detail)#掺入3个参数; ] """
一些请求的例子: articles/2005/03/ 请求将匹配列表中的第三个模式。Django 将调用函数views.month_archive(request, '2005', '03');
/articles/2005/3/ 不匹配任何URL 模式,因为列表中的第三个模式要求月份应该是两个数字;
/articles/2003/ 将匹配列表中的第一个模式不是第二个,因为模式按顺序匹配,第一个会首先测试是否匹配。请像这样自由插入一些特殊的情况来探测匹配的次序;
/articles/2003 不匹配任何一个模式,因为每个模式要求URL 以一个反斜线结尾;
/articles/2003/03/03/ 将匹配最后一个模式。Django 将调用函数views.article_detail(request, '2003', '03', '03');
"""
22-路由控制之登录验证示例
1、登录实例验证演示;
urls.py;
"""demo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,re_path,include from statics.app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('timer/', views.timer),
path('login/', views.login), #简单的路由配置:路径------>视图函数;从上至下进行判断;
# re_path(r'^articles/2003/$',views.special_case_2003),#special_case_2003(request)
# re_path(r'^articles/([0-9]{4})/$',views.year_archive),#此处分组之后,相当于传入了两个参数;year_archive(request,2009)
# #re_path(r'^articles/([0-9]{4})/([0-9]{2})/$',views.month_archive),#此处分组之后,相当于传入了两个参数;month_archive(request,2009,11)
# re_path(r'^articles/(?P<y>[0-9]{4})/(?P<m>[0-9]{2})/$',views.month_archive),#此处分组之后,相当于传入了两个参数;month_archive(request,y=2009,m=11)
# re_path(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$',views.article_detail)#掺入3个参数; #分发:注意添加上statics,因为app01当前位于statics目录下!!!
re_path(r'^',include("statics.app01.urls")),
#re_path(r'app01/',include("statics.app01.urls")),
#re_path(r'app02/',include("app02.urls")),
] """
一些请求的例子: articles/2005/03/ 请求将匹配列表中的第三个模式。Django 将调用函数views.month_archive(request, '2005', '03');
/articles/2005/3/ 不匹配任何URL 模式,因为列表中的第三个模式要求月份应该是两个数字;
/articles/2003/ 将匹配列表中的第一个模式不是第二个,因为模式按顺序匹配,第一个会首先测试是否匹配。请像这样自由插入一些特殊的情况来探测匹配的次序;
/articles/2003 不匹配任何一个模式,因为每个模式要求URL 以一个反斜线结尾;
/articles/2003/03/03/ 将匹配最后一个模式。Django 将调用函数views.article_detail(request, '2003', '03', '03');
"""
views.py;
from django.shortcuts import render,HttpResponse # Create your views here. def timer(request):
import time
ctime = time.time() return render(request, "time.html", {"ctime":ctime}) def special_case_2003(request):
return HttpResponse("special_case_2003") def year_archive(request,year):
return HttpResponse(year,"year.....") def month_archive(request,year,month):
#def month_archive(request,y,m):
#def month_archive(request,m,y):
#return HttpResponse(y+"-"+m)
return HttpResponse(year+"-"+month) def article_detail(request,year,month,detail):
return HttpResponse(year+"-"+month+"-"+detail) def login(request):
print(request.method)
if request.method =="GET": return render(request,"login.html")
else:
print(request.GET)
print(request.POST)
user = request.POST.get('user')
pwd = request.POST.get('pwd')
if user =="cui" and pwd =="":
return HttpResponse('登录成功!')
else:
return HttpResponse('用户名或者密码错误!')
23-路由控制之反向解析1
1、起个别名;
urlpatterns = [
path('admin/', admin.site.urls),
path('timer/', views.timer),
# path('login/', views.login),
path('login/', views.login,name = "Log"),#给路径起个别名Log,不管是login.htm还是login或者login.html;
]
2、HTML文件中的{% url "Log" %}用法;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css"> </style>
</head>
<body>
<!--<form action="http://127.0.0.1:8000/login/" method="post">-->
<form action="{% url "Log" %}/" method="post">
用户名2:<input type="text" name="user">
密码2:<input type="password" name="pwd">
<input type="submit"> </form>
</body>
</html>
24-流程控制之反向解析2
1、在urlpatterns中给路由起个别名比如name = "s_c_2003";
urlpatterns = [ #简单的路由配置:路径------>视图函数;从上至下进行判断;
re_path(r'^articles/2003/$',views.special_case_2003,name = "s_c_2003"),#special_case_2003(request)
re_path(r'^articles/([0-9]{4})/$',views.year_archive,name = "y_a"),#此处分组之后,相当于传入了两个参数;year_archive(request,2009)
re_path(r'^articles/([0-9]{4})/([0-9]{2})/$',views.month_archive),#此处分组之后,相当于传入了两个参数;month_archive(request,2009,11)
#re_path(r'^articles/(?P<y>[0-9]{4})/(?P<m>[0-9]{2})/$',views.month_archive),#此处分组之后,相当于传入了两个参数;month_archive(request,y=2009,m=11)
re_path(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$',views.article_detail)#掺入3个参数; ]
2、views.py中重新进行配置,需要导入reverse模块;
from django.shortcuts import render,HttpResponse from django.urls import reverse
# Create your views here. def timer(request):
import time
ctime = time.time()
url = reverse("s_c_2003")
url = reverse("y_a", args=(1993,))#当原有匹配格式中出现正则的时候,需要传入一个与原有格式位数相同的数字;比如1993
print(url)
25-路由控制之名称空间1
1、名称空间的概念初识;
命名空间(英语:Namespace)是表示标识符的可见范围。一个标识符可在多个命名空间中定义,它在不同命名空间中的含义是互不相干的。这样,在一个新的命名空间中可定义任何标识符,它们不会与任何已有的标识符发生冲突,因为已有的定义都处于其它命名空间中。
project的urls.py;
urlpatterns = [
re_path(r'^admin/', admin.site.urls),
re_path(r'^app01/', include("app01.urls",namespace="app01")),
re_path(r'^app02/', include("app02.urls",namespace="app02")),
]
app01.urls;
urlpatterns = [
re_path(r'^index/', index,name="index"),
]
app02.urls;
urlpatterns = [
re_path(r'^index/', index,name="index"),
]
app01.views.py;
from django.shortcuts import render,HttpResponse # Create your views here.
from django.urls import reverse
def index(request):
#return HttpResponse("index1,OK")
return HttpResponse(reverse("app01:index"))
app02.views.py;
from django.shortcuts import render,HttpResponse # Create your views here.
from django.urls import reverse
def index(request):
#return HttpResponse("index2,OK")
return HttpResponse(reverse("app02:index"))
26-路由控制之名称空间2
1、Django2.0的名称空间名称与Django1.0有所不同——以元组的形式进行传值;
re_path(r'^app01/',include(("statics.app01.urls","app01"))),#引入名称空间的概念;
re_path(r'^app02/',include(("statics.app02.urls","app02"))),#引入名称空间的概念;
27-url控制器之path方法
1、基本示例;
from django.urls import path
from . import views
urlpatterns = [
path('articles/2003/', views.special_case_2003),
path('articles/<int:year>/', views.year_archive),
path('articles/<int:year>/<int:month>/', views.month_archive),
path('articles/<int:year>/<int:month>/<slug>/', views.article_detail),
]
- 使用尖括号(<>)从url中取值;
- 捕获值中可以包含一个转化器类型(Content Type),比如<int:year>捕获了一个整数变量;
- 无需添加“前导斜杠”;
2、Path转化器;
Django默认支持5个转化器;
- str,匹配除了路径分隔符(
/
)之外的非空字符串,这是默认的形式; - int,匹配正整数,包含0;
- slug,匹配字母、数字以及横杠、下划线组成的字符串;
- uuid,匹配格式化的uuid,如 075194d3-6885-417e-a8a8-6c931e272f00;
- path,匹配任何非空字符串,包含了路径分隔符;
28-path的自定义转换器
1、path支持自定义转换器;
对于一些复杂或者复用的需要,可以定义自己的转化器,转化器是一个类或接口,它的要求有三点:
regex
类属性,默认规定的名称,不可修改,字符串类型;
to_python(self, value)
方法,value是由类属性regex
所匹配到的字符串,返回具体的Python变量值,以供Django传递到对应的视图函数中;to_url(self, value)
方法,和to_python
相反,value是一个具体的Python变量值,返回其字符串,通常用于url反向引用;
class FourDigitYearConverter:
regex = '[0-9]{4}'
def to_python(self, value):
return int(value)
def to_url(self, value):
return '%04d' % value
2、将register_converter注册到URL配置中;
from django.urls import register_converter, path
from . import converters, views
register_converter(converters.FourDigitYearConverter, 'yyyy')
urlpatterns = [
path('articles/2003/', views.special_case_2003),
path('articles/<yyyy:year>/', views.year_archive),
...
]
29-url控制总结
1、路由控制之简单配置;
2、路由控制之有名分组;
3、路由控制之分发include引入外部文件;
4、路由控制之登录验证;
5、路由控制之反向解析;
6、路由控制之名称空间namespace;
7、路由控制之path;
8、路由控制之自定义转换器;
30-视图层之请求对象
1、Django中视图函数初识;
Django中的视图函数,是一个简单的Python 函数,它接受Web请求并且返回Web响应。响应可以是一张网页的HTML内容,一个重定向,一个404错误,一个XML文档,或者一张图片. . . 是任何东西都可以。无论视图本身包含什么逻辑,都要返回响应,代码写在哪里也无所谓,只要它在我们的Python目录下面,除此之外没有更多的要求了——可以说“没有什么神奇的地方”。为了将代码放在某处,约定是将视图函数放置在项目或应用程序目录中的名为views.py的文件中;
2、request属性;
- HttpRequest.GET;
- HttpRequest.POST;
- HttpRequest.body;
- HttpRequest.path;
- HttpRequest.method;
- HttpRequest.encoding;
- HttpRequest.META;
- HttpRequest.FILES;
- HttpRequest.COOKIES;
- HttpRequest.session;
- HttpRequest.user;
1.HttpRequest.GET 一个类似于字典的对象,包含 HTTP GET 的所有参数,详情请参考 QueryDict 对象; 2.HttpRequest.POST 一个类似于字典的对象,如果请求中包含表单数据,则将这些数据封装成 QueryDict 对象; POST 请求可以带有空的 POST 字典 —— 如果通过 HTTP POST 方法发送一个表单,但是表单中没有任何的数据,QueryDict 对象依然会被创建。
因此,不应该使用 if request.POST 来检查使用的是否是POST 方法;应该使用 if request.method == "POST"
另外:如果使用 POST 上传文件的话,文件信息将包含在 FILES 属性中。 注意:键值对的值是多个的时候,比如checkbox类型的input标签,select标签,需要用:
request.POST.getlist("hobby") 3.HttpRequest.body 一个字符串,代表请求报文的主体。在处理非 HTTP 形式的报文时非常有用,例如:二进制图片、XML,Json等。
但是,如果要处理表单数据的时候,推荐还是使用 HttpRequest.POST 。 4.HttpRequest.path 一个字符串,表示请求的路径组件(不含域名)。
例如:"/music/bands/the_beatles/" 5.HttpRequest.method 一个字符串,表示请求使用的HTTP 方法。必须使用大写。
例如:"GET"、"POST" 6.HttpRequest.encoding 一个字符串,表示提交的数据的编码方式(如果为 None 则表示使用 DEFAULT_CHARSET 的设置,默认为 'utf-8')。
这个属性是可写的,你可以修改它来修改访问表单数据使用的编码。
接下来对属性的任何访问(例如从 GET 或 POST 中读取数据)将使用新的 encoding 值。
如果你知道表单数据的编码不是 DEFAULT_CHARSET ,则使用它。 7.HttpRequest.META 一个标准的Python 字典,包含所有的HTTP 首部。具体的头部信息取决于客户端和服务器,下面是一些示例: CONTENT_LENGTH —— 请求的正文的长度(是一个字符串)。
CONTENT_TYPE —— 请求的正文的MIME 类型。
HTTP_ACCEPT —— 响应可接收的Content-Type。
HTTP_ACCEPT_ENCODING —— 响应可接收的编码。
HTTP_ACCEPT_LANGUAGE —— 响应可接收的语言。
HTTP_HOST —— 客服端发送的HTTP Host 头部。
HTTP_REFERER —— Referring 页面。
HTTP_USER_AGENT —— 客户端的user-agent 字符串。
QUERY_STRING —— 单个字符串形式的查询字符串(未解析过的形式)。
REMOTE_ADDR —— 客户端的IP 地址。
REMOTE_HOST —— 客户端的主机名。
REMOTE_USER —— 服务器认证后的用户。
REQUEST_METHOD —— 一个字符串,例如"GET" 或"POST"。
SERVER_NAME —— 服务器的主机名。
SERVER_PORT —— 服务器的端口(是一个字符串)。
从上面可以看到,除 CONTENT_LENGTH 和 CONTENT_TYPE 之外,请求中的任何 HTTP 首部转换为 META 的键时,
都会将所有字母大写并将连接符替换为下划线最后加上 HTTP_ 前缀。
所以,一个叫做 X-Bender 的头部将转换成 META 中的 HTTP_X_BENDER 键。 8.HttpRequest.FILES 一个类似于字典的对象,包含所有的上传文件信息。
FILES 中的每个键为<input type="file" name="" /> 中的name,值则为对应的数据。
注意,FILES 只有在请求的方法为POST 且提交的<form> 带有enctype="multipart/form-data" 的情况下才会
包含数据。否则,FILES 将为一个空的类似于字典的对象。 9.HttpRequest.COOKIES 一个标准的Python 字典,包含所有的cookie。键和值都为字符串。 10.HttpRequest.session 一个既可读又可写的类似于字典的对象,表示当前的会话。只有当Django 启用会话的支持时才可用。
完整的细节参见会话的文档。 11.HttpRequest.user(用户认证组件下使用) 一个 AUTH_USER_MODEL 类型的对象,表示当前登录的用户。 如果用户当前没有登录,user 将设置为 django.contrib.auth.models.AnonymousUser 的一个实例。你可以通过 is_authenticated() 区分它们。 例如: if request.user.is_authenticated():
# Do something for logged-in users.
else:
# Do something for anonymous users. user 只有当Django 启用 AuthenticationMiddleware 中间件时才可用。 ------------------------------------------------------------------------------------- 匿名用户
class models.AnonymousUser django.contrib.auth.models.AnonymousUser 类实现了django.contrib.auth.models.User 接口,但具有下面几个不同点: id 永远为None。
username 永远为空字符串。
get_username() 永远返回空字符串。
is_staff 和 is_superuser 永远为False。
is_active 永远为 False。
groups 和 user_permissions 永远为空。
is_anonymous() 返回True 而不是False。
is_authenticated() 返回False 而不是True。
set_password()、check_password()、save() 和delete() 引发 NotImplementedError。
New in Django 1.8:
新增 AnonymousUser.get_username() 以更好地模拟 django.contrib.auth.models.User。
3、request的常用方法;
- HttpRequest.get_full_path();
- HttpRequest.is_ajax();
settings.py注释MIDDLEWARE列表中的# 'django.middleware.csrf.CsrfViewMiddleware',
urls.py配置;
views.py;
from django.shortcuts import render,HttpResponse # Create your views here.
""
"""
URL格式:
协议://IP:PORT/a1/b2/?Get请求数据
"""
def index(request):
print("method",request.method)#GET请求;
print(request.GET)#<QueryDict: {'name': ['cuixiaozhao'], 'age': ['26']}>
print(request.POST)#<QueryDict: {'name': ['lijingping'], 'age': ['22']}>
print(request.GET.get("name"))#cuixiaozhao
print(request.POST.get("age"))# print(request.path)#/index/name=cuixiaozhao&age=26 print(request.get_full_path())#/index/name%3Dcuixiaozhao&age%3D26 return render(request,"index.html")
操作日志:
"D:\Program\PyCharm 2018.1.4\bin\runnerw.exe" C:\Users\TQTL911\PycharmProjects\views_demo\venv\Scripts\python.exe C:/Users/TQTL911/PycharmProjects/views_demo/manage.py runserver 8000
Performing system checks... System check identified no issues (0 silenced). You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
August 16, 2018 - 10:55:43
Django version 2.1, using settings 'views_demo.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
method GET
<QueryDict: {}>
<QueryDict: {}>
None
None
/index/name=cuixiaozhao&age=26
/index/name%3Dcuixiaozhao&age%3D26
[16/Aug/2018 10:55:46] "GET /index/name=cuixiaozhao&age=26 HTTP/1.1" 200 326
Not Found: /name=cuixiaozhao&age=26
[16/Aug/2018 10:56:12] "GET /name=cuixiaozhao&age=26 HTTP/1.1" 404 2236
[16/Aug/2018 10:56:19] "GET /index/name=cuixiaozhao&age=26 HTTP/1.1" 200 326
method GET
<QueryDict: {}>
<QueryDict: {}>
None
None
/index/name=cuixiaozhao&age=26
/index/name%3Dcuixiaozhao&age%3D26
[16/Aug/2018 10:57:15] "POST /index/name=cuixiaozhao&age=26 HTTP/1.1" 200 326
method POST
<QueryDict: {}>
<QueryDict: {'name': ['lijingping'], 'age': ['']}>
None
23
/index/name=cuixiaozhao&age=26
/index/name%3Dcuixiaozhao&age%3D26
method GET
[16/Aug/2018 10:57:38] "GET /index/name=cuixiaozhao&age=26 HTTP/1.1" 200 326
<QueryDict: {}>
<QueryDict: {}>
None
None
/index/name=cuixiaozhao&age=26
/index/name%3Dcuixiaozhao&age%3D26
method GET
[16/Aug/2018 10:57:59] "GET /index/name=cuixiaozhao&age=26 HTTP/1.1" 200 326
<QueryDict: {}>
<QueryDict: {}>
None
None
/index/name=cuixiaozhao&age=26
/index/name%3Dcuixiaozhao&age%3D26
[16/Aug/2018 10:58:25] "GET /index/ HTTP/1.1" 200 326
method GET
<QueryDict: {}>
<QueryDict: {}>
None
None
/index/
/index/
[16/Aug/2018 10:58:59] "GET /index/?name=%22cuixiaozhao%22&age=%2226%22 HTTP/1.1" 200 326
method GET
<QueryDict: {'name': ['"cuixiaozhao"'], 'age': ['"26"']}>
<QueryDict: {}>
"cuixiaozhao"
None
/index/
/index/?name=%22cuixiaozhao%22&age=%2226%22
method GET
<QueryDict: {'name': ['cuixiaozhao'], 'age': ['']}>
<QueryDict: {}>
cuixiaozhao
None
/index/
/index/?name=cuixiaozhao&age=26
[16/Aug/2018 10:59:20] "GET /index/?name=cuixiaozhao&age=26 HTTP/1.1" 200 326
Performing system checks... System check identified no issues (0 silenced). You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
August 16, 2018 - 10:59:53
Django version 2.1, using settings 'views_demo.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
31-视图响应对象
1、HttpResponse对象的三种主要形式;
- HttpResponse();
- render();
- redirect();
2、render()方法,因为html文件中引用了{{ctime}}属性;
from django.shortcuts import render,HttpResponse # Create your views here.
""
"""
URL格式:
协议://IP:PORT/a1/b2/?Get请求数据;
"""
def index(request):
print("method",request.method)#GET请求;
print(request.GET)#<QueryDict: {'name': ['cuixiaozhao'], 'age': ['26']}>
print(request.POST)#<QueryDict: {'name': ['lijingping'], 'age': ['22']}>
print(request.GET.get("name"))#cuixiaozhao
print(request.POST.get("age"))# print(request.path)#/index/name=cuixiaozhao&age=26 print(request.get_full_path())#/index/name%3Dcuixiaozhao&age%3D26 #return HttpResponse("cuixiaozhao ") import time
ctime = time.time() #return HttpResponse("<h1>lijingping</h1> ")
return render(request,"index.html",{"ctime":ctime})#本质同上,return HttpResponse("xxxx")
"""
带有{{}}的HTML文件在Django中称之为template模板文件;
"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css"> </style>
</head>
<body>
<form action="" method="post">
姓名:<input type="text" name="name">
年龄:<input type="text" name="age">
<input type="submit"></input>
</form>
<p>{{ ctime }}</p>
</body>
</html>
32-模版语法之变量
1、Django中的模板语言的深度查询;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css"> </style>
</head>
<body>
<h1>index</h1>
<p>{{ name }}</p>
<p>{{ num }}</p>
<p>{{ info }}</p>
<p>{{ cxz }}</p>
<p>{{ ljp }}</p>
<p>{{ person_list }}</p>
<p>{{ bool }}</p>
<p>{{ list_num }}</p>
<hr>
深度查询
<p>{{ list_num.1 }}</p>
<p>{{ info.name }}</p>
</body>
</html>
2、locals()方法的引入;
from django.shortcuts import render # Create your views here.
def index(request):
"""
模板语法只有两种:
1、渲染变量{{ name }}
2、渲染标签{% age % }
:param request:
:return:
"""
name = "cuixiaozhao"
num = 10
list_num = [1,2,3,4]
info = {"name":"cuixiaozhao","age":26}
bool = True
class Person(object):
def __init__(self,name,age):
self.name = name
self.age = age cxz = Person("崔晓昭",26)
ljp = Person("李静瓶",22)
person_list = [cxz,ljp]
#return render(request,"index.html",{"name":name})
return render(request,"index.html",locals())
33-过滤器
1、Django中的模板过滤器初识;
语法:{{object|fileter_name:param}};算了,我还是说人话吧:{{对象|过滤器的名称:属性值}}
- default;
- length;
- filesizeformat;
- date;
- slice;
- truncatechars;
- safe;
Django的模板中会对HTML标签和JS等语法标签进行自动转义,原因显而易见,这样是为了安全。但是有的时候我们可能不希望这些HTML元素被转义,比如我们做一个内容管理系统,后台添加的文章中是经过修饰的,这些修饰可能是通过一个类似于FCKeditor编辑加注了HTML修饰符的文本,如果自动转义的话显示的就是保护HTML标签的源文件。为了在Django中关闭HTML的自动转义有两种方式,如果是一个单独的变量我们可以通过过滤器“|safe”的方式告诉Django这段代码是安全的不必转义。比如:
- truncatewords
from django.shortcuts import render # Create your views here.
def index(request):
"""
模板语法只有两种:
1、渲染变量{{ name }}
2、渲染标签{% age % }
:param request:
:return:
"""
name = "cuixiaozhao"
num = 10
list_num = [1,2,3,4]
info = {"name":"cuixiaozhao","age":26}
bool = True
class Person(object):
def __init__(self,name,age):
self.name = name
self.age = age cxz = Person("崔晓昭",26)
ljp = Person("李静瓶",22)
person_list = [cxz,ljp]
#person_list = []
#return render(request,"index.html",{"name":name})
import datetime
now = datetime.datetime.now()
file_size = 123456
text = "Hello Python hi LuffyCity Go Java Linux"
link = "<a href ="" >link</a>"#Django自行做转义,为了安全; ###############过滤器 return render(request,"index.html",locals())
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css"> </style>
</head>
<body>
<h1>index</h1>
<p>{{ name }}</p>
<p>{{ num }}</p>
<p>{{ info }}</p>
<p>{{ cxz }}</p>
<p>{{ ljp }}</p>
<p>{{ person_list }}</p>
<p>{{ bool }}</p>
<p>{{ list_num }}</p>
<hr>
深度查询
<p>{{ list_num.1 }}</p>
<p>{{ info.name }}</p>
<h3>Django内置的过滤器初识</h3>
<p>{{ now|date }}</p>
<p>{{ now|date:"Y-m-d" }}</p>
<p>{{ person_list|default:"数据此刻为空" }}</p>
<p>{{ file_size|filesizeformat }}</p>
<p>{{ text|truncatechars:9 }}</p>
<p>{{ text|truncatewords:3 }}</p>
<p>{{ link|safe }}</p>
<p>{{list_num.0|add:100 }}</p>
<p>{{ info.name|upper}}</p>
</body>
</html>
34-模版语法之标签
1、Django模板之标签初识;
- for标签;
- for...empty标签;
- if标签;
- with标签;
- crsf_token(这个标签用于跨站请求伪造保护);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css"> </style>
</head>
<body>
<h1>index</h1>
<p>{{ name }}</p>
<p>{{ num }}</p>
<p>{{ info }}</p>
<p>{{ cxz }}</p>
<p>{{ ljp }}</p>
<p>{{ person_list }}</p>
<p>{{ bool }}</p>
<p>{{ list_num }}</p>
<hr>
深度查询
<p>{{ list_num.1 }}</p>
<p>{{ info.name }}</p>
<hr>
<h3>Django内置的过滤器初识</h3>
<p>{{ now|date }}</p>
<p>{{ now|date:"Y-m-d" }}</p>
<p>{{ person_list|default:"数据此刻为空" }}</p>
<p>{{ file_size|filesizeformat }}</p>
<p>{{ text|truncatechars:9 }}</p>
<p>{{ text|truncatewords:3 }}</p>
<p>{{ link|safe }}</p>
<p>{{list_num.0|add:100 }}</p>
<p>{{ info.name|upper}}</p>
<hr>
<h4>for标签</h4>
{% for i in list_num %}
<p>{{ i }}</p>
{% endfor %} {% for keys in info %}
<p>{{ keys }}</p>
{% endfor %} {% for foo in person_list %}
{# <p>{{ forloop.counter }} {{ foo.name }},{{ foo.age }}</p>#}
<p>{{ forloop.counter0 }} {{ foo.name }},{{ foo.age }}</p>
{% endfor %} {% for foo in class_list %}
<p>{{ forloop.counter0 }} {{ foo.name }},{{ foo.age }}</p>
{% empty %}
<p>列表为空</p>
{% endfor %}
<hr>
{% if user %}
<p>
<a href="">Hi {{ user }},欢迎登录!</a>
<a href="">注销登录</a>
</p>
{% else %}
<p>
<a href="">登录</a>
<a href="">注册</a>
</p>
{% endif %}
<hr>
{% with person_list.1.name as N %}
{{ N }}
{% endwith %}
<hr> </body>
</html>
2、{% csrf_token %}的引入;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css"> </style>
</head>
<body> <form action="" method="post">
{% csrf_token %}
<input type="text" name="user">
<input type="submit">
</form>
</body>
</html>
35-模版语法之自定义标签与过滤器
1、Django中自定义标签与过滤器的N大步骤;
1、在settings中的INSTALLED_APPS配置当前app的名称如app01(注意不能存在重名),不然django无法找到自定义的simple_tag;
2、在app中创建templatetags包(即包含__init__.py文件,包名只能是templatetags);
3、创建任意 .py 文件,如:my_tag_filter.py;
- 4、在使用自定义simple_tag和filter的html文件中导入之前创建的 my_tag_filter.py;
- 5、使用simple_tag和filter(如何调用);
my_tag_filter.py;
#导入;
from django import template #register变量名是固定的,不用是他其他;
register = template.Library() @register.filter
def multi_filter(x,y):
return x * y @register.simple_tag()
def multi_tag(m,n,z):
return m*n*z
2、Django中过滤器与自定义标签的使用场景与区别;
1)过滤器只能接收2个参数;
2)自定义标签可以接收多个参数;
3)过滤器可以进行if判断,但是自定义标签不可以;
{% if num|multi_filter:30 > 100 %}
{{ num|multi_filter:30 }}
{% endif %}
36-模版语法之继承
1、Django模板之继承;
Django模版引擎中最强大也是最复杂的部分就是模版继承了。模版继承可以让我们创建一个基本的“骨架”模版,它包含我们站点中的全部元素,并且可以定义能够被子模版覆盖的 blocks ;
base.html;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
{% block title %} {% endblock %}
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<style type="text/css">
*{
padding: 0;
margin: 0;
}
.header{
width: 100%;
height: 50px;
background-color: green;
}
</style>
</head>
<body>
<div class="header">
<div class="row">
<div class="col-md-3">
{% include 'advertise.html' %}
</div>
<div class="col-md-9">
{% block con %}
<h1>content</h1>
{% endblock %}
</div>
</div>
</div>
<div class="container"></div> </body>
</html>
orders.html;
{% extends 'base.html' %} {% block title %}
<title>orders</title>
{% endblock %} {% block con %}
{{ block.super }}
<h4>订单</h4>
{% endblock con %}
index.html;
{% extends 'base.html' %} {% block title %}
<title>index</title>
{% endblock %}
{% block con %}
<h1>index</h1>
<p>{{ name }}</p>
<p>{{ num }}</p>
<p>{{ info }}</p>
<p>{{ cxz }}</p>
<p>{{ ljp }}</p>
<p>{{ person_list }}</p>
<p>{{ bool }}</p>
<p>{{ list_num }}</p>
<hr>
深度查询
<p>{{ list_num.1 }}</p>
<p>{{ info.name }}</p>
<hr>
<h3>Django内置的过滤器初识</h3>
<p>{{ now|date }}</p>
<p>{{ now|date:"Y-m-d" }}</p>
<p>{{ person_list|default:"数据此刻为空" }}</p>
<p>{{ file_size|filesizeformat }}</p>
<p>{{ text|truncatechars:9 }}</p>
<p>{{ text|truncatewords:3 }}</p>
<p>{{ link|safe }}</p>
<p>{{list_num.0|add:100 }}</p>
<p>{{ info.name|upper}}</p>
<hr>
<h4>for标签</h4>
{% for i in list_num %}
<p>{{ i }}</ p>
{% endfor %} {% for keys in info %}
<p>{{ keys }}</p>
{% endfor %} {% for foo in person_list %}
<!-- <p>{{ forloop.counter }} {{ foo.name }},{{ foo.age }}</p>-->
<p>{{ forloop.counter0 }} {{ foo.name }},{{ foo.age }}</p>
{% endfor %} {% for foo in class_list %}
<p>{{ forloop.counter0 }} {{ foo.name }},{{ foo.age }}</p>
{% empty %}
<p>列表为空</p>
{% endfor %}
<hr>
{% if user %}
<p>
<a href="">Hi {{ user }},欢迎登录!</a>
<a href="">注销登录</a>
</p>
{% else %}
<p>
<a href="">登录</a>
<a href="">注册</a>
</p>
{% endif %}
<hr>
{% with person_list.1.name as N %}
{{ N }}
{% endwith %}
<hr> <hr>
<h4>Django中的自定义过滤器、标签</h4>
{% load my_tag_filter %}
<p>{{ list_num|multi_filter:20 }}</p>
<p>{% multi_tag 7 9 11 %}</p>
{% endblock %}
2、Django模板继承的启示;
这里是使用继承的一些提示:
如果我们在模版中使用
{% extends %}
标签,它必须是模版中的第一个标签。其他的任何情况下,模版继承都将无法工作;在base模版中设置越多的
{% block %}
标签越好。请记住,子模版不必定义全部父模版中的blocks,所以,我们可以在大多数blocks中填充合理的默认内容,然后,只定义我们需要的那一个,多一点钩子总比少一点好;如果发现我们自己在大量的模版中复制内容,那可能意味着我们应该把内容移动到父模版中的一个
{% block %}
中;If you need to get the content of the block from the parent template, the
{{ block.super }}
variable will do the trick. This is useful if you want to add to the contents of a parent block instead of completely overriding it. Data inserted using{{ block.super }}
will not be automatically escaped (see the next section), since it was already escaped, if necessary, in the parent template;为了更好的可读性,我们也可以给你的
{% endblock %}
标签一个 名字 。例如:
37-ORM简介
1、Django中的ORM简介;
MVC或者MVC框架中包括一个重要的部分,就是ORM,它实现了数据模型与数据库的解耦,即数据模型的设计不需要依赖于特定的数据库,通过简单的配置就可以轻松更换数据库,这极大的减轻了开发人员的工作量,不需要面对因数据库变更而导致的无效劳动;
ORM(Object Relational Mapping)是“对象-关系-映射”的简称;
2、SQL中的表;
#sql中的表; #创建表:
CREATE TABLE employee(
id INT PRIMARY KEY auto_increment ,
name VARCHAR (20),
gender BIT default 1,
birthday DATE ,
department VARCHAR (20),
salary DECIMAL (8,2) unsigned
); #sql中的表纪录
#添加一条表纪录:
INSERT employee (name,gender,birthday,salary,department)
VALUES ("alex",1,"1985-12-12",8000,"保洁部");
#查询一条表纪录:
SELECT * FROM employee WHERE age=24;
#更新一条表纪录:
UPDATE employee SET birthday="1989-10-24" WHERE id=1;
#删除一条表纪录:
DELETE FROM employee WHERE name="alex";
3、Python中的类;
#python的类
class Employee(models.Model):
id=models.AutoField(primary_key=True)
name=models.CharField(max_length=32)
gender=models.BooleanField()
birthday=models.DateField()
department=models.CharField(max_length=32)
salary=models.DecimalField(max_digits=8,decimal_places=2)
#python的类对象
#添加一条表纪录:
emp=Employee(name="alex",gender=True,birthday="1985-12-12",epartment="保洁部")
emp.save()
#查询一条表纪录:
Employee.objects.filter(age=24)
#更新一条表纪录:
Employee.objects.filter(id=1).update(birthday="1989-10-24")
#删除一条表纪录:
Employee.objects.filter(name="alex").delete()
38-单表操作之生成表模型
1、单表操作的N个主要步骤;
1)创建模型;
from django.db import models # Create your models here.
class Book(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=32,unique=True)
pub_date = models.DateField()
price = models.DecimalField(max_digits=8,decimal_places=2)#999999.99
publish = models.CharField(max_length=22)
2)settings.py文件中的数据库(提前创建数据库实例orm)连接信息配置(先注释默认sqllite3的数据连接信息配置);
settings.py;
"""
Django settings for ORM project. Generated by 'django-admin startproject' using Django 2.1. For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
""" import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '0uw!%id+y+xv=dm@0v+d(tf-#r!_zm1&ymtb$f2mi$5*6$5a&j' # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01.apps.App01Config',
] MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
] ROOT_URLCONF = 'ORM.urls' TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
] WSGI_APPLICATION = 'ORM.wsgi.application' # Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases # DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
# }
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',#数据库的引擎为MySQL;
'NAME': 'orm',#要连接的数据库实例的名称,连接前需要已经完成创建;
'USER': 'root',#MySQL数据库的用户名;
'PASSWORD': 'Tqtl911!@%*123)',#MySQL数据库的密码;
'HOST': '147.195.221.254',#MySQL数据库服务器的IP地址;
'PORT': '3306'#MySQL数据库的款口号,默认3306;
}
} # Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
] # Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console':{
'level':'DEBUG',
'class':'logging.StreamHandler',
},
},
'loggers': {
'django.db.backends': {
'handlers': ['console'],
'propagate': True,
'level':'DEBUG',
},
}
}
3)项目中pip安装第三方模块pymysql;
pip3 install pymysql
4)在项目的根目录中的__init__.py文件中导入两条记录;
import pymysql
pymysql.install_as_MySQLdb()
5 )Django2.0版本,注释base.py中的内容;
路径参考:C:\Users\TQTL911\PycharmProjects\ORM\venv\Lib\site-packages\django\db\backends\mysql\base.py;
if version < (1, 3, 7):
raise ImproperlyConfigured('mysqlclient 1.3.7 or newer is required; you have %s.' % Database.__version__)
"""
MySQL database backend for Django. Requires mysqlclient: https://pypi.org/project/mysqlclient/
"""
import re from django.core.exceptions import ImproperlyConfigured
from django.db import utils
from django.db.backends import utils as backend_utils
from django.db.backends.base.base import BaseDatabaseWrapper
from django.utils.functional import cached_property try:
import MySQLdb as Database
except ImportError as err:
raise ImproperlyConfigured(
'Error loading MySQLdb module.\n'
'Did you install mysqlclient?'
) from err from MySQLdb.constants import CLIENT, FIELD_TYPE # isort:skip
from MySQLdb.converters import conversions # isort:skip # Some of these import MySQLdb, so import them after checking if it's installed.
from .client import DatabaseClient # isort:skip
from .creation import DatabaseCreation # isort:skip
from .features import DatabaseFeatures # isort:skip
from .introspection import DatabaseIntrospection # isort:skip
from .operations import DatabaseOperations # isort:skip
from .schema import DatabaseSchemaEditor # isort:skip
from .validation import DatabaseValidation # isort:skip version = Database.version_info
#if version < (1, 3, 7):
# raise ImproperlyConfigured('mysqlclient 1.3.7 or newer is required; you have %s.' % #Database.__version__) # MySQLdb returns TIME columns as timedelta -- they are more like timedelta in
# terms of actual behavior as they are signed and include days -- and Django
# expects time.
django_conversions = {
**conversions,
**{FIELD_TYPE.TIME: backend_utils.typecast_time},
} # This should match the numerical portion of the version numbers (we can treat
# versions like 5.0.24 and 5.0.24a as the same).
server_version_re = re.compile(r'(\d{1,2})\.(\d{1,2})\.(\d{1,2})') class CursorWrapper:
"""
A thin wrapper around MySQLdb's normal cursor class that catches particular
exception instances and reraises them with the correct types. Implemented as a wrapper, rather than a subclass, so that it isn't stuck
to the particular underlying representation returned by Connection.cursor().
"""
codes_for_integrityerror = (
1048, # Column cannot be null
1690, # BIGINT UNSIGNED value is out of range
) def __init__(self, cursor):
self.cursor = cursor def execute(self, query, args=None):
try:
# args is None means no string interpolation
return self.cursor.execute(query, args)
except Database.OperationalError as e:
# Map some error codes to IntegrityError, since they seem to be
# misclassified and Django would prefer the more logical place.
if e.args[0] in self.codes_for_integrityerror:
raise utils.IntegrityError(*tuple(e.args))
raise def executemany(self, query, args):
try:
return self.cursor.executemany(query, args)
except Database.OperationalError as e:
# Map some error codes to IntegrityError, since they seem to be
# misclassified and Django would prefer the more logical place.
if e.args[0] in self.codes_for_integrityerror:
raise utils.IntegrityError(*tuple(e.args))
raise def __getattr__(self, attr):
return getattr(self.cursor, attr) def __iter__(self):
return iter(self.cursor) class DatabaseWrapper(BaseDatabaseWrapper):
vendor = 'mysql'
display_name = 'MySQL'
# This dictionary maps Field objects to their associated MySQL column
# types, as strings. Column-type strings can contain format strings; they'll
# be interpolated against the values of Field.__dict__ before being output.
# If a column type is set to None, it won't be included in the output.
data_types = {
'AutoField': 'integer AUTO_INCREMENT',
'BigAutoField': 'bigint AUTO_INCREMENT',
'BinaryField': 'longblob',
'BooleanField': 'bool',
'CharField': 'varchar(%(max_length)s)',
'DateField': 'date',
'DateTimeField': 'datetime(6)',
'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
'DurationField': 'bigint',
'FileField': 'varchar(%(max_length)s)',
'FilePathField': 'varchar(%(max_length)s)',
'FloatField': 'double precision',
'IntegerField': 'integer',
'BigIntegerField': 'bigint',
'IPAddressField': 'char(15)',
'GenericIPAddressField': 'char(39)',
'NullBooleanField': 'bool',
'OneToOneField': 'integer',
'PositiveIntegerField': 'integer UNSIGNED',
'PositiveSmallIntegerField': 'smallint UNSIGNED',
'SlugField': 'varchar(%(max_length)s)',
'SmallIntegerField': 'smallint',
'TextField': 'longtext',
'TimeField': 'time(6)',
'UUIDField': 'char(32)',
} # For these columns, MySQL doesn't:
# - accept default values and implicitly treats these columns as nullable
# - support a database index
_limited_data_types = (
'tinyblob', 'blob', 'mediumblob', 'longblob', 'tinytext', 'text',
'mediumtext', 'longtext', 'json',
) operators = {
'exact': '= %s',
'iexact': 'LIKE %s',
'contains': 'LIKE BINARY %s',
'icontains': 'LIKE %s',
'gt': '> %s',
'gte': '>= %s',
'lt': '< %s',
'lte': '<= %s',
'startswith': 'LIKE BINARY %s',
'endswith': 'LIKE BINARY %s',
'istartswith': 'LIKE %s',
'iendswith': 'LIKE %s',
} # The patterns below are used to generate SQL pattern lookup clauses when
# the right-hand side of the lookup isn't a raw string (it might be an expression
# or the result of a bilateral transformation).
# In those cases, special characters for LIKE operators (e.g. \, *, _) should be
# escaped on database side.
#
# Note: we use str.format() here for readability as '%' is used as a wildcard for
# the LIKE operator.
pattern_esc = r"REPLACE(REPLACE(REPLACE({}, '\\', '\\\\'), '%%', '\%%'), '_', '\_')"
pattern_ops = {
'contains': "LIKE BINARY CONCAT('%%', {}, '%%')",
'icontains': "LIKE CONCAT('%%', {}, '%%')",
'startswith': "LIKE BINARY CONCAT({}, '%%')",
'istartswith': "LIKE CONCAT({}, '%%')",
'endswith': "LIKE BINARY CONCAT('%%', {})",
'iendswith': "LIKE CONCAT('%%', {})",
} isolation_levels = {
'read uncommitted',
'read committed',
'repeatable read',
'serializable',
} Database = Database
SchemaEditorClass = DatabaseSchemaEditor
# Classes instantiated in __init__().
client_class = DatabaseClient
creation_class = DatabaseCreation
features_class = DatabaseFeatures
introspection_class = DatabaseIntrospection
ops_class = DatabaseOperations
validation_class = DatabaseValidation def get_connection_params(self):
kwargs = {
'conv': django_conversions,
'charset': 'utf8',
}
settings_dict = self.settings_dict
if settings_dict['USER']:
kwargs['user'] = settings_dict['USER']
if settings_dict['NAME']:
kwargs['db'] = settings_dict['NAME']
if settings_dict['PASSWORD']:
kwargs['passwd'] = settings_dict['PASSWORD']
if settings_dict['HOST'].startswith('/'):
kwargs['unix_socket'] = settings_dict['HOST']
elif settings_dict['HOST']:
kwargs['host'] = settings_dict['HOST']
if settings_dict['PORT']:
kwargs['port'] = int(settings_dict['PORT'])
# We need the number of potentially affected rows after an
# "UPDATE", not the number of changed rows.
kwargs['client_flag'] = CLIENT.FOUND_ROWS
# Validate the transaction isolation level, if specified.
options = settings_dict['OPTIONS'].copy()
isolation_level = options.pop('isolation_level', 'read committed')
if isolation_level:
isolation_level = isolation_level.lower()
if isolation_level not in self.isolation_levels:
raise ImproperlyConfigured(
"Invalid transaction isolation level '%s' specified.\n"
"Use one of %s, or None." % (
isolation_level,
', '.join("'%s'" % s for s in sorted(self.isolation_levels))
))
self.isolation_level = isolation_level
kwargs.update(options)
return kwargs def get_new_connection(self, conn_params):
return Database.connect(**conn_params) def init_connection_state(self):
assignments = []
if self.features.is_sql_auto_is_null_enabled:
# SQL_AUTO_IS_NULL controls whether an AUTO_INCREMENT column on
# a recently inserted row will return when the field is tested
# for NULL. Disabling this brings this aspect of MySQL in line
# with SQL standards.
assignments.append('SET SQL_AUTO_IS_NULL = 0') if self.isolation_level:
assignments.append('SET SESSION TRANSACTION ISOLATION LEVEL %s' % self.isolation_level.upper()) if assignments:
with self.cursor() as cursor:
cursor.execute('; '.join(assignments)) def create_cursor(self, name=None):
cursor = self.connection.cursor()
return CursorWrapper(cursor) def _rollback(self):
try:
BaseDatabaseWrapper._rollback(self)
except Database.NotSupportedError:
pass def _set_autocommit(self, autocommit):
with self.wrap_database_errors:
self.connection.autocommit(autocommit) def disable_constraint_checking(self):
"""
Disable foreign key checks, primarily for use in adding rows with
forward references. Always return True to indicate constraint checks
need to be re-enabled.
"""
self.cursor().execute('SET foreign_key_checks=0')
return True def enable_constraint_checking(self):
"""
Re-enable foreign key checks after they have been disabled.
"""
# Override needs_rollback in case constraint_checks_disabled is
# nested inside transaction.atomic.
self.needs_rollback, needs_rollback = False, self.needs_rollback
try:
self.cursor().execute('SET foreign_key_checks=1')
finally:
self.needs_rollback = needs_rollback def check_constraints(self, table_names=None):
"""
Check each table name in `table_names` for rows with invalid foreign
key references. This method is intended to be used in conjunction with
`disable_constraint_checking()` and `enable_constraint_checking()`, to
determine if rows with invalid references were entered while constraint
checks were off.
"""
with self.cursor() as cursor:
if table_names is None:
table_names = self.introspection.table_names(cursor)
for table_name in table_names:
primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name)
if not primary_key_column_name:
continue
key_columns = self.introspection.get_key_columns(cursor, table_name)
for column_name, referenced_table_name, referenced_column_name in key_columns:
cursor.execute(
"""
SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING
LEFT JOIN `%s` as REFERRED
ON (REFERRING.`%s` = REFERRED.`%s`)
WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL
""" % (
primary_key_column_name, column_name, table_name,
referenced_table_name, column_name, referenced_column_name,
column_name, referenced_column_name,
)
)
for bad_row in cursor.fetchall():
raise utils.IntegrityError(
"The row in table '%s' with primary key '%s' has an invalid "
"foreign key: %s.%s contains a value '%s' that does not "
"have a corresponding value in %s.%s."
% (
table_name, bad_row[0], table_name, column_name,
bad_row[1], referenced_table_name, referenced_column_name,
)
) def is_usable(self):
try:
self.connection.ping()
except Database.Error:
return False
else:
return True @cached_property
def mysql_server_info(self):
with self.temporary_connection() as cursor:
cursor.execute('SELECT VERSION()')
return cursor.fetchone()[0] @cached_property
def mysql_version(self):
match = server_version_re.match(self.mysql_server_info)
if not match:
raise Exception('Unable to determine MySQL version from version string %r' % self.mysql_server_info)
return tuple(int(x) for x in match.groups()) @cached_property
def mysql_is_mariadb(self):
# MariaDB isn't officially supported.
return 'mariadb' in self.mysql_server_info.lower()
base.py
6)确保配置文件中的INSTALLED_APPS中写入我们创建的app名称-app01;
7) 通过两条数据库迁移命令即可在指定的数据库中创建表;
python manage.py makemigrations
python manage.py migrate
8)检查数据表是否创建成功;
操作日志:
Microsoft Windows [版本 10.0.17134.1]
(c) 2018 Microsoft Corporation。保留所有权利。 (venv) C:\Users\TQTL911\PycharmProjects\ORM>python manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\management\__init__.py", line 224, in fetch_command
klass = load_command_class(app_name, subcommand)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\management\__init__.py", line 36, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 12, in <module>
from django.db.migrations.autodetector import MigrationAutodetector
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\migrations\autodetector.py", line 11, in <module>
from django.db.migrations.questioner import MigrationQuestioner
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\migrations\questioner.py", line 9, in <module>
from .loader import MigrationLoader
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\migrations\loader.py", line 8, in <module>
from django.db.migrations.recorder import MigrationRecorder
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\migrations\recorder.py", line 9, in <module>
class MigrationRecorder:
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\migrations\recorder.py", line 22, in MigrationRecorder
class Migration(models.Model):
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\base.py", line 87, in __new__
app_config = apps.get_containing_app_config(module)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\apps\registry.py", line 249, in get_containing_app_config
self.check_apps_ready()
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\apps\registry.py", line 131, in check_apps_ready
settings.INSTALLED_APPS
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\conf\__init__.py", line 57, in __getattr__
self._setup(name)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\conf\__init__.py", line 44, in _setup
self._wrapped = Settings(settings_module)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\conf\__init__.py", line 107, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "C:\Users\TQTL911\PycharmProjects\ORM\ORM\__init__.py", line 1, in <module>
import pymysql
ModuleNotFoundError: No module named 'pymysql' (venv) C:\Users\TQTL911\PycharmProjects\ORM>pip show pymysql
You are using pip version 10.0.1, however version 18.0 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command. (venv) C:\Users\TQTL911\PycharmProjects\ORM>pip3 install pymysql
Collecting pymysql
Using cached https://files.pythonhosted.org/packages/a7/7d/682c4a7da195a678047c8f1c51bb7682aaedee1dca7547883c3993ca9282/PyMySQL-0.9.2-py2.py3-none-any.whl
Collecting cryptography (from pymysql)
Using cached https://files.pythonhosted.org/packages/f1/01/a144ec664d3f9ae5837bd72c4d11bdd2d8d403318898e4092457e8af9272/cryptography-2.3.1-cp36-cp36m-win_amd64.whl
Collecting asn1crypto>=0.21.0 (from cryptography->pymysql)
Using cached https://files.pythonhosted.org/packages/ea/cd/35485615f45f30a510576f1a56d1e0a7ad7bd8ab5ed7cdc600ef7cd06222/asn1crypto-0.24.0-py2.py3-none-any.whl
Collecting idna>=2.1 (from cryptography->pymysql)
Using cached https://files.pythonhosted.org/packages/4b/2a/0276479a4b3caeb8a8c1af2f8e4355746a97fab05a372e4a2c6a6b876165/idna-2.7-py2.py3-none-any.whl
Collecting cffi!=1.11.3,>=1.7 (from cryptography->pymysql)
Using cached https://files.pythonhosted.org/packages/2f/85/a9184548ad4261916d08a50d9e272bf6f93c54f3735878fbfc9335efd94b/cffi-1.11.5-cp36-cp36m-win_amd64.whl
Collecting six>=1.4.1 (from cryptography->pymysql)
Using cached https://files.pythonhosted.org/packages/67/4b/141a581104b1f6397bfa78ac9d43d8ad29a7ca43ea90a2d863fe3056e86a/six-1.11.0-py2.py3-none-any.whl
Collecting pycparser (from cffi!=1.11.3,>=1.7->cryptography->pymysql)
Using cached https://files.pythonhosted.org/packages/8c/2d/aad7f16146f4197a11f8e91fb81df177adcc2073d36a17b1491fd09df6ed/pycparser-2.18.tar.gz
Installing collected packages: asn1crypto, idna, pycparser, cffi, six, cryptography, pymysql
Running setup.py install for pycparser ... done
Successfully installed asn1crypto-0.24.0 cffi-1.11.5 cryptography-2.3.1 idna-2.7 pycparser-2.18 pymysql-0.9.2 six-1.11.0
You are using pip version 10.0.1, however version 18.0 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command. (venv) C:\Users\TQTL911\PycharmProjects\ORM>python manage.py makemigrations
(0.011) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.011) SHOW FULL TABLES; args=None
No changes detected (venv) C:\Users\TQTL911\PycharmProjects\ORM>python manage.py migrate
(0.012) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.332) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.017) SELECT @@sql_mode; args=None
(0.015) SHOW FULL TABLES; args=None
(0.013) SHOW FULL TABLES; args=None
Operations to perform:
Apply all migrations: admin, app01, auth, contenttypes, sessions
Running migrations:
(0.018) SHOW FULL TABLES; args=None
CREATE TABLE `django_migrations` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `app` varchar(255) NOT NULL, `name` varchar(255) NOT NULL, `applied` datetime(6) NOT NULL); (params None)
(0.215) CREATE TABLE `django_migrations` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `app` varchar(255) NOT NULL, `name` varchar(255) NOT NULL, `applied` datetime(6) NOT NULL); args=None
(0.366) SELECT engine FROM information_schema.tables WHERE table_name = 'django_migrations'; args=['django_migrations']
(0.310) SELECT engine FROM information_schema.tables WHERE table_name = 'django_migrations'; args=['django_migrations']
(0.156) SELECT engine FROM information_schema.tables WHERE table_name = 'django_migrations'; args=['django_migrations']
(0.158) SELECT engine FROM information_schema.tables WHERE table_name = 'django_migrations'; args=['django_migrations']
CREATE TABLE `django_content_type` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(100) NOT NULL, `app_label` varchar(100) NOT NULL, `model` varchar(100) NOT NULL); (params None)
(0.170) CREATE TABLE `django_content_type` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(100) NOT NULL, `app_label` varchar(100) NOT NULL, `model` varchar(100) NOT NULL); args=None
(0.263) SELECT engine FROM information_schema.tables WHERE table_name = 'django_content_type'; args=['django_content_type']
(0.222) SELECT engine FROM information_schema.tables WHERE table_name = 'django_content_type'; args=['django_content_type']
(0.220) SELECT engine FROM information_schema.tables WHERE table_name = 'django_content_type'; args=['django_content_type']
(0.176) SELECT engine FROM information_schema.tables WHERE table_name = 'django_content_type'; args=['django_content_type']
ALTER TABLE `django_content_type` ADD CONSTRAINT django_content_type_app_label_model_76bd3d3b_uniq UNIQUE (`app_label`, `model`); (params ())
(0.234) ALTER TABLE `django_content_type` ADD CONSTRAINT django_content_type_app_label_model_76bd3d3b_uniq UNIQUE (`app_label`, `model`); args=()
(0.012) SHOW FULL TABLES; args=None
(0.158) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('contenttypes', '0001_initial', '2018-08-16 15:08:06.854620'); args=['contenttypes', '0001_initial', '2018-08-16 15:08:06.854620']
Applying contenttypes.0001_initial... OK
CREATE TABLE `auth_permission` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(50) NOT NULL, `content_type_id` integer NOT NULL, `codename` varchar(100) NOT NULL); (params None)
(0.122) CREATE TABLE `auth_permission` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(50) NOT NULL, `content_type_id` integer NOT NULL, `codename` varchar(100) NOT NULL); args=None
(0.073) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_permission'; args=['auth_permission']
(0.178) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_permission'; args=['auth_permission']
(0.161) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_permission'; args=['auth_permission']
(0.162) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_permission'; args=['auth_permission']
CREATE TABLE `auth_group` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(80) NOT NULL UNIQUE); (params None)
(0.175) CREATE TABLE `auth_group` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(80) NOT NULL UNIQUE); args=None
(0.169) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_group'; args=['auth_group']
(0.147) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_group'; args=['auth_group']
CREATE TABLE `auth_group_permissions` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `group_id` integer NOT NULL, `permission_id` integer NOT NULL); (params None)
(0.215) CREATE TABLE `auth_group_permissions` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `group_id` integer NOT NULL, `permission_id` integer NOT NULL); args=None
(0.111) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_group_permissions'; args=['auth_group_permissions']
(0.102) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_group_permissions'; args=['auth_group_permissions']
(0.146) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_group_permissions'; args=['auth_group_permissions']
CREATE TABLE `auth_user` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `password` varchar(128) NOT NULL, `last_login` datetime(6) NOT NULL, `is_superuser` bool NOT NULL, `username` varchar(30) NOT NULL
UNIQUE, `first_name` varchar(30) NOT NULL, `last_name` varchar(30) NOT NULL, `email` varchar(75) NOT NULL, `is_staff` bool NOT NULL, `is_active` bool NOT NULL, `date_joined` datetime(6) NOT NULL); (params
None)
(0.206) CREATE TABLE `auth_user` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `password` varchar(128) NOT NULL, `last_login` datetime(6) NOT NULL, `is_superuser` bool NOT NULL, `username` varchar(30)
NOT NULL UNIQUE, `first_name` varchar(30) NOT NULL, `last_name` varchar(30) NOT NULL, `email` varchar(75) NOT NULL, `is_staff` bool NOT NULL, `is_active` bool NOT NULL, `date_joined` datetime(6) NOT NULL);
args=None
(0.158) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user'; args=['auth_user']
(0.166) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user'; args=['auth_user']
(0.139) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user'; args=['auth_user']
(0.096) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user'; args=['auth_user']
(0.141) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user'; args=['auth_user']
(0.125) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user'; args=['auth_user']
(0.188) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user'; args=['auth_user']
(0.210) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user'; args=['auth_user']
(0.154) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user'; args=['auth_user']
(0.163) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user'; args=['auth_user']
(0.186) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user'; args=['auth_user']
CREATE TABLE `auth_user_groups` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `user_id` integer NOT NULL, `group_id` integer NOT NULL); (params None)
(0.194) CREATE TABLE `auth_user_groups` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `user_id` integer NOT NULL, `group_id` integer NOT NULL); args=None
(0.104) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user_groups'; args=['auth_user_groups']
(0.115) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user_groups'; args=['auth_user_groups']
(0.166) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user_groups'; args=['auth_user_groups']
CREATE TABLE `auth_user_user_permissions` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `user_id` integer NOT NULL, `permission_id` integer NOT NULL); (params None)
(0.178) CREATE TABLE `auth_user_user_permissions` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `user_id` integer NOT NULL, `permission_id` integer NOT NULL); args=None
(0.138) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user_user_permissions'; args=['auth_user_user_permissions']
(0.146) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user_user_permissions'; args=['auth_user_user_permissions']
(0.079) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user_user_permissions'; args=['auth_user_user_permissions']
ALTER TABLE `auth_permission` ADD CONSTRAINT `auth_permission_content_type_id_2f476e4b_fk_django_co` FOREIGN KEY (`content_type_id`) REFERENCES `django_content_type` (`id`); (params ())
(0.156) ALTER TABLE `auth_permission` ADD CONSTRAINT `auth_permission_content_type_id_2f476e4b_fk_django_co` FOREIGN KEY (`content_type_id`) REFERENCES `django_content_type` (`id`); args=()
ALTER TABLE `auth_permission` ADD CONSTRAINT auth_permission_content_type_id_codename_01ab375a_uniq UNIQUE (`content_type_id`, `codename`); (params ())
(0.300) ALTER TABLE `auth_permission` ADD CONSTRAINT auth_permission_content_type_id_codename_01ab375a_uniq UNIQUE (`content_type_id`, `codename`); args=()
ALTER TABLE `auth_group_permissions` ADD CONSTRAINT `auth_group_permissions_group_id_b120cbf9_fk_auth_group_id` FOREIGN KEY (`group_id`) REFERENCES `auth_group` (`id`); (params ())
(0.215) ALTER TABLE `auth_group_permissions` ADD CONSTRAINT `auth_group_permissions_group_id_b120cbf9_fk_auth_group_id` FOREIGN KEY (`group_id`) REFERENCES `auth_group` (`id`); args=()
ALTER TABLE `auth_group_permissions` ADD CONSTRAINT `auth_group_permissio_permission_id_84c5c92e_fk_auth_perm` FOREIGN KEY (`permission_id`) REFERENCES `auth_permission` (`id`); (params ())
(0.280) ALTER TABLE `auth_group_permissions` ADD CONSTRAINT `auth_group_permissio_permission_id_84c5c92e_fk_auth_perm` FOREIGN KEY (`permission_id`) REFERENCES `auth_permission` (`id`); args=()
ALTER TABLE `auth_group_permissions` ADD CONSTRAINT auth_group_permissions_group_id_permission_id_0cd325b0_uniq UNIQUE (`group_id`, `permission_id`); (params ())
(0.205) ALTER TABLE `auth_group_permissions` ADD CONSTRAINT auth_group_permissions_group_id_permission_id_0cd325b0_uniq UNIQUE (`group_id`, `permission_id`); args=()
ALTER TABLE `auth_user_groups` ADD CONSTRAINT `auth_user_groups_user_id_6a12ed8b_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`); (params ())
(0.252) ALTER TABLE `auth_user_groups` ADD CONSTRAINT `auth_user_groups_user_id_6a12ed8b_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`); args=()
ALTER TABLE `auth_user_groups` ADD CONSTRAINT `auth_user_groups_group_id_97559544_fk_auth_group_id` FOREIGN KEY (`group_id`) REFERENCES `auth_group` (`id`); (params ())
(0.210) ALTER TABLE `auth_user_groups` ADD CONSTRAINT `auth_user_groups_group_id_97559544_fk_auth_group_id` FOREIGN KEY (`group_id`) REFERENCES `auth_group` (`id`); args=()
ALTER TABLE `auth_user_groups` ADD CONSTRAINT auth_user_groups_user_id_group_id_94350c0c_uniq UNIQUE (`user_id`, `group_id`); (params ())
(0.205) ALTER TABLE `auth_user_groups` ADD CONSTRAINT auth_user_groups_user_id_group_id_94350c0c_uniq UNIQUE (`user_id`, `group_id`); args=()
ALTER TABLE `auth_user_user_permissions` ADD CONSTRAINT `auth_user_user_permissions_user_id_a95ead1b_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`); (params ())
(0.212) ALTER TABLE `auth_user_user_permissions` ADD CONSTRAINT `auth_user_user_permissions_user_id_a95ead1b_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`); args=()
ALTER TABLE `auth_user_user_permissions` ADD CONSTRAINT `auth_user_user_permi_permission_id_1fbb5f2c_fk_auth_perm` FOREIGN KEY (`permission_id`) REFERENCES `auth_permission` (`id`); (params ())
(0.162) ALTER TABLE `auth_user_user_permissions` ADD CONSTRAINT `auth_user_user_permi_permission_id_1fbb5f2c_fk_auth_perm` FOREIGN KEY (`permission_id`) REFERENCES `auth_permission` (`id`); args=()
ALTER TABLE `auth_user_user_permissions` ADD CONSTRAINT auth_user_user_permissions_user_id_permission_id_14a6b632_uniq UNIQUE (`user_id`, `permission_id`); (params ())
(0.161) ALTER TABLE `auth_user_user_permissions` ADD CONSTRAINT auth_user_user_permissions_user_id_permission_id_14a6b632_uniq UNIQUE (`user_id`, `permission_id`); args=()
(0.014) SHOW FULL TABLES; args=None
(0.121) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('auth', '0001_initial', '2018-08-16 15:08:14.269528'); args=['auth', '0001_initial', '2018-08-16 15:08:14.269528']
Applying auth.0001_initial... OK
CREATE TABLE `django_admin_log` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `action_time` datetime(6) NOT NULL, `object_id` longtext NULL, `object_repr` varchar(200) NOT NULL, `action_flag` smallint
UNSIGNED NOT NULL, `change_message` longtext NOT NULL, `content_type_id` integer NULL, `user_id` integer NOT NULL); (params None)
(0.193) CREATE TABLE `django_admin_log` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `action_time` datetime(6) NOT NULL, `object_id` longtext NULL, `object_repr` varchar(200) NOT NULL, `action_flag` s
mallint UNSIGNED NOT NULL, `change_message` longtext NOT NULL, `content_type_id` integer NULL, `user_id` integer NOT NULL); args=None
(0.168) SELECT engine FROM information_schema.tables WHERE table_name = 'django_admin_log'; args=['django_admin_log']
(0.143) SELECT engine FROM information_schema.tables WHERE table_name = 'django_admin_log'; args=['django_admin_log']
(0.174) SELECT engine FROM information_schema.tables WHERE table_name = 'django_admin_log'; args=['django_admin_log']
(0.147) SELECT engine FROM information_schema.tables WHERE table_name = 'django_admin_log'; args=['django_admin_log']
(0.155) SELECT engine FROM information_schema.tables WHERE table_name = 'django_admin_log'; args=['django_admin_log']
(0.132) SELECT engine FROM information_schema.tables WHERE table_name = 'django_admin_log'; args=['django_admin_log']
(0.128) SELECT engine FROM information_schema.tables WHERE table_name = 'django_admin_log'; args=['django_admin_log']
(0.104) SELECT engine FROM information_schema.tables WHERE table_name = 'django_admin_log'; args=['django_admin_log']
ALTER TABLE `django_admin_log` ADD CONSTRAINT `django_admin_log_content_type_id_c4bce8eb_fk_django_co` FOREIGN KEY (`content_type_id`) REFERENCES `django_content_type` (`id`); (params ())
(0.125) ALTER TABLE `django_admin_log` ADD CONSTRAINT `django_admin_log_content_type_id_c4bce8eb_fk_django_co` FOREIGN KEY (`content_type_id`) REFERENCES `django_content_type` (`id`); args=()
ALTER TABLE `django_admin_log` ADD CONSTRAINT `django_admin_log_user_id_c564eba6_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`); (params ())
(0.165) ALTER TABLE `django_admin_log` ADD CONSTRAINT `django_admin_log_user_id_c564eba6_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`); args=()
(0.021) SHOW FULL TABLES; args=None
(0.121) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('admin', '0001_initial', '2018-08-16 15:08:16.106198'); args=['admin', '0001_initial', '2018-08-16 15:08:16.106198']
Applying admin.0001_initial... OK
(0.014) SHOW FULL TABLES; args=None
(0.119) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('admin', '0002_logentry_remove_auto_add', '2018-08-16 15:08:16.288329'); args=['admin', '0002_logentry_remove_auto_add', '2018-08-1
6 15:08:16.288329']
Applying admin.0002_logentry_remove_auto_add... OK
(0.014) SHOW FULL TABLES; args=None
(0.106) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('admin', '0003_logentry_add_action_flag_choices', '2018-08-16 15:08:16.470961'); args=['admin', '0003_logentry_add_action_flag_choi
ces', '2018-08-16 15:08:16.470961']
Applying admin.0003_logentry_add_action_flag_choices... OK
CREATE TABLE `app01_book` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `title` varchar(32) NOT NULL UNIQUE, `pub_date` date NOT NULL, `price` numeric(8, 2) NOT NULL, `publish` varchar(22) NOT NULL); (
params None)
(0.119) CREATE TABLE `app01_book` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `title` varchar(32) NOT NULL UNIQUE, `pub_date` date NOT NULL, `price` numeric(8, 2) NOT NULL, `publish` varchar(22) NOT
NULL); args=None
(0.124) SELECT engine FROM information_schema.tables WHERE table_name = 'app01_book'; args=['app01_book']
(0.128) SELECT engine FROM information_schema.tables WHERE table_name = 'app01_book'; args=['app01_book']
(0.114) SELECT engine FROM information_schema.tables WHERE table_name = 'app01_book'; args=['app01_book']
(0.094) SELECT engine FROM information_schema.tables WHERE table_name = 'app01_book'; args=['app01_book']
(0.105) SELECT engine FROM information_schema.tables WHERE table_name = 'app01_book'; args=['app01_book']
(0.015) SHOW FULL TABLES; args=None
(0.166) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('app01', '0001_initial', '2018-08-16 15:08:17.320430'); args=['app01', '0001_initial', '2018-08-16 15:08:17.320430']
Applying app01.0001_initial... OK
ALTER TABLE `django_content_type` MODIFY `name` varchar(100) NULL; (params [])
(0.243) ALTER TABLE `django_content_type` MODIFY `name` varchar(100) NULL; args=[]
ALTER TABLE `django_content_type` DROP COLUMN `name`; (params ())
(0.142) ALTER TABLE `django_content_type` DROP COLUMN `name`; args=()
(0.016) SHOW FULL TABLES; args=None
(0.165) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('contenttypes', '0002_remove_content_type_name', '2018-08-16 15:08:17.989002'); args=['contenttypes', '0002_remove_content_type_nam
e', '2018-08-16 15:08:17.989002']
Applying contenttypes.0002_remove_content_type_name... OK
ALTER TABLE `auth_permission` MODIFY `name` varchar(255) NOT NULL; (params [])
(0.175) ALTER TABLE `auth_permission` MODIFY `name` varchar(255) NOT NULL; args=[]
(0.013) SHOW FULL TABLES; args=None
(0.144) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('auth', '0002_alter_permission_name_max_length', '2018-08-16 15:08:18.391744'); args=['auth', '0002_alter_permission_name_max_lengt
h', '2018-08-16 15:08:18.391744']
Applying auth.0002_alter_permission_name_max_length... OK
ALTER TABLE `auth_user` MODIFY `email` varchar(254) NOT NULL; (params [])
(0.165) ALTER TABLE `auth_user` MODIFY `email` varchar(254) NOT NULL; args=[]
(0.019) SHOW FULL TABLES; args=None
(0.133) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('auth', '0003_alter_user_email_max_length', '2018-08-16 15:08:18.776295'); args=['auth', '0003_alter_user_email_max_length', '2018-
08-16 15:08:18.776295']
Applying auth.0003_alter_user_email_max_length... OK
(0.013) SHOW FULL TABLES; args=None
(0.164) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('auth', '0004_alter_user_username_opts', '2018-08-16 15:08:18.970966'); args=['auth', '0004_alter_user_username_opts', '2018-08-16
15:08:18.970966']
Applying auth.0004_alter_user_username_opts... OK
ALTER TABLE `auth_user` MODIFY `last_login` datetime(6) NULL; (params [])
(0.213) ALTER TABLE `auth_user` MODIFY `last_login` datetime(6) NULL; args=[]
(0.016) SHOW FULL TABLES; args=None
(0.206) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('auth', '0005_alter_user_last_login_null', '2018-08-16 15:08:19.416542'); args=['auth', '0005_alter_user_last_login_null', '2018-08
-16 15:08:19.416542']
Applying auth.0005_alter_user_last_login_null... OK
(0.022) SHOW FULL TABLES; args=None
(0.177) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('auth', '0006_require_contenttypes_0002', '2018-08-16 15:08:19.696792'); args=['auth', '0006_require_contenttypes_0002', '2018-08-1
6 15:08:19.696792']
Applying auth.0006_require_contenttypes_0002... OK
(0.014) SHOW FULL TABLES; args=None
(0.187) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('auth', '0007_alter_validators_add_error_messages', '2018-08-16 15:08:19.934158'); args=['auth', '0007_alter_validators_add_error_m
essages', '2018-08-16 15:08:19.934158']
Applying auth.0007_alter_validators_add_error_messages... OK
ALTER TABLE `auth_user` MODIFY `username` varchar(150) NOT NULL; (params [])
(0.195) ALTER TABLE `auth_user` MODIFY `username` varchar(150) NOT NULL; args=[]
(0.018) SHOW FULL TABLES; args=None
(0.153) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('auth', '0008_alter_user_username_max_length', '2018-08-16 15:08:20.388736'); args=['auth', '0008_alter_user_username_max_length',
'2018-08-16 15:08:20.388736']
Applying auth.0008_alter_user_username_max_length... OK
ALTER TABLE `auth_user` MODIFY `last_name` varchar(150) NOT NULL; (params [])
(0.187) ALTER TABLE `auth_user` MODIFY `last_name` varchar(150) NOT NULL; args=[]
(0.013) SHOW FULL TABLES; args=None
(0.132) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('auth', '0009_alter_user_last_name_max_length', '2018-08-16 15:08:20.790483'); args=['auth', '0009_alter_user_last_name_max_length'
, '2018-08-16 15:08:20.790483']
Applying auth.0009_alter_user_last_name_max_length... OK
CREATE TABLE `django_session` (`session_key` varchar(40) NOT NULL PRIMARY KEY, `session_data` longtext NOT NULL, `expire_date` datetime(6) NOT NULL); (params None)
(0.152) CREATE TABLE `django_session` (`session_key` varchar(40) NOT NULL PRIMARY KEY, `session_data` longtext NOT NULL, `expire_date` datetime(6) NOT NULL); args=None
(0.163) SELECT engine FROM information_schema.tables WHERE table_name = 'django_session'; args=['django_session']
(0.161) SELECT engine FROM information_schema.tables WHERE table_name = 'django_session'; args=['django_session']
(0.186) SELECT engine FROM information_schema.tables WHERE table_name = 'django_session'; args=['django_session']
CREATE INDEX `django_session_expire_date_a5c62663` ON `django_session` (`expire_date`); (params ())
(0.189) CREATE INDEX `django_session_expire_date_a5c62663` ON `django_session` (`expire_date`); args=()
(0.013) SHOW FULL TABLES; args=None
(0.262) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('sessions', '0001_initial', '2018-08-16 15:08:21.836393'); args=['sessions', '0001_initial', '2018-08-16 15:08:21.836393']
Applying sessions.0001_initial... OK
(0.013) SHOW FULL TABLES; args=None
(0.266) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
(0.285) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'admin' AND `django_content_
type`.`model` = 'logentry'); args=('admin', 'logentry')
(0.309) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'admin' AND `django_content_
type`.`model` = 'logentry'); args=('admin', 'logentry')
(0.339) INSERT INTO `django_content_type` (`app_label`, `model`) VALUES ('admin', 'logentry'); args=['admin', 'logentry']
(0.375) SELECT `auth_permission`.`content_type_id`, `auth_permission`.`codename` FROM `auth_permission` INNER JOIN `django_content_type` ON (`auth_permission`.`content_type_id` = `django_content_type`.`id`)
WHERE `auth_permission`.`content_type_id` IN (1) ORDER BY `django_content_type`.`app_label` ASC, `django_content_type`.`model` ASC, `auth_permission`.`codename` ASC; args=(1,)
(0.250) INSERT INTO `auth_permission` (`name`, `content_type_id`, `codename`) VALUES ('Can add log entry', 1, 'add_logentry'), ('Can change log entry', 1, 'change_logentry'), ('Can delete log entry', 1, 'de
lete_logentry'), ('Can view log entry', 1, 'view_logentry'); args=('Can add log entry', 1, 'add_logentry', 'Can change log entry', 1, 'change_logentry', 'Can delete log entry', 1, 'delete_logentry', 'Can vi
ew log entry', 1, 'view_logentry')
(0.271) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE `django_content_type`.`app_label` = 'admin'; args=('admin',)
(0.237) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'auth' AND `django_content_t
ype`.`model` = 'permission'); args=('auth', 'permission')
(0.353) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'auth' AND `django_content_t
ype`.`model` = 'permission'); args=('auth', 'permission')
(0.203) INSERT INTO `django_content_type` (`app_label`, `model`) VALUES ('auth', 'permission'); args=['auth', 'permission']
(0.270) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'auth' AND `django_content_t
ype`.`model` = 'group'); args=('auth', 'group')
(0.278) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'auth' AND `django_content_t
ype`.`model` = 'group'); args=('auth', 'group')
(0.157) INSERT INTO `django_content_type` (`app_label`, `model`) VALUES ('auth', 'group'); args=['auth', 'group']
(0.129) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'auth' AND `django_content_t
ype`.`model` = 'user'); args=('auth', 'user')
(0.136) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'auth' AND `django_content_t
ype`.`model` = 'user'); args=('auth', 'user')
(0.084) INSERT INTO `django_content_type` (`app_label`, `model`) VALUES ('auth', 'user'); args=['auth', 'user']
(0.093) SELECT `auth_permission`.`content_type_id`, `auth_permission`.`codename` FROM `auth_permission` INNER JOIN `django_content_type` ON (`auth_permission`.`content_type_id` = `django_content_type`.`id`)
WHERE `auth_permission`.`content_type_id` IN (2, 3, 4) ORDER BY `django_content_type`.`app_label` ASC, `django_content_type`.`model` ASC, `auth_permission`.`codename` ASC; args=(2, 3, 4)
(0.137) INSERT INTO `auth_permission` (`name`, `content_type_id`, `codename`) VALUES ('Can add permission', 2, 'add_permission'), ('Can change permission', 2, 'change_permission'), ('Can delete permission',
2, 'delete_permission'), ('Can view permission', 2, 'view_permission'), ('Can add group', 3, 'add_group'), ('Can change group', 3, 'change_group'), ('Can delete group', 3, 'delete_group'), ('Can view group
', 3, 'view_group'), ('Can add user', 4, 'add_user'), ('Can change user', 4, 'change_user'), ('Can delete user', 4, 'delete_user'), ('Can view user', 4, 'view_user'); args=('Can add permission', 2, 'add_per
mission', 'Can change permission', 2, 'change_permission', 'Can delete permission', 2, 'delete_permission', 'Can view permission', 2, 'view_permission', 'Can add group', 3, 'add_group', 'Can change group',
3, 'change_group', 'Can delete group', 3, 'delete_group', 'Can view group', 3, 'view_group', 'Can add user', 4, 'add_user', 'Can change user', 4, 'change_user', 'Can delete user', 4, 'delete_user', 'Can vie
w user', 4, 'view_user')
(0.094) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE `django_content_type`.`app_label` = 'auth'; args=('auth',)
(0.122) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'contenttypes' AND `django_c
ontent_type`.`model` = 'contenttype'); args=('contenttypes', 'contenttype')
(0.123) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'contenttypes' AND `django_c
ontent_type`.`model` = 'contenttype'); args=('contenttypes', 'contenttype')
(0.127) INSERT INTO `django_content_type` (`app_label`, `model`) VALUES ('contenttypes', 'contenttype'); args=['contenttypes', 'contenttype']
(0.091) SELECT `auth_permission`.`content_type_id`, `auth_permission`.`codename` FROM `auth_permission` INNER JOIN `django_content_type` ON (`auth_permission`.`content_type_id` = `django_content_type`.`id`)
WHERE `auth_permission`.`content_type_id` IN (5) ORDER BY `django_content_type`.`app_label` ASC, `django_content_type`.`model` ASC, `auth_permission`.`codename` ASC; args=(5,)
(0.089) INSERT INTO `auth_permission` (`name`, `content_type_id`, `codename`) VALUES ('Can add content type', 5, 'add_contenttype'), ('Can change content type', 5, 'change_contenttype'), ('Can delete conten
t type', 5, 'delete_contenttype'), ('Can view content type', 5, 'view_contenttype'); args=('Can add content type', 5, 'add_contenttype', 'Can change content type', 5, 'change_contenttype', 'Can delete conte
nt type', 5, 'delete_contenttype', 'Can view content type', 5, 'view_contenttype')
(0.100) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE `django_content_type`.`app_label` = 'contenttypes'; args=('conten
ttypes',)
(0.093) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'sessions' AND `django_conte
nt_type`.`model` = 'session'); args=('sessions', 'session')
(0.122) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'sessions' AND `django_conte
nt_type`.`model` = 'session'); args=('sessions', 'session')
(0.148) INSERT INTO `django_content_type` (`app_label`, `model`) VALUES ('sessions', 'session'); args=['sessions', 'session']
(0.097) SELECT `auth_permission`.`content_type_id`, `auth_permission`.`codename` FROM `auth_permission` INNER JOIN `django_content_type` ON (`auth_permission`.`content_type_id` = `django_content_type`.`id`)
WHERE `auth_permission`.`content_type_id` IN (6) ORDER BY `django_content_type`.`app_label` ASC, `django_content_type`.`model` ASC, `auth_permission`.`codename` ASC; args=(6,)
(0.132) INSERT INTO `auth_permission` (`name`, `content_type_id`, `codename`) VALUES ('Can add session', 6, 'add_session'), ('Can change session', 6, 'change_session'), ('Can delete session', 6, 'delete_ses
sion'), ('Can view session', 6, 'view_session'); args=('Can add session', 6, 'add_session', 'Can change session', 6, 'change_session', 'Can delete session', 6, 'delete_session', 'Can view session', 6, 'view
_session')
(0.093) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `d
jango_content_type` WHERE `django_content_type`.`app_label` = 'sessions'; args=('sessions',)
(0.134) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `d
jango_content_type` WHERE (`django_content_type`.`app_label` = 'app01' AND `django_content_type`.`model` = 'book');
args=('app01', 'book')
(0.144) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `d
jango_content_type` WHERE (`django_content_type`.`app_label` = 'app01' AND `django_content_type`.`model` = 'book');
args=('app01', 'book')
(0.108) INSERT INTO `django_content_type` (`app_label`, `model`) VALUES ('app01', 'book'); args=['app01', 'book']
(0.109) SELECT `auth_permission`.`content_type_id`, `auth_permission`.`codename` FROM `auth_permission` INNER JOIN `django_content_type` ON (`auth_permi
ssion`.`content_type_id` = `django_content_type`.`id`) WHERE `auth_permission`.`content_type_id` IN (7) ORDER BY `django_content_type`.`app_label` ASC,
`django_content_type`.`model` ASC, `auth_permission`.`codename` ASC; args=(7,)
(0.093) INSERT INTO `auth_permission` (`name`, `content_type_id`, `codename`) VALUES ('Can add book', 7, 'add_book'), ('Can change book', 7, 'change_boo
k'), ('Can delete book', 7, 'delete_book'), ('Can view book', 7, 'view_book'); args=('Can add book', 7, 'add_book', 'Can change book', 7, 'change_book',
'Can delete book', 7, 'delete_book', 'Can view book', 7, 'view_book')
(0.129) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE `django_con
tent_type`.`app_label` = 'app01'; args=('app01',) (venv) C:\Users\TQTL911\PycharmProjects\ORM>
39-单表操作之添加记录
1、单表操作添加记录的两种方式;
view.py;
from django.shortcuts import render,HttpResponse #from app01 import models
from app01.models import Book
# Create your views here.
def index(request):
#添加表记录;
#方式1:通过类生成对象的方法进行添加,但是需要使用save()方法进行保存记录;
# book_obj = Book(id=1,title="Python红宝书",price=100,pub_date="2018-08-16",publish="人民教育出版社")
# book_obj.save()
# return HttpResponse("OK") #方式2:create是有返回值的,就是当前生成的对象的记录;
book_obj = Book.objects.create(title="Python全栈开发指南2",price=100,pub_date="2018-08-16",publish="人民教育出版社")
print(book_obj.title)
print(book_obj.price)
print(book_obj.publish)
return HttpResponse("记录添加成功!")
操作日志:
"D:\Program\PyCharm 2018.1.4\bin\runnerw.exe" C:\Users\TQTL911\PycharmProjects\ORM\venv\Scripts\python.exe C:/Users/TQTL911/PycharmProjects/ORM/manage.py runserver 8000
Performing system checks... System check identified no issues (0 silenced).
(0.010) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.010) SHOW FULL TABLES; args=None
(0.010) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
August 16, 2018 - 23:42:21
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
(0.010) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` LIMIT 21; args=()
Internal Server Error: /index/
Traceback (most recent call last):
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\TQTL911\PycharmProjects\ORM\app01\views.py", line 15, in index
book_obj = Book.objects.create(ititle="Python红宝书",price=100,pub_date="2018-08-16",publish="人民教育出版社")
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\query.py", line 411, in create
obj = self.model(**kwargs)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\base.py", line 484, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % kwarg)
TypeError: 'ititle' is an invalid keyword argument for this function
[16/Aug/2018 23:42:35] "GET /index/ HTTP/1.1" 500 81556
Performing system checks... System check identified no issues (0 silenced).
(0.010) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.010) SHOW FULL TABLES; args=None
August 16, 2018 - 23:42:49
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
(0.010) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
(0.010) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.011) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.010) INSERT INTO `app01_book` (`title`, `pub_date`, `price`, `publish`) VALUES ('Python红宝书', '2018-08-16', '100.00', '人民教育出版社'); args=['Python红宝书', '2018-08-16', '100.00', '人民教育出版社']
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` LIMIT 21; args=()
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` LIMIT 21; args=()
Internal Server Error: /index/
Traceback (most recent call last):
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\mysql\base.py", line 71, in execute
return self.cursor.execute(query, args)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\cursors.py", line 170, in execute
result = self._query(query)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\cursors.py", line 328, in _query
conn.query(q)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 516, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 727, in _read_query_result
result.read()
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 1066, in read
first_packet = self.connection._read_packet()
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 683, in _read_packet
packet.check_error()
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\protocol.py", line 220, in check_error
err.raise_mysql_exception(self._data)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\err.py", line 109, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.IntegrityError: (1062, "Duplicate entry 'Python红宝书' for key 'title'") The above exception was the direct cause of the following exception: Traceback (most recent call last):
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\TQTL911\PycharmProjects\ORM\app01\views.py", line 15, in index
book_obj = Book.objects.create(title="Python红宝书",price=100,pub_date="2018-08-16",publish="人民教育出版社")
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\query.py", line 413, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\base.py", line 717, in save
force_update=force_update, update_fields=update_fields)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\base.py", line 747, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\base.py", line 830, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\base.py", line 868, in _do_insert
using=using, raw=raw)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\query.py", line 1133, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1285, in execute_sql
cursor.execute(sql, params)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 100, in execute
return super().execute(sql, params)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\mysql\base.py", line 71, in execute
return self.cursor.execute(query, args)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\cursors.py", line 170, in execute
result = self._query(query)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\cursors.py", line 328, in _query
conn.query(q)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 516, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 727, in _read_query_result
result.read()
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 1066, in read
first_packet = self.connection._read_packet()
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 683, in _read_packet
packet.check_error()
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\protocol.py", line 220, in check_error
err.raise_mysql_exception(self._data)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\err.py", line 109, in raise_mysql_exception
raise errorclass(errno, errval)
django.db.utils.IntegrityError: (1062, "Duplicate entry 'Python红宝书' for key 'title'")
[16/Aug/2018 23:42:53] "GET /index/ HTTP/1.1" 500 219064
Performing system checks... System check identified no issues (0 silenced).
(0.011) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.011) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.012) SHOW FULL TABLES; args=None
(0.012) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
August 16, 2018 - 23:43:28
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
(0.009) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.009) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.009) INSERT INTO `app01_book` (`title`, `pub_date`, `price`, `publish`) VALUES ('Python全栈开发指南', '2018-08-16', '100.00', '人民教育出版社'); args=['Python全栈开发指南', '2018-08-16', '100.00', '人民教育出版社']
Python全栈开发指南
100
人民教育出版社
Internal Server Error: /index/
Traceback (most recent call last):
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\handlers\base.py", line 137, in _get_response
"returned None instead." % (callback.__module__, view_name)
ValueError: The view app01.views.index didn't return an HttpResponse object. It returned None instead.
[16/Aug/2018 23:43:30] "GET /index/ HTTP/1.1" 500 58321
Performing system checks... System check identified no issues (0 silenced).
(0.010) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.011) SHOW FULL TABLES; args=None
(0.011) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
August 16, 2018 - 23:44:05
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
(0.012) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.011) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.011) INSERT INTO `app01_book` (`title`, `pub_date`, `price`, `publish`) VALUES ('Python全栈开发指南', '2018-08-16', '100.00', '人民教育出版社'); args=['Python全栈开发指南', '2018-08-16', '100.00', '人民教育出版社']
(0.012) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` LIMIT 21; args=()
(0.012) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` LIMIT 21; args=()
Internal Server Error: /index/
Traceback (most recent call last):
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\mysql\base.py", line 71, in execute
return self.cursor.execute(query, args)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\cursors.py", line 170, in execute
result = self._query(query)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\cursors.py", line 328, in _query
conn.query(q)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 516, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 727, in _read_query_result
result.read()
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 1066, in read
first_packet = self.connection._read_packet()
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 683, in _read_packet
packet.check_error()
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\protocol.py", line 220, in check_error
err.raise_mysql_exception(self._data)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\err.py", line 109, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.IntegrityError: (1062, "Duplicate entry 'Python全栈开发指南' for key 'title'") The above exception was the direct cause of the following exception: Traceback (most recent call last):
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\TQTL911\PycharmProjects\ORM\app01\views.py", line 15, in index
book_obj = Book.objects.create(title="Python全栈开发指南",price=100,pub_date="2018-08-16",publish="人民教育出版社")
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\query.py", line 413, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\base.py", line 717, in save
force_update=force_update, update_fields=update_fields)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\base.py", line 747, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\base.py", line 830, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\base.py", line 868, in _do_insert
using=using, raw=raw)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\query.py", line 1133, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1285, in execute_sql
cursor.execute(sql, params)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 100, in execute
return super().execute(sql, params)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\mysql\base.py", line 71, in execute
return self.cursor.execute(query, args)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\cursors.py", line 170, in execute
result = self._query(query)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\cursors.py", line 328, in _query
conn.query(q)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 516, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 727, in _read_query_result
result.read()
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 1066, in read
first_packet = self.connection._read_packet()
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 683, in _read_packet
packet.check_error()
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\protocol.py", line 220, in check_error
err.raise_mysql_exception(self._data)
File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\err.py", line 109, in raise_mysql_exception
raise errorclass(errno, errval)
django.db.utils.IntegrityError: (1062, "Duplicate entry 'Python全栈开发指南' for key 'title'")
[16/Aug/2018 23:44:07] "GET /index/ HTTP/1.1" 500 219853
Performing system checks... System check identified no issues (0 silenced).
(0.012) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.011) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.012) SHOW FULL TABLES; args=None
August 16, 2018 - 23:44:17
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
(0.012) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
(0.010) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.010) INSERT INTO `app01_book` (`title`, `pub_date`, `price`, `publish`) VALUES ('Python全栈开发指南2', '2018-08-16', '100.00', '人民教育出版社'); args=['Python全栈开发指南2', '2018-08-16', '100.00', '人民教育出版社']
Python全栈开发指南2
100
人民教育出版社
[16/Aug/2018 23:44:19] "GET /index/ HTTP/1.1" 200 21
Performing system checks... System check identified no issues (0 silenced).
(0.009) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.009) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.010) SHOW FULL TABLES; args=None
(0.010) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
August 16, 2018 - 23:45:46
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Performing system checks... System check identified no issues (0 silenced).
(0.011) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.011) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.010) SHOW FULL TABLES; args=None
August 16, 2018 - 23:46:50
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
(0.011) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
40-单表操作之查询API
1、查询API初识;
先做查询操作,因为没有拿到查询结果就不知道如何去删除、修改,二者理论上是基于查询操作进行的;
- all();
- first()、last()基于all()方法基础之上使用;
- filter();
- get();
<1> all(): 查询所有结果 <2> filter(**kwargs): 它包含了与所给筛选条件相匹配的对象; <3> get(**kwargs): 返回与所给筛选条件相匹配的对象,返回结果有且只有一个,
如果符合筛选条件的对象超过一个或者没有都会抛出错误; <4> exclude(**kwargs): 它包含了与所给筛选条件不匹配的对象; <5> order_by(*field): 对查询结果排序; <6> reverse(): 对查询结果反向排序; <8> count(): 返回数据库中匹配查询(QuerySet)的对象数量; <9> first(): 返回第一条记录; <10> last(): 返回最后一条记录; <11> exists(): 如果QuerySet包含数据,就返回True,否则返回False; <12> values(*field): 返回一个ValueQuerySet——一个特殊的QuerySet,运行后得到的并不是一系列;
model的实例化对象,而是一个可迭代的字典序列;
<13> values_list(*field): 它与values()非常相似,它返回的是一个元组序列,values返回的是一个字典序列; <14> distinct(): 从返回结果中剔除重复纪录;
views.py;
from django.shortcuts import render,HttpResponse #from app01 import models
from app01.models import Book
# Create your views here.
def index(request):
#----------------------添加表记录;--------------------------#
#方式1:通过类生成对象的方法进行添加,但是需要使用save方法进行保存记录;
# book_obj = Book(id=1,title="Python红宝书",price=100,pub_date="2018-08-16",publish="人民教育出版社")
# book_obj.save()
# return HttpResponse("OK") #方式2:create是有返回值的,就是当前生成的对象的记录;
# book_obj = Book.objects.create(title="Python全栈开发指南2",price=100,pub_date="2018-08-16",publish="人民教育出版社")
# print(book_obj.title)
# print(book_obj.price)
# print(book_obj.publish)
#return HttpResponse("记录添加成功!")
#----------------------查询表记录API--------------------------#
""
"""
1、方法的返回值;
2、方法的调用者; :param request:
:return:
"""
#(1)all查询素有结果;
book_list = Book.objects.all()
print(book_list)#ook: Book object (1)>, <Book: Book object (3)>, <Book: Book object (5)>]>,类似于列表中,放着一个个对象![obj1,obj2,.....objn]
for obj in book_list:
print("书名-书的价格",obj.title,"-",obj.price)
print('-'*20)
print("book_list[1].title",book_list[1].title)
print("book_list[1].price",book_list[1].price) #(2)first和last方法;调用者:queryset对象;返回值:model对象;
book_first = Book.objects.all().first()
book_last = Book.objects.all().last()
print("book_first",book_first)
print("book_last",book_last)
#(3)filter()方法_返回值:queryset对象;
#Book.objects.all().filter(title = "python")
Book.objects.all().filter(price = 100)#[obj1,obj2,obj3]
book_filter_first = Book.objects.filter(price=100).first()
print("book_list",book_list)#<QuerySet [<Book: Python红宝书>, <Book: Python全栈开发指南>, <Book: Python全栈开发指南2>]>
print("book_filter_first",book_filter_first)
#(3) get()方法;有且只有一个查询结果时候才有意义,返回值:model对象;
#book_get_title = Book.objects.get(title="go")
book_get_price = Book.objects.get(price=200)
#print("book_get_title",book_get_title)
print("book_get_price",book_get_price) return HttpResponse("OK")
操作日志:
app01.models.Book.MultipleObjectsReturned: get() returned more than one Book -- it returned 2!
[17/Aug/2018 10:48:42] "GET /index/ HTTP/1.1" 500 77130
(0.010) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.010) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` LIMIT 21; args=()
<QuerySet [<Book: Python红宝书>, <Book: Python全栈开发指南>, <Book: Python全栈开发指南2>, <Book: Go语言从入门到放弃>, <Book: Go全栈开发>]>
书名-书的价格 Python红宝书 - 100.00
书名-书的价格 Python全栈开发指南 - 100.00
书名-书的价格 Python全栈开发指南2 - 100.00
书名-书的价格 Go语言从入门到放弃 - 201.00
书名-书的价格 Go全栈开发 - 200.00
--------------------
book_list[1].title Python全栈开发指南
book_list[1].price 100.00
(0.010) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book`; args=()
(0.010) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`id` ASC LIMIT 1; args=()
book_first Python红宝书
book_last Go全栈开发
(0.010) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`id` DESC LIMIT 1; args=()
(0.010) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`price` = 100 ORDER BY `app01_book`.`id` ASC LIMIT 1; args=(Decimal(''),)
book_list <QuerySet [<Book: Python红宝书>, <Book: Python全栈开发指南>, <Book: Python全栈开发指南2>, <Book: Go语言从入门到放弃>, <Book: Go全栈开发>]>
book_filter_first Python红宝书
(0.010) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`price` = 200; args=(Decimal(''),)
[17/Aug/2018 10:49:06] "GET /index/ HTTP/1.1" 200 2
book_get_price Go全栈开发
Performing system checks... System check identified no issues (0 silenced).
(0.011) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.011) SHOW FULL TABLES; args=None
(0.011) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
August 17, 2018 - 10:53:51
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
41-单表操作之查询API-2
1、单表查询API之其他方法;
- exclude();
- order_by();
- count();
- exist();
views.py;
from django.shortcuts import render,HttpResponse #from app01 import models
from app01.models import Book
# Create your views here.
def index(request):
#----------------------添加表记录;--------------------------#
#方式1:通过类生成对象的方法进行添加,但是需要使用save方法进行保存记录;
# book_obj = Book(id=1,title="Python红宝书",price=100,pub_date="2018-08-16",publish="人民教育出版社")
# book_obj.save()
# return HttpResponse("OK") #方式2:create是有返回值的,就是当前生成的对象的记录;
# book_obj = Book.objects.create(title="Python全栈开发指南2",price=100,pub_date="2018-08-16",publish="人民教育出版社")
# print(book_obj.title)
# print(book_obj.price)
# print(book_obj.publish)
#return HttpResponse("记录添加成功!")
#----------------------查询表记录API--------------------------#
""
"""
1、方法的返回值;
2、方法的调用者; :param request:
:return:
"""
#(1)all查询素有结果;
book_list = Book.objects.all()
print(book_list)#ook: Book object (1)>, <Book: Book object (3)>, <Book: Book object (5)>]>,类似于列表中,放着一个个对象![obj1,obj2,.....objn]
for obj in book_list:
print("书名-书的价格",obj.title,"-",obj.price)
print('-'*20)
print("book_list[1].title",book_list[1].title)
print("book_list[1].price",book_list[1].price) #(2)first和last方法;调用者:queryset对象;返回值:model对象;
book_first = Book.objects.all().first()
book_last = Book.objects.all().last()
print("book_first",book_first)
print("book_last",book_last)
#(3)filter()方法,支持多条件过滤;——返回值:queryset对象;
#Book.objects.all().filter(title = "python")
Book.objects.all().filter(price = 100)#[obj1,obj2,obj3]
book_filter_first = Book.objects.filter(price=100).first()
book_filter_and = Book.objects.filter(price=100,title = "Go")
print("book_list",book_list)#<QuerySet [<Book: Python红宝书>, <Book: Python全栈开发指南>, <Book: Python全栈开发指南2>]>
print("book_filter_first",book_filter_first)
print("book_filter_and",book_filter_and)
#(3) get()方法;有且只有一个查询结果时候才有意义,返回值:model对象;
#book_get_title = Book.objects.get(title="go")
book_get_price = Book.objects.get(price=200)
#print("book_get_title",book_get_title)
print("book_get_price",book_get_price) #(5)exclude过滤取反;返回值:
book_exclude = Book.objects.all().exclude(title="Go")
print("book_exclude",book_exclude)#<QuerySet [<Book: Python红宝书>, <Book: Python全栈开发指南>, <Book: Python全栈开发指南2>, <Book: Go语言从入门到放弃>, <Book: Go全栈开发>]> #(6)order_by方法,调用者:queryset对象;返回值:queryset对象;
book_order_by_id = Book.objects.all().order_by("-id")
book_order_by_price = Book.objects.all().order_by("price")
book_order_by_price_id = Book.objects.all().order_by("price","id")
print("book_order_by_price",book_order_by_price)#ASC
print("book_order_by_id",book_order_by_id)#DESC
print("book_order_by_price_id",book_order_by_price_id)#DESC&ACS #count()方法——调用者:queryset对象,返回值:int;
book_count = Book.objects.all().count()
print(book_count) #exist()方法——返回值:布尔值,True 或者 False;
book_all = Book.objects.all()#效率低下!
book_exist = Book.objects.all().exists()#效率低下!
print("book_all",book_all)
print("book_exist",book_exist)#book_exist True return HttpResponse("OK")
操作日志:
System check identified no issues (0 silenced).
(0.019) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.011) SHOW FULL TABLES; args=None
August 17, 2018 - 11:13:56
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
(0.011) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
(0.011) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` LIMIT 21; args=()
<QuerySet [<Book: Python红宝书>, <Book: Python全栈开发指南>, <Book: Python全栈开发指南2>, <Book: Go语言从入门到放弃>, <Book: Go全栈开发>]>
书名-书的价格 Python红宝书 - 100.00
书名-书的价格 Python全栈开发指南 - 100.00
书名-书的价格 Python全栈开发指南2 - 100.00
书名-书的价格 Go语言从入门到放弃 - 201.00
书名-书的价格 Go全栈开发 - 200.00
--------------------
book_list[1].title Python全栈开发指南
book_list[1].price 100.00
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book`; args=()
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`id` ASC LIMIT 1; args=()
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`id` DESC LIMIT 1; args=()
book_first Python红宝书
book_last Go全栈开发
book_list <QuerySet [<Book: Python红宝书>, <Book: Python全栈开发指南>, <Book: Python全栈开发指南2>, <Book: Go语言从入门到放弃>, <Book: Go全栈开发>]>
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`price` = 100 ORDER BY `app01_book`.`id` ASC LIMIT 1; args=(Decimal(''),)
book_filter_first Python红宝书
book_filter_and <QuerySet []>
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE (`app01_book`.`price` = 100 AND `app01_book`.`title` = 'Go') LIMIT 21; args=(Decimal(''), 'Go')
book_get_price Go全栈开发
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`price` = 200; args=(Decimal(''),)
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE NOT (`app01_book`.`title` = 'Go') LIMIT 21; args=('Go',)
book_exclude <QuerySet [<Book: Python红宝书>, <Book: Python全栈开发指南>, <Book: Python全栈开发指南2>, <Book: Go语言从入门到放弃>, <Book: Go全栈开发>]>
book_order_by_price <QuerySet [<Book: Python红宝书>, <Book: Python全栈开发指南>, <Book: Python全栈开发指南2>, <Book: Go全栈开发>, <Book: Go语言从入门到放弃>]>
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`price` ASC LIMIT 21; args=()
book_order_by_id <QuerySet [<Book: Go全栈开发>, <Book: Go语言从入门到放弃>, <Book: Python全栈开发指南2>, <Book: Python全栈开发指南>, <Book: Python红宝书>]>
(0.019) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`id` DESC LIMIT 21; args=()
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`price` ASC, `app01_book`.`id` ASC LIMIT 21; args=()
book_order_by_price_id <QuerySet [<Book: Python红宝书>, <Book: Python全栈开发指南>, <Book: Python全栈开发指南2>, <Book: Go全栈开发>, <Book: Go语言从入门到放弃>]>
5
(0.010) SELECT COUNT(*) AS `__count` FROM `app01_book`; args=()
(0.011) SELECT (1) AS `a` FROM `app01_book` LIMIT 1; args=()
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` LIMIT 21; args=()
[17/Aug/2018 11:13:56] "GET /index/ HTTP/1.1" 200 2
book_all <QuerySet [<Book: Python红宝书>, <Book: Python全栈开发指南>, <Book: Python全栈开发指南2>, <Book: Go语言从入门到放弃>, <Book: Go全栈开发>]>
book_exist True
Performing system checks... System check identified no issues (0 silenced).
(0.010) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.010) SHOW FULL TABLES; args=None
(0.011) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
August 17, 2018 - 11:14:37
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
42-单表操作之查询API-3
1、单表操作之查询API;
- values();
- values_list();
- distinct(),基于values()或者values_list()方法进行使用;
views.py;
from django.shortcuts import render,HttpResponse #from app01 import models
from app01.models import Book
# Create your views here.
def index(request):
#----------------------添加表记录;--------------------------#
#方式1:通过类生成对象的方法进行添加,但是需要使用save方法进行保存记录;
# book_obj = Book(id=1,title="Python红宝书",price=100,pub_date="2018-08-16",publish="人民教育出版社")
# book_obj.save()
# return HttpResponse("OK") #方式2:create是有返回值的,就是当前生成的对象的记录;
# book_obj = Book.objects.create(title="Python全栈开发指南2",price=100,pub_date="2018-08-16",publish="人民教育出版社")
# print(book_obj.title)
# print(book_obj.price)
# print(book_obj.publish)
#return HttpResponse("记录添加成功!")
#----------------------查询表记录API--------------------------#
""
"""
1、方法的返回值;
2、方法的调用者; :param request:
:return:
"""
#(1)、all查询素有结果;
book_list = Book.objects.all()
print(book_list)#ook: Book object (1)>, <Book: Book object (3)>, <Book: Book object (5)>]>,类似于列表中,放着一个个对象![obj1,obj2,.....objn]
for obj in book_list:
print("书名-书的价格",obj.title,"-",obj.price)
print('-'*20)
print("book_list[1].title",book_list[1].title)
print("book_list[1].price",book_list[1].price) #(2)、first和last方法;调用者:queryset对象;返回值:model对象;
book_first = Book.objects.all().first()
book_last = Book.objects.all().last()
print("book_first",book_first)
print("book_last",book_last)
#(3)、filter()方法,支持多条件过滤;——返回值:queryset对象;
#Book.objects.all().filter(title = "python")
Book.objects.all().filter(price = 100)#[obj1,obj2,obj3]
book_filter_first = Book.objects.filter(price=100).first()
book_filter_and = Book.objects.filter(price=100,title = "Go")
print("book_list",book_list)#<QuerySet [<Book: Python红宝书>, <Book: Python全栈开发指南>, <Book: Python全栈开发指南2>]>
print("book_filter_first",book_filter_first)
print("book_filter_and",book_filter_and)
#(4) 、get()方法;有且只有一个查询结果时候才有意义,返回值:model对象;
#book_get_title = Book.objects.get(title="go")
book_get_price = Book.objects.get(price=200)
#print("book_get_title",book_get_title)
print("book_get_price",book_get_price) #(5)、exclude过滤取反;返回值:
book_exclude = Book.objects.all().exclude(title="Go")
print("book_exclude",book_exclude)#<QuerySet [<Book: Python红宝书>, <Book: Python全栈开发指南>, <Book: Python全栈开发指南2>, <Book: Go语言从入门到放弃>, <Book: Go全栈开发>]> #(6)、order_by方法,调用者:queryset对象;返回值:queryset对象;
book_order_by_id = Book.objects.all().order_by("-id")
book_order_by_price = Book.objects.all().order_by("price")
book_order_by_price_id = Book.objects.all().order_by("price","id")
print("book_order_by_price",book_order_by_price)#ASC
print("book_order_by_id",book_order_by_id)#DESC
print("book_order_by_price_id",book_order_by_price_id)#DESC&ACS #(7)、count()方法——调用者:queryset对象,返回值:int;
book_count = Book.objects.all().count()
print(book_count) #(8)、exist()方法——返回值:布尔值,True 或者 False
book_all = Book.objects.all()#效率低下!
book_exist = Book.objects.all().exists()#效率低下!
print("book_all",book_all)
print("book_exist",book_exist)#book_exist True
#(9)、values()方法;返回值是1个列表内部嵌套字典;
#book_values = Book.objects.values()
#book_values = Book.objects.all().values("price","title")
book_values = Book.objects.all().values()
print("book_values",book_values)#book_values <QuerySet [{'id': 1, 'title': 'Python红宝书', 'pub_date': datetime.date(2018, 8, 16), 'price': Decimal('100.00'), 'publish': '人民教育出版社'}, {'id': 3, 'title': 'Python全栈开发指南', 'pub_date': datetime.date(2018, 8, 16), 'price': Decimal('100.00'), 'publish': '人民教育出版社'}, {'id': 5, 'title': 'Python全栈开发指南2', 'pub_date': datetime.date(2018, 8, 16), 'price': Decimal('100.00'), 'publish': '人民教育出版社'}, {'id': 7, 'title': 'Go语言从入门到放弃', 'pub_date': datetime.date(2018, 8, 17), 'price': Decimal('201.00'), 'publish': '清华出版社'}, {'id': 8, 'title': 'Go全栈开发', 'pub_date': datetime.date(2018, 8, 17), 'price': Decimal('200.00'), 'publish': '北大出版社'}]>
#print(book_values.get('price'))
#(11)、values_list()方法;返回值是元组;
book_values_list = Book.objects.all().values_list("price","title")
print("book_values_list",book_values_list)#book_values_list <QuerySet [(Decimal('100.00'), 'Python红宝书'), (Decimal('100.00'), 'Python全栈开发指南'), (Decimal('100.00'), 'Python全栈开发指南2'), (Decimal('201.00'), 'Go语言从入门到放弃'), (Decimal('200.00'), 'Go全栈开发')]> #(11)、distinct()方法:配合values()和values_list()方法使用; book_distinct_values = Book.objects.all().values("price").distinct()
book_distinct_values_list = Book.objects.all().values_list("price").distinct()
print("book_distinct_values",book_distinct_values)
print("book_distinct_values_list",book_distinct_values_list)
"""
book_distinct_values <QuerySet [{'price': Decimal('100.00')}, {'price': Decimal('201.00')}, {'price': Decimal('200.00')}]>
book_distinct_values_list <QuerySet [(Decimal('100.00'),), (Decimal('201.00'),), (Decimal('200.00'),)]>
"""
return HttpResponse("OK")
操作日志:
System check identified no issues (0 silenced).
(0.011) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.011) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.019) SHOW FULL TABLES; args=None
August 17, 2018 - 11:34:40
(0.012) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
(0.010) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` LIMIT 21; args=()
<QuerySet [<Book: Python红宝书>, <Book: Python全栈开发指南>, <Book: Python全栈开发指南2>, <Book: Go语言从入门到放弃>, <Book: Go全栈开发>]>
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book`; args=()
书名-书的价格 Python红宝书 - 100.00
书名-书的价格 Python全栈开发指南 - 100.00
书名-书的价格 Python全栈开发指南2 - 100.00
书名-书的价格 Go语言从入门到放弃 - 201.00
书名-书的价格 Go全栈开发 - 200.00
--------------------
book_list[1].title Python全栈开发指南
book_list[1].price 100.00
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`id` ASC LIMIT 1; args=()
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`id` DESC LIMIT 1; args=()
book_first Python红宝书
book_last Go全栈开发
book_list <QuerySet [<Book: Python红宝书>, <Book: Python全栈开发指南>, <Book: Python全栈开发指南2>, <Book: Go语言从入门到放弃>, <Book: Go全栈开发>]>
book_filter_first Python红宝书
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`price` = 100 ORDER BY `app01_book`.`id` ASC LIMIT 1; args=(Decimal(''),)
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE (`app01_book`.`price` = 100 AND `app01_book`.`title` = 'Go') LIMIT 21; args=(Decimal(''), 'Go')
book_filter_and <QuerySet []>
book_get_price Go全栈开发
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`price` = 200; args=(Decimal(''),)
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE NOT (`app01_book`.`title` = 'Go') LIMIT 21; args=('Go',)
book_exclude <QuerySet [<Book: Python红宝书>, <Book: Python全栈开发指南>, <Book: Python全栈开发指南2>, <Book: Go语言从入门到放弃>, <Book: Go全栈开发>]>
book_order_by_price <QuerySet [<Book: Python红宝书>, <Book: Python全栈开发指南>, <Book: Python全栈开发指南2>, <Book: Go全栈开发>, <Book: Go语言从入门到放弃>]>
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`price` ASC LIMIT 21; args=()
book_order_by_id <QuerySet [<Book: Go全栈开发>, <Book: Go语言从入门到放弃>, <Book: Python全栈开发指南2>, <Book: Python全栈开发指南>, <Book: Python红宝书>]>
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`id` DESC LIMIT 21; args=()
book_order_by_price_id <QuerySet [<Book: Python红宝书>, <Book: Python全栈开发指南>, <Book: Python全栈开发指南2>, <Book: Go全栈开发>, <Book: Go语言从入门到放弃>]>
(0.012) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`price` ASC, `app01_book`.`id` ASC LIMIT 21; args=()
5
(0.010) SELECT COUNT(*) AS `__count` FROM `app01_book`; args=()
(0.010) SELECT (1) AS `a` FROM `app01_book` LIMIT 1; args=()
book_all <QuerySet [<Book: Python红宝书>, <Book: Python全栈开发指南>, <Book: Python全栈开发指南2>, <Book: Go语言从入门到放弃>, <Book: Go全栈开发>]>
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` LIMIT 21; args=()
book_exist True
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` LIMIT 21; args=()
book_values <QuerySet [{'id': 1, 'title': 'Python红宝书', 'pub_date': datetime.date(2018, 8, 16), 'price': Decimal('100.00'), 'publish': '人民教育出版社'}, {'id': 3, 'title': 'Python全栈开发指南', 'pub_date': datetime.date(2018, 8, 16), 'price': Decimal('100.00'), 'publish': '人民教育出版社'}, {'id': 5, 'title': 'Python全栈开发指南2', 'pub_date': datetime.date(2018, 8, 16), 'price': Decimal('100.00'), 'publish': '人民教育出版社'}, {'id': 7, 'title': 'Go语言从入门到放弃', 'pub_date': datetime.date(2018, 8, 17), 'price': Decimal('201.00'), 'publish': '清华出版社'}, {'id': 8, 'title': 'Go全栈开发', 'pub_date': datetime.date(2018, 8, 17), 'price': Decimal('200.00'), 'publish': '北大出版社'}]>
(0.011) SELECT `app01_book`.`price`, `app01_book`.`title` FROM `app01_book` LIMIT 21; args=()
book_values_list <QuerySet [(Decimal('100.00'), 'Python红宝书'), (Decimal('100.00'), 'Python全栈开发指南'), (Decimal('100.00'), 'Python全栈开发指南2'), (Decimal('201.00'), 'Go语言从入门到放弃'), (Decimal('200.00'), 'Go全栈开发')]>
(0.011) SELECT DISTINCT `app01_book`.`price` FROM `app01_book` LIMIT 21; args=()
book_distinct_values <QuerySet [{'price': Decimal('100.00')}, {'price': Decimal('201.00')}, {'price': Decimal('200.00')}]>
book_distinct_values_list <QuerySet [(Decimal('100.00'),), (Decimal('201.00'),), (Decimal('200.00'),)]>
(0.019) SELECT DISTINCT `app01_book`.`price` FROM `app01_book` LIMIT 21; args=()
[17/Aug/2018 11:34:41] "GET /index/ HTTP/1.1" 200 2
Performing system checks... System check identified no issues (0 silenced).
(0.010) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.019) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.011) SHOW FULL TABLES; args=None
(0.011) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
August 17, 2018 - 11:35:06
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
43-单表操作之模糊查询
1、单表查询之模糊查询-基于双下划线;
Book.objects.filter(price__in=[100,200,300])
Book.objects.filter(price__gt=100)
Book.objects.filter(price__lt=100)
Book.objects.filter(price__range=[100,200])
Book.objects.filter(title__contains="python")
Book.objects.filter(title__icontains="python")
Book.objects.filter(title__startswith="py")
Book.objects.filter(pub_date__year=2012)
views.py;
#--------------------查询表记录之模糊查询--------------------------#
#大于
book_gt_lt = Book.objects.filter(price__gt =10,price__lt = 200)
print(book_gt_lt) book_price_in = Book.objects.all(price__in =[200,100])
print(book_price_in)
book_startwith = Book.objects.filter(title__startswith="p")
print(book_startwith) book_contains = Book.objects.filter(title__contains="h")
print(book_contains) book_endwith = Book.objects.filter(title__icontains="H")
print(book_endwith)
操作日志:
book_gt_lt <QuerySet [<Book: Python红宝书>, <Book: Python全栈开发指南>, <Book: Python全栈开发指南2>]>
(0.009) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE (`app01_book`.`price` > 10 AND `app01_book`.`price` < 200) LIMIT 21; args=(Decimal(''), Decimal(''))
book_price_in <QuerySet [<Book: Python红宝书>, <Book: Python全栈开发指南>, <Book: Python全栈开发指南2>, <Book: Go全栈开发>]>
(0.009) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`price` IN (200, 100) LIMIT 21; args=(Decimal(''), Decimal(''))
(0.008) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`title` LIKE BINARY 'p%' LIMIT 21; args=('p%',)
book_startwith <QuerySet []>
(0.009) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`title` LIKE BINARY '%h%' LIMIT 21; args=('%h%',)
book_contains <QuerySet [<Book: Python红宝书>, <Book: Python全栈开发指南>, <Book: Python全栈开发指南2>]>
(0.009) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`title` LIKE '%H%' LIMIT 21; args=('%H%',)
book_endwith <QuerySet [<Book: Python红宝书>, <Book: Python全栈开发指南>, <Book: Python全栈开发指南2>]>
[17/Aug/2018 12:04:29] "GET /index/ HTTP/1.1" 200 2
44-单表查询之删除与修改操作
1、单表查询之删除与修改;
- delete()方法;
- update()方法;
view.py;
# --------------------查询表记录之删除、修改记录--------------------------#
#(1)、delete()方法,删除记录;
book_delete = Book.objects.filter(price=201).delete()
print("book_delete",book_delete)#(0.010) DELETE FROM `app01_book` WHERE `app01_book`.`price` = 201; args=(Decimal('201'),) book_delete_first = Book.objects.filter(price=100).first().delete()
print("book_delete_first",book_delete_first)
#(2)update()方法,修改记录;
book_update = Book.objects.filter(title="PHP1").update(title = "《细说PHP 崔晓昭》")
print("book_update",book_update)
#新增记录;
book_obj = Book.objects.create(title="PHP4",price=101,pub_date="2018-08-17",publish="人民教育出版社1")
book_obj = Book.objects.create(title="Ruby4",price=101,pub_date="2018-08-17",publish="人民教育出版社1")
book_obj = Book.objects.create(title="R4",price=101,pub_date="2018-08-17",publish="人民教育出版社1")
"""
(0.010) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`title` LIKE '%H%' LIMIT 21; args=('%H%',)
(0.010) DELETE FROM `app01_book` WHERE `app01_book`.`price` = 201; args=(Decimal('201'),)
book_delete (0, {'app01.Book': 0})
(0.009) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`price` = 100 ORDER BY `app01_book`.`id` ASC LIMIT 1; args=(Decimal('100'),)
(0.009) DELETE FROM `app01_book` WHERE `app01_book`.`id` IN (5); args=(5,)
book_delete_first (1, {'app01.Book': 1})
(0.010) UPDATE `app01_book` SET `title` = '《细说PHP 崔晓昭》' WHERE `app01_book`.`title` = 'PHP1'; args=('《细说PHP 崔晓昭》', 'PHP1')
book_update 0
(0.019) INSERT INTO `app01_book` (`title`, `pub_date`, `price`, `publish`) VALUES ('PHP4', '2018-08-17', '101.00', '人民教育出版社1'); args=['PHP4', '2018-08-17', '101.00', '人民教育出版社1']
(0.010) INSERT INTO `app01_book` (`title`, `pub_date`, `price`, `publish`) VALUES ('Ruby4', '2018-08-17', '101.00', '人民教育出版社1'); args=['Ruby4', '2018-08-17', '101.00', '人民教育出版社1']
(0.010) INSERT INTO `app01_book` (`title`, `pub_date`, `price`, `publish`) VALUES ('R4', '2018-08-17', '101.00', '人民教育出版社1'); args=['R4', '2018-08-17', '101.00', '人民教育出版社1']
R4
[17/Aug/2018 12:16:14] "GET /index/ HTTP/1.1" 200 2
"""
print(book_obj.title)
操作日志:
(0.010) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`title` LIKE '%H%' LIMIT 21; args=('%H%',)
(0.010) DELETE FROM `app01_book` WHERE `app01_book`.`price` = 201; args=(Decimal(''),)
book_delete (0, {'app01.Book': 0})
(0.009) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`price` = 100 ORDER BY `app01_book`.`id` ASC LIMIT 1; args=(Decimal(''),)
(0.009) DELETE FROM `app01_book` WHERE `app01_book`.`id` IN (5); args=(5,)
book_delete_first (1, {'app01.Book': 1})
(0.010) UPDATE `app01_book` SET `title` = '《细说PHP 崔晓昭》' WHERE `app01_book`.`title` = 'PHP1'; args=('《细说PHP 崔晓昭》', 'PHP1')
book_update 0
(0.019) INSERT INTO `app01_book` (`title`, `pub_date`, `price`, `publish`) VALUES ('PHP4', '2018-08-17', '101.00', '人民教育出版社1'); args=['PHP4', '2018-08-17', '101.00', '人民教育出版社1']
(0.010) INSERT INTO `app01_book` (`title`, `pub_date`, `price`, `publish`) VALUES ('Ruby4', '2018-08-17', '101.00', '人民教育出版社1'); args=['Ruby4', '2018-08-17', '101.00', '人民教育出版社1']
(0.010) INSERT INTO `app01_book` (`title`, `pub_date`, `price`, `publish`) VALUES ('R4', '2018-08-17', '101.00', '人民教育出版社1'); args=['R4', '2018-08-17', '101.00', '人民教育出版社1']
R4
[17/Aug/2018 12:16:14] "GET /index/ HTTP/1.1" 200 2
45-单表操作章节作业
1、查询老男孩出版社过的价格大于200的书籍;
2、查询2017年8月出版的所有以py开头的书籍的名称;
3、查询价格为50,100或150的所有书籍名称及其出版社名称;
4、查询价格在100到200之间的所有书籍的名称及其价格;
5、查询所有人民出版社的书籍的价格,(从高到低排序、去重);
46-单表操作章节作业讲解
1、查询老男孩出版社过的价格大于200的书籍;
2、查询2017年8月出版的所有以py开头的书籍的名称;
3、查询价格为50,100或150的所有书籍名称及其出版社名称;
4、查询价格在100到200之间的所有书籍的名称及其价格;
5、查询所有人民出版社的书籍的价格,(从高到低排序、去重);
views.py;
from django.shortcuts import render,HttpResponse #from app01 import models
from app01.models import Book
# Create your views here.
"""
1、查询老男孩出版社过的价格大于200的书籍;
2、查询2017年8月出版的所有以py开头的书籍的名称;
3、查询价格为50,100或150的所有书籍名称及其出版社名称;
4、查询价格在100到200之间的所有书籍的名称及其价格;
5、查询所有人民出版社的书籍的价格,(从高到低排序、去重);
""" def query(request):
book_01 = Book.objects.filter(price__gt=200,publish = "人民教育出版社1")
print("1、查询老男孩出版社过的价格大于200的书籍;",book_01) book_02 = Book.objects.filter(title__istartswith="py",pub_date__year = 2018,pub_date__month=8)
print("2、查询2017年8月出版的所有以py开头的书籍的名称;",book_02) book_03 = Book.objects.all().filter(price__in=[50,100,150]).values("title","publish")
print("3、查询价格为50,100或150的所有书籍名称及其出版社名称;",book_03) book_04 = Book.objects.all().filter(price__range=[100,200]).values("title","price")
print("4、查询价格在100到200之间的所有书籍的名称及其价格;",book_04) book_05 = Book.objects.all().filter(publish="人民教育出版社1").values("price").distinct().order_by("price")
print("5、查询所有人民出版社的书籍的价格,(从高到低排序、去重);",book_05) return HttpResponse("Query OK")
操作日志:
System check identified no issues (0 silenced).
(0.010) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.010) SHOW FULL TABLES; args=None
August 18, 2018 - 10:31:09
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
(0.019) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
(0.011) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.011) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
1、查询老男孩出版社过的价格大于200的书籍; <QuerySet []>
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE (`app01_book`.`price` > 200 AND `app01_book`.`publish` = '人民教育出版社1') LIMIT 21; args=(Decimal(''), '人民教育出版社1')
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE (EXTRACT(MONTH FROM `app01_book`.`pub_date`) = 8 AND `app01_book`.`pub_date` BETWEEN '2018-01-01' AND '2018-12-31' AND `app01_book`.`title` LIKE 'py%') LIMIT 21; args=(8, '2018-01-01', '2018-12-31', 'py%')
2、查询2017年8月出版的所有以py开头的书籍的名称; <QuerySet [<Book: python>, <Book: Python全栈开发与实战>]>
(0.011) SELECT `app01_book`.`title`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`price` IN (50, 100, 150) LIMIT 21; args=(Decimal(''), Decimal(''), Decimal(''))
3、查询价格为50,100或150的所有书籍名称及其出版社名称; <QuerySet [{'title': 'PHP2', 'publish': '人民教育出版社1'}, {'title': 'R3', 'publish': '人民教育出版社1'}, {'title': 'Ruby4', 'publish': '人民教育出版社1'}]>
4、查询价格在100到200之间的所有书籍的名称及其价格; <QuerySet [{'title': 'Go全栈开发', 'price': Decimal('200.00')}, {'title': 'Ruby', 'price': Decimal('101.00')}, {'title': 'R', 'price': Decimal('101.00')}, {'title': 'python', 'price': Decimal('101.00')}, {'title': 'R1', 'price': Decimal('101.00')}, {'title': 'R3', 'price': Decimal('150.00')}, {'title': 'Python全栈开发与实战', 'price': Decimal('101.00')}, {'title': 'Ruby4', 'price': Decimal('100.00')}, {'title': 'R4', 'price': Decimal('101.00')}]>
(0.011) SELECT `app01_book`.`title`, `app01_book`.`price` FROM `app01_book` WHERE `app01_book`.`price` BETWEEN 100 AND 200 LIMIT 21; args=(Decimal(''), Decimal(''))
(0.011) SELECT DISTINCT `app01_book`.`price` FROM `app01_book` WHERE `app01_book`.`publish` = '人民教育出版社1' ORDER BY `app01_book`.`price` ASC LIMIT 21; args=('人民教育出版社1',)
[18/Aug/2018 10:31:52] "GET /query/ HTTP/1.1" 200 8
5、查询所有人民出版社的书籍的价格,(从高到低排序、去重); <QuerySet [{'price': Decimal('50.00')}, {'price': Decimal('88.00')}, {'price': Decimal('99.00')}, {'price': Decimal('100.00')}, {'price': Decimal('101.00')}, {'price': Decimal('150.00')}]>
47-图书管理系统之添加页面
1、新建项目bookms并创建应用文件app01;
2、检查settings.py文件;
3、导入app01下的views模块并配置urls.py,新增"addbook/";
from django.contrib import admin
from django.urls import path from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('addbook/', views.addbook),
]
4、编写views.py业务逻辑代码;
from django.shortcuts import render,HttpResponse # Create your views here. from app01.models import Book
def addbook(request):
if request.method == "POST":
title = request.POST.get("title")
price = request.POST.get("price")
date = request.POST.get("date")
publish = request.POST.get("publish") book_obj = Book.objects.create(title=title,price=price,pub_date=date,publish=publish)
return HttpResponse("OK") return render(request,"addbook.html")
5、编写addbook.html页面并引入css文件;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title> {# <link rel="stylesheet" href="/app01/static/bootstrap-3.3.7-dist/css/bootstrap.css">#}
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<style>
.container{
margin-top: 100px;
}
.btn{
margin-top: 10px;
}
</style>
</head>
<body> <h3>添加书籍</h3> <div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form action="" method="post">
{% csrf_token %}
<div>
<label for="">书籍名称</label>
<input type="text" class="form-control" name="title">
</div>
<div>
<label for="">价格</label>
<input type="text" class="form-control" name="price">
</div>
<div>
<label for="">出版日期</label>
<input type="date" class="form-control" name="date">
</div>
<div>
<label for="">出版社</label>
<input type="text" class="form-control" name="publish">
</div> <input type="submit" class="btn btn-success pull-right"> </form>
</div>
</div>
</div> </body>
</html>
6、编写models.py数据库文件;
from django.db import models # Create your models here.
class Book(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=32)
pub_date = models.DateField()
price = models.DecimalField(max_digits=8,decimal_places=2)
publish = models.CharField(max_length=32)
7、执行迁移数据库操作并启动Django项目进行访问;
python manage.py makemigrations python manage.py migrate
8、查看Django框架中自带的sqllite3数据库的数据;
9、通过Pycharm IDE工具自带的数据库连接工具,进行数据查看;
1) 初次使用,使用Pycharm下载sqllite驱动程序;
2)寻找本地db.sqllite3文件,进行连接验证;
C:\Users\TQTL911\PycharmProjects\bookms\db.sqlite3
3)初识jdbc数据库连接;
jdbc:sqlite:C:\Users\TQTL911\PycharmProjects\bookms\db.sqlite3
4)使用Test Connection按钮,进行测试连接;
48-图书管理系统之查看书籍
1、新增urls.py中的path路径;
"""book URL Configuration The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('addbook/', views.addbook),
path('books/', views.books),
]
2、编辑views.py下的业务逻辑代码;
from django.shortcuts import render,HttpResponse # Create your views here. from app01.models import Book
def addbook(request):
if request.method == "POST":
title = request.POST.get("title")
price = request.POST.get("price")
date = request.POST.get("date")
publish = request.POST.get("publish")
book_obj = Book.objects.create(title=title,price=price,pub_date=date,publish=publish)
return HttpResponse("addbook is OK")
return render(request,"addbook.html") def books(request):
book_list = Book.objects.all()#
return render(request,"books.html",locals())
3、编辑前端books.html页面代码;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title> {# <link rel="stylesheet" href="/bookms/app01/static/bootstrap-3.3.7-dist/">#}
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<style>
.container{
margin-top: 100px;
}
.btn{
margin-top: 10px;
}
</style>
</head>
<body> <h3>查看书籍</h3> <div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>书籍名称</th>
<th>价格</th>
<th>出版日期</th>
<th>出版社</th>
<th>删除操作</th>
<th>编辑出版社</th>
</tr>
</thead>
<tbody>
{% for book in book_list %}
<tr>
<td>{{ book.title }}</td>
<td>{{ book.price }}</td>
<td>{{ book.pub_date|date:'Y-m-d' }}</td>
<td>{{ book.publish }}</td>
<td><a href="" class="btn btn-danger">删除</a></td>
<td><a href="" class="btn btn-info">编辑</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div> </body>
</html>
4、进行查看页面展示效果;
49-图书管理系统之删除数据
1、urls.py中新增re_path路径;
from django.contrib import admin
from django.urls import path,re_path from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('addbook/', views.addbook),
path('books/', views.books),
re_path(r'books/(\d+)/delete',views.delbook),#delbook(request,x)
]
2、views.py视图函数中添加delbook功能代码;
from django.shortcuts import render,HttpResponse,redirect
# Create your views here. from app01.models import Book
def addbook(request):
if request.method == "POST": title = request.POST.get("title")
price = request.POST.get("price")
pub_date = request.POST.get("date")
publish = request.POST.get("publish")
book_obj = Book.objects.create(title=title,price=price,pub_date=pub_date,publish=publish)
return redirect("/addbook/")
return render(request,"addbook.html") def books(request):
book_list = Book.objects.all()
return render(request,"books.html",locals()) def delbook(request,id):
Book.objects.filter(id=id).delete()
return redirect("/books/")
3、books.html中分别添加一个删除、编辑按钮;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title> {# <link rel="stylesheet" href="/bookms/app01/static/bootstrap-3.3.7-dist/">#}
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<style>
.container{
margin-top: 100px;
}
.btn{
margin-top: 10px;
}
</style>
</head>
<body> <h3>查看书籍</h3> <div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<a href="/addbook" class="btn btn-primary">添加书籍</a>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>书籍名称</th>
<th>价格</th>
<th>出版日期</th>
<th>出版社</th>
<th>删除操作</th>
<th>编辑出版社</th>
</tr>
</thead>
<tbody>
{% for book in book_list %}
<tr>
<td>{{ book.title }}</td>
<td>{{ book.price }}</td>
<td>{{ book.pub_date|date:'Y-m-d' }}</td>
<td>{{ book.publish }}</td>
<td><a href="/books/{{ book.pk }}/delete" class="btn btn-danger">删除</a></td>
<td><a href="" class="btn btn-info">编辑</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div> </body>
</html>
4、添加或删除后通过redirect()方法,重定向至某个页面;
return redirect("/addbook/")
return redirect("/books/")
5、检查页面重定向跳转以及页面按钮是否可见;
50-图书管理系统之编辑功能
1、urls.py中新增re_path路径;
"""book URL Configuration The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,re_path from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('addbook/', views.addbook),
path('books/', views.books),
re_path(r'books/(\d+)/delete',views.delbook),#delbook(request,x)
re_path(r'books/(\d+)/modify',views.modbooks),#modbook(request,x)
]
2、views.py视图函数中添加modbooks功能代码;
from django.shortcuts import render,HttpResponse,redirect
# Create your views here. from app01.models import Book
def addbook(request):
if request.method == "POST": title = request.POST.get("title")
price = request.POST.get("price")
pub_date = request.POST.get("date")
publish = request.POST.get("publish")
book_obj = Book.objects.create(title=title,price=price,pub_date=pub_date,publish=publish)
return redirect("/addbook/")
return render(request,"addbook.html") def books(request):
book_list = Book.objects.all()
return render(request,"books.html",locals()) def delbook(request,id):
Book.objects.filter(id=id).delete()
return redirect("/books/") def modbooks(request,id):
book_obj = Book.objects.filter(id=id).first()
if request.method == "POST":
title = request.POST.get("title")
price = request.POST.get("price")
pub_date = request.POST.get("date")
publish = request.POST.get("publish")
book_obj = Book.objects.filter(id=id).update(title=title, price=price, pub_date=pub_date, publish=publish)
return redirect("/books/")
return render(request, "modbooks.html", {"book_obj":book_obj})
3、modbooks.html中分别添加一个删除、编辑按钮;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title> <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
{# <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">#}
<style>
.container{
margin-top: 100px;
}
.btn{
margin-top: 10px;
}
</style>
</head>
<body> <h3>编辑书籍</h3> <div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form action="" method="post">
{% csrf_token %}
<div>
<label for="">书籍名称</label>
<input type="text" class="form-control" name="title" value="{{ book_obj.title }}">
</div>
<div>
<label for="">价格</label>
<input type="text" class="form-control" name="price" value="{{ book_obj.price }}">
</div>
<div>
<label for="">出版日期</label>
<input type="date" class="form-control" name="date" value="{{ book_obj.pub_date|date:"Y-m-d" }}">
</div>
<div>
<label for="">出版社</label>
<input type="text" class="form-control" name="publish" value="{{ book_obj.publish }}">
</div>
<input type="submit" class="btn btn-success pull-right"> </form>
</div>
</div>
</div> </body>
</html>
4、修改后通过redirect()方法,重定向至books页面;
return redirect("/books/")
return render(request, "modbooks.html", {"book_obj":book_obj})
5、检查页面重定向跳转以及页面按钮是否可见;
第六模块:WEB框架开发 第1章·Django框架开发1~50的更多相关文章
- 第六模块:WEB框架开发 第1章·Django框架开发88~128
88-Ajax简介 89-Ajax的简单实现 90-基于Ajax的传递数据 91-基于Ajax的登录验证 92-基于Form表单的文件上传 93-请求头之contentType 94-Ajax传递js ...
- 第六模块:WEB框架开发 第1章·Django框架开发50~87
51-表关系之一对多 52-表关系之多对多 53-表关系之一对一 54-数据库表关系之关联字段与外键约束 55-数据库表关系之sql创建关联表 56-ORM生成关联表模型 57-多表操作之一对多添加记 ...
- 第四模块:网络编程进阶&数据库开发 第2章·MySQL数据库开发
01-MySQL开篇 02-MySQL简单介绍 03-不同平台下安装MySQL 04-Windows平台MySQL密码设置与破解 05-Linux平台MySQL密码设置与破解 06-Mac平台MySQ ...
- Python学习笔记_04:Django框架简介
目录 1 什么是Django? 2 Django框架的开发环境搭建 3 Django操作MySql数据库简介 4 功能强大的Django管理工具应用 1 什么是Django? Django是应用于We ...
- python 之 Django框架(服务器程序和应用程序、基础必备三件套及相关配置)
第十二章 Django框架 12.1 服务器程序和应用程序 服务器程序负责对socket服务器进行封装,并在请求到来时,对请求的各种数据进行整理.应用程序则负责具体的逻辑处理.为了方便应用程序的开发, ...
- python主流框架简介和Django框架的使用
目录 一.手撸简易web框架 二.动静态网页 1. 静态网页 2. 动态网页 三.jinja2模板语法 1. jinja2的作用 四.python主流web框架 1. django 3. tornad ...
- 分布式队列celery 异步----Django框架中的使用
仅仅是个人学习的过程,发现有问题欢迎留言 一.celery 介绍 celery是一种功能完备的即插即用的任务对列 celery适用异步处理问题,比如上传邮件.上传文件.图像处理等比较耗时的事情 异步执 ...
- MySQL在Django框架下的基本操作(MySQL在Linux下配置)
[原]本文根据实际操作主要介绍了Django框架下MySQL的一些常用操作,核心内容如下: ------------------------------------------------------ ...
- Django框架数据库模型
博主最近开始优化之前的API接口自动化框架,这次打算使用django框架来完成 # -*- coding: utf-8 -*- from __future__ import unicode_liter ...
随机推荐
- 学习openGL-windows环境配置
windows对openGL的支持直到1.1,而如今openGL版本已经更新到4.5,为了使用高版本的API,需要安装拓展库(glew). openGL只是个渲染系统,但是它不能产生窗口,需要依赖其它 ...
- Excel批量导入商品,遇到导入失败记录到另一个Excel中供下载查看
/// <summary> /// EXCEL批量导入 /// </summary> /// <param name="filePath">文件 ...
- redux和react-redux的使用详解
我自己的理解redux就跟vue中的vuex差不多,都是数据管理器,话不多说,我们从经典的计数器案例开始讲解 使用redux实现计数器 创建如下的react项目,我习惯把每一个模块分块,才有这么多文件 ...
- 关于Hibernate基于version的乐观锁
刚刚接触SSH框架,虽然可能这个框架已经比较过时了,但是个人认为,SSH作为一个成熟的框架,作为框架的入门还是可以的. 马马虎虎学完了Hibernate的基础,总结一点心得之类的. 学习Hiberna ...
- mysql如何配置sql记录
原文链接:http://www.qqdeveloper.com/detail/11/1.html 为什么要记录sql记录 主要目的是为了检测我们的网站安全问题,有效的避免一些sql注入或者是xss攻击 ...
- js加载等待效果
demo01: 加载首页的时候,可能会很缓慢,放一张等待图片. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN ...
- Asp.Net Core使用Log4Net优化日志【项目开源】
我在前一篇文章中介绍了一种使用Log4Net的方法,但是那种方法打出来的日志不是很直观 然后我前不久阅读了一篇非常不错的博客:https://www.cnblogs.com/guolianyu/p/9 ...
- 【Java】集合概述Collection、Map
Java集合分为Collection和Map,Collection又分为List.Set. List中有ArrayList.LinkedList和Vector:Set中又分为HashSet和TreeS ...
- 论反向ajax
在讨论反向ajax之前,说一下我大二写的一个聊天程序,通过前端ajax不断向服务器发送请求(通过http连接),服务器进行一次数据库查询,然后返回结果,断开与服务器的链接(绝大部分都是无用的结果)来维 ...
- 关于PHPExcel 导出下载表格,调试器响应乱码
PHPExcel导出表格是日常程序开发很常见的一功能,有些小伙伴千辛万苦把代码写好之后,运行一下结果发现浏览器没反应,表格下载不了或者表格乱码!!!像这种情况有三种解决方法: 1.在header 之前 ...