第75天Djiango框架导读

知识点导读

```python
# 1、虚拟环境的安装
# 2、web应用 C/S | B/S 架构
# 3、http协议介绍
# 4、状态码
# 5、原生socket
# 6、框架演变
# 7、项目演变
```

一.虚拟环境的安装

- 重点

```python
# 1.通过pip3安装虚拟环境:
#    -- pip3 install virtualenv

# 2.前往目标文件夹:
#    -- cd 目标文件夹  (C:Virtualenv)

# 3.创建纯净虚拟环境:
#    -- virtualenv 虚拟环境名 (py3-env1)

# 4.终端启动虚拟环境:
#    -- cd py3-env1Scripts
#    -- activate

# 5.进入虚拟环境下的python开发环境
#     -- python3

# 6.关闭虚拟环境:
#    -- deactivate

# 7.PyCharm的开发配置
#    添加:创建项目 -> Project Interpreter -> Existing interpreter -> Virtualenv Environment | System Interpreter -> 目标路径下的python.exe
#    删除:Setting -> Project -> Project Interpreter -> Show All
```
- 了解

```python
# 创建非纯净环境:
#    -- virtualenv-clone 本地环境 虚拟环境名
```

```python
# Mac配置终端,在终端运行虚拟环境
# 在用户根目录下的.bash_profile(没有需手动创建)文件中设置
# alias 终端指令名(env-py3)='/Library/Virtualenv/虚拟环境名/bin/python3'
# alias 终端指令名(env-pip3)='/Library/Virtualenv/虚拟环境名/bin/pip3'
```

二.web应用架构

- C/S架构

```python
# client/server:客户端服务器架构,C++
```

- B/S架构

```python
# brower/server:浏览器服务器架构,Java、Python
```

三.http协议

1.什么是http协议

```python
# HTTP(HyperText Transport Protocol)是超文本传输协议
# 基于TCP/IP协议基础上的应用层协议,底层实现仍为socket
# 基于请求-响应模式:通信一定是从客户端开始,服务器端接收到客户端一定会做出对应响应
# 无状态:协议不对任何一次通信状态和任何数据做保存
# 无连接:一次连接只完成一次请求-响应,请求-响应

2.http工作原理(事务)

```python
# 一次http操作称之为一个事务,工作过程可分为四步
# 1.客户端与服务端建立连接
# 2.客户端发生一个http协议指定格式的请求
# 3.服务器端接收请求后,响应一个http协议指定格式的响应
# 4.客户端将服务器的响应显示展现给用户

3.请求报文

``python
# 请求行  请求头  请求体
'''
POST / HTTP/1.1
 (请求行)
Host: 127.0.0.1:8001

Connection: keep-alive

Upgrade-Insecure-Requests: 1

User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8

Accept-Encoding: gzip, deflate, br

Accept-Language: zh-CN,zh;q=0.9,en;q=0.8


(请求头)
usr=abc&pwd=123 (请求体)
'''
```

4.响应报文

```python
# 响应行  响应头  响应体
'''
HTTP/1.1 200 OK
 (响应行)
Content-type:text/html


 (响应头)
Login Success (响应行)
'''

四.状态码

