环境:
python 3.9
Django 3
pycharm

在此处选择项目的存放地址以及python的开发版本

先忽视下 apps文件夹,后面会讲到
manage.py 【项目的管理,启动项目、创建app、数据管理】【不要动】【常常用】
└── Django
├── init.py
├── settings.py 【项目配置】 【常常修改】
├── urls.py 【URL和函数的对应关系】【常常修改】
├── asgi.py 【接收网络请求】【不要动】
└── wsgi.py 【接收网络请求】【不要动】
一个app就是一个功能模块,比如:用户管理、用户管理都是一个app
python manage.py startapp app01 刷新项目
此时便可以看到 app01的文件夹,这就是一个app

├── app01 app的名称
│ ├── init.py
│ ├── admin.py 【固定,不用动】django默认提供了admin后台管理。
│ ├── apps.py 【固定,不用动】app启动类
│ ├── migrations 【固定,不用动】数据库变更记录
│ │ └── init.py
│ ├── models.py 【重要】,对数据库操作。
│ ├── tests.py 【固定,不用动】单元测试
│ └── views.py 主要进行业务操作
上面只是创建了一个app但是并没有注册进我们的Django 项目
确保app已注册 【settings.py】在INSTALLED_APPS 中添加 ‘app01.apps.App01Config’


因为 新创建的app 的启动类的路径是 app01.apps.App01Config
首先在 根目录的 urls.py中,配置请求路由和对应的业务代码地址

路由地址是 127.0.0.1:8000/index ,对应的业务在 app01下的views的index函数【from app01 import view】

启动项目:python manage.py runserver
或者 pycharm的启动

定义好路由和业务
path('getUserList', views.getUserList),
render(request,“user_list.html”) 返回html页面
# 返回对应的 html页面
def getUserList(request):
return render(request, "user_list.html")
app01下新建一个templates文件夹,新建user_list.html 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
</head>
<body>
</body>
</html>
项目寻找 user_list.html 文件的顺序:优先到根目录中的templates 下查找,否则根据配置文件的中注册的 app的注册顺序,逐一去他们的 templates 目录查找

1、首先在 app01下新建文件 urls.py文件 在这个里面写 这个app的路由
# 指定当前 app的命名
from django.urls import path
from app01 import views
app_name = "app01"
urlpatterns = [
# path('admin/', admin.site.urls),
path('index', views.index),
path('getUserList', views.getUserList),
path('startRequest', views.startRequest),
path('ORM', views.orm),
]
2、在根目录中的urls中配置app01的路由
from django.contrib import admin
from django.urls import path, include
from app01 import views
urlpatterns = [
path('demo/', include("app01.urls"))
]
此时的hello的程序路由是
http://127.0.0.1:8000/demo/index 根目录的路由+对应app的路由

request.method
GET: request.GET
POST: request.POST
# 可以通过request对象拿到请求的所有数据
if request.method == 'GET': # 大写
return HttpResponse(" You're at the polls login.GET请求")
elif request.method == 'POST':
return HttpResponse(" You're at the polls login.POST请求")
else:
return HttpResponse(" You're at the polls login.其它请求")
import pymysql
# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', passwd="root123", charset='utf8', db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 2.发送指令
cursor.execute("insert into admin(username,password,mobile) values('wupeiqi','qwe123','15155555555')")
conn.commit()
# 3.关闭
cursor.close()
conn.close()
其中Django内置了ORM ,他的作用是:
创建、修改、删除数据库,对表的操作:不需要写sql。
安装组件:pip install mysqlclient
1、在根目录下的setting配置文件中配置mysql路径地址
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 驱动`在这里插入代码片`
'NAME': 'school', # 数据库名字
'USER': 'root',
'PASSWORD': '123456',
'HOST': '127.0.0.1', # 那台机器安装了MySQL
'PORT': 3306,
}
}
2、在 app下的models文件中写入
from django.db import models
class UserInfo(models.Model):
name = models.CharField(max_length=32)
class Aaa(models.Model):
name = models.CharField(max_length=32,verbose_name="姓名")
age = models.IntegerField(max_length=10)
create_time = models.DateTimeField
count = models.DecimalField(verbose_name="账户余额", max_digits=10, decimal_places=2, default=0)
del_flag = models.IntegerField(max_length=2,default=1)
3、在pycharm的 terminal中分别输入
python manage.py makemigrations
python manage.py migrate
看下数据库,多了两张表


