django 开端
web应用的本质
socket网络编程:
架构:c/s架构
协议:TCP/UDP协议
传输层
web应用:
架构:B/S架构
协议:http协议
应用层
ps:
字符串转字节: bytes('dbsabhdsba', encoding='utf-8')
字节转字符串: str(res, encoding='utf-8')
HTTP协议
请求头:
GET / HTTP/1.1
Host: 127.0.0.1:8080
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
请求体:
dsjahbdjsahjdsa
响应头:
HTTP/1.1 200 OK
响应体:
"hello world"
用户看到的内容
路由系统
作用:将客户端请求的URL映射到相应的函数,最后执行函数即可,
routes = [
('/xxx', f1),
('/ooo', f2),
('/aaa', f3),
]
def run():
import socket
sock = socket.socket()
sock.bind(('127.0.0.1', 8080))
sock.listen(5)
while True:
conn, addr = sock.accept()
data = conn.recv(8090)
# print(data)
### 转成字符串类型
data_str = str(data, encoding='utf-8')
header_list = data_str.split('
')
headers = header_list[0]
url = headers.split('
')[0].split(' ')[1]
### 判断url
# if url == '/xxx':
# res = bytes('xxxx', encoding='utf-8')
# elif url == '/ooo':
# res = bytes('oooo', encoding='utf-8')
# else:
# res = bytes('404 not found', encoding='utf-8')
func_name = None
for items in routes:
if items[0] == url:
func_name = items[1]
break
if func_name:
res = func_name()
else:
res = bytes('404 not found', encoding='utf-8')
conn.send(bytes("HTTP/1.1 200 OK
",encoding='utf-8'))
conn.send(res)
conn.close()
Django的安装和启动
django的安装:
a. pip3 install django==1.11.22 -i https://pypi.tuna.tsinghua.edu.cn/simple
b. pycharm安装
django的创建:
a. django-admin startproject xxx
b. pycharm创建 (*************)
django目录结构:
s9day54:
s9day54:
settings.py: 配置文件
urls.py: 路由映射关系
wsgi.py : socket服务端文件
manage.py: 管理文件
启动django服务:
pycharm启动
django的路由介绍
添加路由和函数的对应关系:
urlpatterns = [
# url(r'^admin/', admin.site.urls),
url(r'^index/', index),
]
def index(request):
return HttpResponse('index')
Django的模版介绍
模板渲染函数:
def f1(request):
return render(request, 'f1.html')
变量替换:
name = 'zekai'
render(request, 'f1.html', {"name":name})
html页面:
<h2>{{ xxx }}</h2>
以后再去创建django项目的时候, 需要做的几个操作:
到settings.py中, 配置:
1. STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
逗号不能少
static目录需要创建
2. 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',
]
3. 'DIRS': [os.path.join(BASE_DIR, 'templates')]
Django的网页操作流程
1.占位符
将每个页面不变的代码写好之后,自己定一个不会重复的占位符字符串 @@content@@ ,然后在前台提交数据给后台时,后台将相应的数据处理后用 替换命令把占位符替换掉,然后返回给前台,渲染出来)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
</head>
<body>
@@content@@
</body>
</html>
2.语法
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
</head>
<body>
<table border="1px">
<thead>
<tr>
<th>ID</th>
<th>name</th>
<th>age</th>
</tr>
</thead>
<tbody>
{% for item in users %}
<tr>
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
3.Django里的写法
from django.conf.urls import url
from django.contrib import admin
from django.shortcuts import HttpResponse, render
def index(request):
return HttpResponse('index')
def f1(request):
### 变量的渲染
name = 'zekai'
### 列表
li = ['zekai', 'lxxx', 'leijun']
### 字典
dict = {"name":'zekai', 'age':18, 'hobby':'bj'}
### 列表中套字典
myli = [
{'id': 1, 'name': 'zekai', 'age': 12},
{'id': 2, 'name': 'yuechun', 'age': 32},
{'id': 3, 'name': 'lifu', 'age': 23}
]
return render(request, 'f1.html', {"xxx":name, "li":li, 'dict':dict, 'myli':myli})
def f2(request):
pass
urlpatterns = [
# url(r'^admin/', admin.site.urls),
url(r'^index/', index),
url(r'^f1/', f1),
]
Django的链接数据库操作
a.pymysql连接
b.django的orm连接