Django beginning

django beginning

The nature of web applications

socket网络编程:
    架构:c/s架构
    协议:TCP/UDP协议
    传输层
web应用:
    架构:B/S架构
    协议:http协议
    应用层
ps:
    字符串转字节: bytes('dbsabhdsba', encoding='utf-8')
    字节转字符串: str(res, encoding='utf-8')

HTTP protocol

请求头:
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"
    用户看到的内容
        

Routing System

Action: the client request to a corresponding URL mapping function, the function can be performed last,

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('\r\n\r\n')
                    headers = header_list[0]
                    url = headers.split('\r\n')[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\r\n\r\n",encoding='utf-8'))
                    conn.send(res)
                    conn.close()

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目录结构:

s9day54:
    s9day54:
        settings.py: 配置文件
        urls.py: 路由映射关系
        wsgi.py : socket服务端文件

        manage.py: 管理文件

启动django服务:
pycharm启动

django route description

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

Django template description

模板渲染函数:
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 web operating procedures

1. placeholder


将每个页面不变的代码写好之后,自己定一个不会重复的占位符字符串 @@content@@ ,然后在前台提交数据给后台时,后台将相应的数据处理后用 替换命令把占位符替换掉,然后返回给前台,渲染出来)
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Title</title>
</head>
<body>

    @@content@@

</body>
</html>

2. Grammar

<!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 in the wording

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 link database operations

a.pymysql连接
        
b.django的orm连接

Guess you like

Origin www.cnblogs.com/bladecheng/p/11317184.html