---------------https://www.cnblogs.com/yuanchenqi/articles/8875659.html
一、python的web框架
flask --- 小项目
django ---- 大项目
二、django基础
(1)、web服务的本质
网络编程都是基于套接字socket编程,不分语言
client ---- server
BS架构
browser ------ server
import socket sock=socket.socket() sock.bind(("127.0.0.1",8800)) sock.listen(5) while 1 : conn,addr=sock.accept() data=conn.recv(1024) print("data",data) with open('index.html',"rb") as f: html=f.read() conn.send(b'HTTP/1.1 200 OK %s'%html) conn.close()
(2)、django的介绍,下载,实例
下载pip install django
创建项目 django-admin start project mysite
生成app python manage.py startapp app01
mysite
----- mysite
----- settings 项目配置文件
------ urls 路径与视图函数的映射关系
----- wsgi 封装的socket
------ manage.py django项目进行交互的脚本
----- app01(项目应用)
-----models 数据库操作
-----views 视图函数
-----templates
login.html
(3)、MTV(MVC)
M models :负责业务对象和数据库的关系映射(ORM)
T Template : 负责如何 把页面展示给用户(HTML)
V views : 负责业务逻辑,并在适当时候调用Model 和 Template
(4)、URL
url: 协议://IP(域名):端口(80)/路径/?GET参数
https://www.jd.com/
https://127.0.0.1:8000/books/1/?x=123
功能:url的路径和视图函数的映射关系
url的简单应用
from django.conf.urls import url,include from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), # url(r'^articles/2003/$', views.special_case_2003), # special_case_2003(request) # url(r'^articles/(d{4})/$', views.article_year), # article_year(request,2004) # # url(r'^articles/(d{4})/(d{2})$', views.article_yearmonth), # article_year(request,2004,12) # # 有名分组 # url(r'^articles/(?P<year>d{4})/(?P<month>d{2})$', views.article_yearmonth2), # article_year(request,year=2004,month=12) # 分发 url(r'^app01/', include('app01.urls')), # 反射 url(r'^login/', views.login,name="xxxxxx") ] ''' import re re.findall("规则","待匹配字符串") ret=re.findall("^articles/2003/$","该请求的url的路径") if ret: views.special_case_2003(request) '''
url的有名分组
url的分发
url的反射
在有时需要改变url名称的时候,采用别名方便修改
# 反射 url(r'^login/', views.login,name="xxxxxx") HTML <form action="{% url 'xxxxxx' %}" method="post"> ... ... </form>
(5)、View
------------https://www.cnblogs.com/yuanchenqi/articles/7629939.html
1、render的方法功能
return render(request,“login.html”)
按着settings指定路径找到对应的login.html,读取文件内容,构建 return HttpsResponse(文件字符串)
return render(request,“login.html”,{"name":wudi})
按着setting指定路径找到对应的login.html,读取文件内容,进行渲染,把文件字符串中所有{{}}的内容按着,{"name":wudi}替换,将新的替换字符串 建 HttpResponse(新的文件字符串)
2、print(request.GET)
print(request.POST)
print(request.method)
print(request.path)
print(request.get_full_path)
django必须响应一个HttpResponse对象
HttpResponse:响应字符串
render: 响应模板
redirect: 重定向
(6)、Template
模板语法
1、变量
1、1深度查询: 使用句点符号
views: 1、L1 = [11,22,33] 2、L2 = {'name':name,'age':age'} 3、class Person(object): def __init__(self,name,age): self.name = name self.age = age agon = Person('egon',18) alex = Person('alex',22) L3 = [egon,alex] templates 1、{{L1.1}} 2、{{L2.name}} 3、{{L3.1.name}} {{L3.1.name.2}} 字符串也可以深度查询到
return render(request,'index.html',{'name':name..........................})换成 return render(request,'index.html',locals())
locals()可以帮函数下的所有变量上传到templates,测试用,开发尽量少用
1、2 过滤器
格式: {{val|fileter_name:参数}}
templates: {{count|add:20}} {{time|date:'Y:m:d h:i'}} {{t1|default:"不存在值"}} {{a|safe}} 浏览器对标签默认转义,加上safe后则不转义 {{str|slice:"0:2"}} {{p|truncatechars:200}} {{a|truncatewords:2}}
2、标签
for
if
{% for i in nums %} <p> {{i}} </p> {% endfor % ----------------------------forloop.counter------------ <ul> {% for i in nums %} <li> {{ forloop.counter }}{{i}} </li> {% endfor % </ul> -----------------------------items ------------------ <ul> {% for k,v in nums.items %} <li> {{ k }}----{{v }} </li> {% endfor % </ul> ------------------------------------------------------ .. {{forloop.counter0}}、 {{forloop.first}}判断是否为第一个,是则为True、 {{forloop.last}}
if和for连用的语法
{% for k in nums%} {% if k > 0%} <p>{{ k }}</p> {% endif %} {% endfor %}
(7)、静态文件的配置
在settings文件里配置
项目部署之后,ningx作为静态文件的主载栈,最后放在apachix和ningx上去
settings.py 别名 STATIC_URL = '/static/' 文件实际存在目录 STATICFILES_DIRS = [os.path.join(BAES_PATH,"static"),]
引用网上jquery的CDN服务器:bootcdn比较稳定 <script src=""></script> <h4 class="btn">深度查询</h4> <div class="con"> <h6>sds</h6> <h6>sds</h6> <h6>sds</h6> </div> <script> $('btn').click(function () { $('.con').toggle() }) </script>
(8)、继承
shopper.html: {% extends "login.html" %} {% block content %} <p>hahh</p> {% endblock content %} base.html: {% block content %} <p>hahh</p> {% endblock content %}
-----------------------------super--------------------
shopper.html:
{% block content %}
<p>hahh</p>
<div> {{ block.super }} </div> -----合并父类的div,不覆盖
{% endblock content %}
(9)、a标签的功能
<div><a href="/login/">点我</a></div>
(10)、ORM(单表操作)
python manage.py makemigrations
python manage.py migrate
1、数据库配置 # Database # https://docs.djangoproject.com/en/1.11/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', 'NAME':'s1orm', # 要连接的数据库,连接前需要创建好 'USER':'root', # 连接数据库的用户名 'PASSWORD':'123', # 连接数据库的密码 'HOST':'127.0.0.1', # 连接主机,默认本级 'PORT':3306# 端口 默认3306 } } init.py: import pymysql pymysql.install_as_MySQLdb() urls.py: from django.conf.urls import url from django.contrib import admin views.py: # 添加数据 # Book.objects.create(title="linux",pub_date="2012-12-12",price=122,publish="人民出版社") # 查看所有书籍 # book_list=Book.objects.all() # [obj1,obj2,obj3] # for book in book_list: # print(book.title) # 删除 Book.objects.filter(id=1,title="python").delete() 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)
书籍管理小型项目
urls.py from django.conf.urls import url from django.contrib import admin from book import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^addbook/$', views.addbook), url(r'^books/$', views.books), url(r'^books/delete/(?P<id>d+)/$', views.deletebooks), ]
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)
views.py
from django.shortcuts import render,HttpResponse,redirect
# Create your views here.
from book.models import Book
def addbook(request):
if request.method=="GET":
return render(request,"addbook.html")
else:
title=request.POST.get("title")
price=request.POST.get("price")
pub_date=request.POST.get("pub_date")
publish=request.POST.get("publish")
Book.objects.create(title=title,
publish=publish,
price=price,
pub_date=pub_date)
return redirect("/books/")
def books(request):
book_list=Book.objects.all()
return render(request,'books.html',{"book_list":book_list})
def deletebooks(request,id):
Book.objects.filter(id=id).delete()
Book.objects.filter(id=id).update(titile="123")
return redirect("/books/")
addbook.html: <form action="/addbook/" method="post"> <p>书籍名称 <input type="text" name="title"></p> <p>价格 <input type="text" name="price"></p> <p>出版日期 <input type="date" name="pub_date"></p> <p>出版社 <input type="text" name="publish"></p> <input type="submit"> </form> books.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head> <body> <h3>图书列表</h3> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div> <a href="/addbook/">添加书籍</a> <table class="table table-bordered table-striped table-hover"> <thead> <tr> <th>序号</th> <th>书籍名称</th> <th>价格</th> <th>日期</th> <th>出版社</th> <th>操作</th> </tr> </thead> <tbody> {% for book in book_list %} <tr> <td>{{ forloop.counter }}</td> <td>{{ book.title }}</td> <td>{{ book.price }}</td> <td>{{ book.pub_date }}</td> <td>{{ book.publish }}</td> <td> <a href="/books/delete/{{ book.id }}" class="btn-sm btn-danger">删除</a> </td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> </div> </body> </html>
三、django 重点
(1)、ORM多表操作
(2)、Django组件:
forms组件
cookie与session
中间件
Ajax($.ajax())