(https://baike.baidu.com/item/HTTP%E7%8A%B6%E6%80%81%E7%A0%81)

```python
# 1打头:消息通知
# 2打头:请求成功
# 3打头:重定向
# 4打头:客户端错误
# 5打头:服务器端错误
```

五、原生socket服务

1.目录结构

``
01_socket
    -- 01_client.html:前台通过form表单访问后台的页面
    -- 01_login.html:后台测试渲染给前台的登录页面
    -- 01_index.html:后台测试渲染给前台的主面
    -- 01_server.py:后台服务器文件
```

2.基础socket服务代码

```python
import socket
# 利用socket建立服务器对象
server = socket.socket()
# 设置ip和端口
server.bind(('127.0.0.1', 8001))
# 设置监听
server.listen(5)
print('服务器设置成功')
print('浏览器访问:http://127.0.0.1:8001')
while True:
    # 阻塞等待客户端数据
    client, address = server.accept()
    # 接收数据
    data = client.recv(1024)
    print('接收到数据: ', data)
    # 返回数据
    client.send(b'Normal Socket Web')
    # 关闭连接(必须关闭每一次连接)
    client.close() 
    
# 注:浏览器错误:发送的响应无效,原因:响应不满足http协议
```

3.修改返回数据,完善响应体

```python
# 字符串
client.send(b'HTTP/1.1 200 OK
')
client.send(b'
')
client.send(b'Normal Socket Web')
```

```python
# html代码,请求头要设置支持html代码
client.send(b'HTTP/1.1 200 OK
')
client.send(b'Content-type:text/html
')
client.send(b'
')
client.send(b'<h1>Normal Socket Web</h1>')
```

```python
# html文件(同级目录建立一个index.html页面)
client.send(b'HTTP/1.1 200 OK
')
client.send(b'Content-type:text/html
')
client.send(b'
')
# 利用文件方式读取页面
with open('01_index.html', 'rb') as f:
    dt = f.read()
client.send(dt)
```

4.拓展:修改接收数据,模拟后台路由

```python
# 分析接收到的数据
data = client.recv(1024)
# 保证接收到的数据作为字符串进行以下处理
data = str(data, encoding='utf-8')
# 拆分出地址位
route = data.split('
')[0].split(' ')[1]
# 匹配地址,做出不同的响应
if route == '/index':
    with open('01_index.html', 'rb') as f:
        dt = f.read()
elif route == '/login':
    with open('01_login.html', 'rb') as f:
        dt = f.read()
else:
    dt = b'404'
client.send(dt)
```

六、框架演变

1.目录结构

```
03_proj
    -- template
        -- index.html
        -- user.html
    favicon.ico
    start.py
    urls.py
    views.py
```

2.template文件内容

- index.html

```html
<h1>{{ name }}</h1>
```

- user.html

```html
<table border="1">
    <tr>
        <th>id</th>
        <th>name</th>
        <th>password</th>
    </tr>
    {% for user in users%}
    <tr>
        <td>{{user.id}}</td>
        <td>{{user.name}}</td>
        <td>{{user.password}}</td>
    </tr>
    {% endfor %}
</table>

3.start文件内容

``python
from wsgiref.simple_server import make_server
from urls import urls


def app(env, response):
    print(env)
    # 设置响应头
    response("200 OK", [('Content-type', 'text/html')])
    route = env['PATH_INFO']
    print(route)
    data = urls['error']()
    if route in urls:
        data = urls[route]()
    # 返回二进制响应体
    return [data]


if __name__ == '__main__':
    server = make_server('127.0.0.1', 8003, app)
    print('start:http://127.0.0.1:8003')
    server.serve_forever()
```

4.urls文件内容

 urls.py

```python
from views import *
urls = {
    '/index': index,
    '/favicon.ico': ico,
    '/user': user,
    'error': error
}
``

5.views文件内容

``python
import pymysql
# 利用jinja2来渲染模板,将后台数据传给前台
from jinja2 import Template

def index():
    with open('templates/index.html', 'r') as f:
        dt = f.read()
    tem = Template(dt)
    resp = tem.render(name='主页')
    return resp.encode('utf-8')

def ico():
    with open('favicon.ico', 'rb') as f:
        dt = f.read()
    return dt

def user():
    # 数据库操作
    conn = pymysql.connect(host='127.0.0.1', port=3306, db='django', user='root', password='root')
    cur = conn.cursor(pymysql.cursors.DictCursor)
    cur.execute('select * from user')
    users = cur.fetchall()
    print(users)

    with open('templates/user.html', 'r') as f:
        dt = f.read()
    tem = Template(dt)
    resp = tem.render(users=users)

    return resp.encode('utf-8')

def error():
    return b'404'

```
原文地址:https://www.cnblogs.com/ye-hui/p/10216958.html