Diqi fourteen nature and django web application basis

First, the nature of web applications

1. Recalls

1.socket network programming:

1.架构:C/S架构
2.协议:TCP/UDP协议
3.\TCP/UDP协议属于OSI七层协议中的传输层

2.web Application:

1.架构:B/S架构
2.协议:HTTP协议
3.HTTP协议属于OSI七层协议中的应用层
4.OSI七层协议从上到下分别是:7)应用层、6)表示层、5)会话层、4)传输层、3)网络层、2)数据链路层、1)物理层。其中高层(7、6、5、4)定义了应用程序的功能,下三层(3、2、1)主要面向通过网络的端到端的数据流
5.应用层:HTTP、FTP等,对应应用程序的通信服务。表示层:加密、ASCII码,定义数据格式以及加密。会话层:SQL、rpc,控制会话。传输层:TCP、UDP,数据流复用和数据包排序。网络层:IP、IPX,定义所有结点的逻辑地址。数据链路层:mac地址。物理层:传输介质。

3. Supplement:

# 字符串转字节:
bytes('字符串', encoding='utf-8')

# 字节转字符串
str(b"字节", encoding='utf-8')

Nature 2.web framework

1. Based on B / S architecture and Http protocol client and server applications to interact

2. The client is the user's browser for sending HTTP requests and receiving HTTP response sent from the server

3. The server is the server socket for receiving a client to send HTTP requests and HTTP responses

Second, a web frame Custom

1. Objectives: The server will be customized into a dynamic server

2.HTTP request and HTTP response typically comprises two parts, the first part is the head, the second part is the body

3. request header generally contains links to a page request, then after the server by comparison, if the page returns a status code and page content

1.HTTP agreement

1. simple request - response protocol, typically runs over TCP. It specifies the client may send a message to the server, and what kind of response obtained

2.HTTP is based on a client / server mode, and the connection-oriented, typically of an HTTP transaction: 1) the client connection with a server; 2) The client makes a request to the server; 3) the server accepts the request and returns a response according to the request file as a response; 4) the client and server closes the connection

3.HTTP header request content or attributes:

GET / HTTP/1.1   # 1.请求方式 根路由(连在IP地址后的网页链接) HTTP协议的版本

Host: 127.0.0.1:8080   2.IP地址(包含端口)

Connection: keep-alive  3.链接状态:保持激活

Cache-Control: max-age=0  4.缓存控制

Upgrade-Insecure-Requests: 1  5.升级加密请求
 
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   6.用户代理(浏览器帮用户去请求服务端的代理,里面是浏览器内核)
                Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3    7.接收的文件类型
                
Accept-Encoding: gzip, deflate, br   8.接收的编码
Accept-Language: zh-CN,zh;q=0.9    9.接收的语言

4. Branch request header using \ r \ n to write, and two \ r \ n request indicates the end of the head, behind the body of the request, i.e. content request

The response header sent by the server with the HTTP protocol usually version, HTTP status code, but also with two \ r \ n response to the response thereof and spaced apart from the head

http/1.1 200 ok \r\n\r\n hello world

2. dynamic server

1. socket based server, to the server via dynamic routing system

2. url routing system by mapping the client requested function corresponding to the last execution of the function implemented

3. Example:

# socket服务器
def run():
    import socket

    server = socket.socket()
    server.bind(('127.0.0.1', 8000))
    server.listen()  # 半连接池,有默认参数,选填

    while True:
        conn, addr = server.accept()
        data = conn.recv(1024)  

        # print(data, type(data))
        data_str = str(data, encoding='utf-8')

        header_list = data_str.split('\r\n\r\n')

        headers = header_list[0]
        url = headers.split('\r\n')[0].split(' ')[1]

        # 直接在源码上修改不太适合实际开发,可拓展性差
        # if url == "/index":
            # res = bytes("index", encoding='utf-8')
        # else:
            # res = bytes('404 NO 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 NO FOUND', encoding='utf-8')

        conn.send(bytes("GET HTTP/1.1 200 OK\r\n\r\n", encoding='utf-8'))
        conn.send(res)
        conn.close()
        
# 路由系统:将客户端请求的url映射到相对应的函数,最后执行函数
# 装着路由映射关系的容器(装元组的列表)
routes = [
    ("/index", index),
    ("/login", login),
    ("/select", select),
    ("/select_jinja", select_jinja),
]