经测试:在 models中的已有表类中,新增或者修改列时,不生效!!!!!!!!!!!!
以后在开发中如果想要对表结构进行调整:
在models.py文件中操作类即可。
命令
python manage.py makemigrations
python manage.py migrate
注意注意注意:提前将pycharm的编码改为 utf-8,否则会报错
遇到的问题解决
python manage.py inspectdb (‘表名,可不写’)> app名/models.py
等一会 ,才会有
1、增:
UserInfo.objects.create(name="武沛齐")
UserInfo.objects.create(name="朱虎飞")
UserInfo.objects.create(name="吴阳军")
2、删除
UserInfo.objects.filter(id=3).delete() # 删除 id = 3
3、修改
UserInfo.objects.all().update(name=999) #修改所以
UserInfo.objects.filter(id=2).update(name=999)# 修改id=2
UserInfo.objects.filter(name="朱虎飞").update(name=999)# 修改 name = 朱虎飞
4、查询
查询条件放进字典
data_dict = {"name":"lsl","id":1}
UserInfo.objects.filter(**data_dict)
UserInfo.objects.filter(id=12) # 等于12
UserInfo.objects.filter(id__gt=12) # 大于12
UserInfo.objects.filter(id__gte=12) # 大于等于12
UserInfo.objects.filter(id__lt=12) # 小于12
UserInfo.objects.filter(id__lte=12) # 小于等于12
UserInfo.objects.filter(mobile__startswith="1999") # 筛选出以1999开头
UserInfo.objects.filter(mobile__endswith="999") # 筛选出以999结尾
UserInfo.objects.filter(mobile__contains="999") # 筛选出包含999
分页查询
queryset = models.PrettyNum.objects.all().order_by("id")
queryset = models.PrettyNum.objects.filter(id=1).order_by("id")[0:10]
# 第1页
queryset = models.PrettyNum.objects.all().order_by("id")[0:10]
# 第2页
queryset = models.PrettyNum.objects.all().order_by("id")[10:20]
# 第3页
queryset = models.PrettyNum.objects.all().order_by("id")[20:30]
查询数量
data = models.PrettyNum.objects.all().count()
data = models.PrettyNum.objects.filter(id=1).count()

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
# 中间件1
class M1(MiddlewareMixin):
def process_request(self, request):
print("M1 comming")
def process_response(self, request, response):
print("M1 outting")
return response
# 中间件1
class M2(MiddlewareMixin):
def process_request(self, request):
print("M2 comming")
def process_response(self, request, response):
print("M2 outting")
return response
新建一个拦截器文件,创建两个拦截器类对象 每个请求都会走进这里

'app01.miiddleware.auth.M1',
'app01.miiddleware.auth.M2',
在项目的 配置文件中配置这个拦截器 M1在前就会先执行 M1
随意访问一个请求:

在process_request 中 如果没有返回值则继续执行,有返回值 则返回 HttpResponse
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
# 中间件1
class M1(MiddlewareMixin):
def process_request(self, request):
# 如果没有返回值则继续执行,有返回值 则返回 HttpResponse
print("M1 comming")
return HttpResponse("err")
def process_response(self, request, response):
print("M1 outting")
return response
# 中间件1
class M2(MiddlewareMixin):
def process_request(self, request):
print("M2 comming")
def process_response(self, request, response):
print("M2 outting")
return response
结果:


不会再进入 M2
参考这个
其中的字体我们在 c:// windows/font下有很多自提可以复制道到项目根目录下

import random
from PIL import Image, ImageDraw, ImageFont, ImageFilter
def check_code(width=120, height=30, char_length=5, font_file='simsun.ttc', font_size=28):
code = []
img = Image.new(mode='RGB', size=(width, height), color=(255, 255, 255))
draw = ImageDraw.Draw(img, mode='RGB')
def rndChar():
"""
生成随机字母
:return:
"""
return chr(random.randint(65, 90))
def rndColor():
"""
生成随机颜色
:return:
"""
return (random.randint(0, 255), random.randint(10, 255), random.randint(64, 255))
# 写文字
font = ImageFont.truetype(font_file, font_size)
for i in range(char_length):
char = rndChar()
code.append(char)
h = random.randint(0, 4)
draw.text([i * width / char_length, h], char, font=font, fill=rndColor())
# 写干扰点
for i in range(40):
draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())
# 写干扰圆圈
for i in range(40):
draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())
x = random.randint(0, width)
y = random.randint(0, height)
draw.arc((x, y, x + 4, y + 4), 0, 90, fill=rndColor())
# 画干扰线
for i in range(5):
x1 = random.randint(0, width)
y1 = random.randint(0, height)
x2 = random.randint(0, width)
y2 = random.randint(0, height)
draw.line((x1, y1, x2, y2), fill=rndColor())
img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
return img, ''.join(code)
if __name__ == '__main__':
img,code = check_code()
print(code)
with open('code.png', 'wb') as f:
img.save(f,format='png')
# 1. 直接打开
# img,code = check_code()
# img.show()
# # 2. 写入文件
# img,code = check_code()
# with open('code.png','wb') as f:
# img.save(f,format='png')
# 3. 写入内存(Python3)
# from io import BytesIO
# stream = BytesIO()
# img.save(stream, 'png')
# stream.getvalue()
# 4. 写入内存(Python2)
# import StringIO
# stream = StringIO.StringIO()
# img.save(stream, 'png')
# stream.getvalue()
结果: 随机码 打印为TFBAG