# 与路由相对应的函数,可以自定义渲染引擎,也可以使用第三方工具
def index():
    return bytes('index', encoding='utf-8')

def login():
    return bytes('login', encoding='utf-8')

# 自定义规则
def select():
    import pymysql
    conn = pymysql.connect(
        host='127.0.0.1',
        user='root',
        password='123',
        database='mydb'
    )
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    sql = "select * from users"
    cursor.execute(sql)
    
    users = cursor.fetchall()
    print(users)  # 是一个装着字典的列表
    
    # 我们需要在html中用@@content@@来充当占位符,以便用数据库中的数据来替换它,将数据渲染到网页上
    '''
    @@content@@ 
    替换成:
    <tr>
        <td>id</td>
        <td>name</td>
        <td>age</td>
    </tr>
    '''
    
    res_list = []
    for info in users:
        res = "<tr><td>%s</td><td>%S</td><td>%s</td></tr>" %(info['id'], info['name'], info['age'])
        res_list.append(res)
    # 将列表通过join组合成字符串
    res_str = "".join(res_list)
    
    # 读取HTML文件中的数据
    fr = open("users.html", "r", encoding="utf-8")
    data = fr.read()
    fr.close()
    
    # 将页面中@@content@@换成数据库中的内容
    data = data.replace("@@content@@", res_str)
    # 返回响应体结果
    return bytes(data, encoding='utf-8')
    
# 第三方工具jinja2
def select_jinja():
    import pymysql
    conn = pymysql.connect(
        host='127.0.0.1',
        user='root',
        password='123',
        database='mydb',
    )
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    sql = "select * from users"
    cursor.execute(sql)
    users = cursor.fetchall()
    
    fr = open("users_jinja.html", "r", encoding="utf-8")
    data = fr.read()
    fr.close()
    
    # 通过jinja2这个工具来实现将数据库中的内容放到页面中
    from jinja2 import Template
    template = Template(data)
    
    data = template.render(users=users)  # users参数是HTML文件中我们需要替换的内容,我们把users这个值传过去,就可以将页面内容更改
    return bytes(data, encoding='utf-8')
    
    

3. Since the web framework written summary

A. the first to write socket server

B. Routing System: url -> Function

C. template rendering engine: 1) rules define yourself; 2) use third-party tools (jinja2)

4.web classification framework

The first dimension Category: 1) A, B, C ---> tornado; 2) A (introduce a third party), B, C ---> django (wsgiref / uwsgi); 3) A (introduce a third party) , B, C (the introduction of a third party) ---> flask

2. The second dimension Category: 1) django (-orm, -session, -form form validation ......); 2) Other

Three, django

1.django installation and startup

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目录结构:
    根目录:
        次目录文件夹(和根目录同名):
            settings.py: 配置文件
            urls.py: 路由映射关系
            wsgi.py : socket服务端文件
        templates: 模板文件夹
        manage.py: 管理文件
        
启动django服务:
    pycharm启动

2.django route description

# urls.py中

# 添加路由和函数的对应关系:
urlpatterns = [
    # url(r'^admin/', admin.site.urls),
    url(r'^index/', index),
]
        
def index(request):
    return HttpResponse('index')

3.django presentation templates

# urls.py中

# 模板渲染函数,自定义规则:

from django.shortcuts import HttpResponse, render

def index(request):  # django中映射函数需要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})  # render是关键,第三个参数是一个字典,里面是要放入页面中的数据库的数据

def f2(request):
    pass

# 路由系统
urlpatterns = [
    # url(r'^admin/', admin.site.urls),
    url(r'^index/', index),
    url(r'^f1/', f1),  
]

4. When the pretreatment operation django

# 以后再去创建django项目的时候, 需要做的几个操作:

# 1.到settings.py中, 配置:
    STATIC_URL = '/static/'
    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, 'static'),
    )  # 逗号不能少
# 2.static目录需要创建,将非模板文件放在静态目录中,比如js、css、img等静态文件
                    
                
# 3.settings.py文件中:
    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',
    ]

# 4.
'DIRS': [os.path.join(BASE_DIR, 'templates')]

5.django connection database operations

1.pymysql connection

2.django of orm connection

Guess you like

Origin www.cnblogs.com/itboy-newking/p/11317273.html