初识Django

Django框架

1.web应用的本质

socket网络编程:基于C/S架构,传输协议:TCP/UDP协议;位于传输层

web应用:基于B/S架构,传输协议:Http协议,处于应用层

2.web框架自定义

​ 目标:将自定制的server变成一个动态的server

#静态的server端
import socket
server = socket.socket()
server.bind(('127.0.0.1',1111))
server.listen(5)

while True:
    conn,addr = server.accept()
    data = conn.recv(1024)
    print(data)
    #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\r\n\r\n
     #换两行后,加请求体信息内容
	
    #响应头
    conn.send(bytes("http/1.1 200 0k\r\n\r\n",encoding="utf-8"))
	#响应体	
    conn.send(bytes("hello world",encoding="utf-8"))

http协议:
    1.请求头
    2.请求体
    3.响应头
    4.响应体
    
str与bytes可强制转换
#动态server端
def run():
    import socket

    server = socket.socket()

    server.bind(('127.0.0.1',1111))

    server.listen(5)

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

        data = conn.recv(1024)

        #获取url路由
        data_str = str(data,encoding="utf8")
        header_list = data_str.split('\r\n')
        header = header_list[0]
        url = header.split(" ")[1]

        ###判断路由url
        func_name = None
        for items in routes:
            if items[0] == url:
                func_name = items[1]
                break
        if func_name:
            response = func_name()
        else:
            response = bytes('404 not found', encoding='utf-8')

        conn.send(bytes("http/1.1 200 0k\r\n\r\n",encoding="utf-8"))

        conn.send(response)

        conn.close()

def f1():
    res = bytes('123', encoding='utf-8')
    return res
def f2():
    res = bytes('345', encoding='utf-8')
    return res
def f3():
    fp = open("f3.html",encoding="utf8")
    data = fp.read()
    import time
    t = time.time()
    #渲染:服务器处理的结构呈现于前端页面
    data = data.replace("@@content@@",str(t))
    res = bytes(data,encoding="utf8")
    return res

def f4():
    import pymysql
    conn = pymysql.Connect(host='127.0.0.1',
                           port = 3306,
                           user = "root",
                           password = "321",
                           db = "oopp")
    c = conn.cursor(pymysql.cursors.DictCursor)

    sql = "select *from user_info"
    c.execute(sql)
    user = c.fetchall()

    """将@@content@@替换成
        <tr>
            <td></td>
            <td></td> 
        </tr>"""
    fp = open("f4.html","r",encoding="utf-8")
    data = fp.read()

    us_list = []
    for info in user:
        us = "<tr><td>%s</td><td>%s</td></tr>" % (info["name"],info["password"])
        us_list.append(us)


    data_str = "".join(us_list)
    data = data.replace("@@content@@", data_str)
    res = bytes(data, encoding="utf8")
    return res

def f5():
    import pymysql
    conn = pymysql.Connect(host='127.0.0.1',
                           port = 3306,
                           user = "root",
                           password = "321",
                           db = "oopp")
    c = conn.cursor(pymysql.cursors.DictCursor)

    sql = "select *from user_info"
    c.execute(sql)
    user = c.fetchall()

    fp = open("f5.html","r",encoding="utf-8")
    user_data = fp.read()

    from jinja2 import Template

    template = Template(user_data)

    data = template.render(users = user)
    res = bytes(data, encoding="utf8")
    return res

routes = [("/123",f1),
          ("/345",f2),
          ("/aaa",f3),
          ("/ccc",f4),
          ("/zzz",f5)]


if __name__ == '__main__':
    run()
    
#f3.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>来自f3的数据</title>
</head>
<body>
    @@content@@
</body>
</html>

#f4.html
<!DOCTYPE html>
<html >
<head>
    <meta charset="UTF-8">
    <title>来自f4的数据</title>
</head>
<body>
    <table border = "1" width="500" height="300" rules = "all"  >
        <thead>
            <tr>
                <th>name</th>
                <th>password</th>
            </tr>
        </thead>
        <tbody>
            @@content@@
        </tbody>
    </table>
</body>
</html>

#f5.html
<!DOCTYPE html>
<html >
<head>
    <meta charset="UTF-8">
    <title>来自f5的数据</title>
</head>
<body>
    <table border = "1" width="500" height="300" rules = "all"  >
        <thead>
            <tr>
                <th>name</th>
                <th>password</th>
            </tr>
        </thead>
        <tbody>
            {% for item in users %}
               <tr>
                   <td>{{item.name}}</td>
                   <td>{{item.password}}</td>
               </tr>
            {% endfor %}
        </tbody>
    </table>
</body>
</html>

web框架的组成:

a. socket服务端
b. 路由系统: url ====> 函数
c. 模板引擎渲染 ,自定义规则(@@content@@),或第三方工具(jinja2)

web框架的分类:

按维度来分:
​ 1.a,b,c ------>Tornada框架
2.a(引入第三方),b,c---->Django框架
3.a和c(引入第三方),b---->Flask框架

3.Django的安装与启动

安装方式:
a. pip3 install django==1.11.22 -i https://pypi.tuna.tsinghua.edu.cn/simple
b. pycharm安装

创建方式:
a. django-admin startproject xxx
b. pycharm创建

目录结构:
文件夹名:
文件夹名:
init.py(包)
settings.py(配置文件)
urls.py(路由映射文件)
wsgi.py(socket服务端文件)
templates(文件夹)
manage.py(管理文件)

4.Django的路由介绍

​ 在urls.py文件中添加设置路由

#urls.py
from django.conf.urls import url
from django.contrib import admin
from django.shortcuts import HttpResponse

def index(request):
    return HttpResponse("liu jin is a cfo!!!")


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/',index)

5.Django的模板介绍

#urls.py
from django.shortcuts import HttpResponse,render

def index(request):
    return HttpResponse("liu jin is a cfo!!!")

def f1(request):
    #变量渲染
    name = "liu_jin"
    #列表的渲染
    li = ['wq','nick','sean']
    #字典的渲染
    dict = {"name":"wq","age":18}
    # 列表套字典渲染
    myli = [{"name": "wq", "age": 18}, {"name": "qq", "age": 18}]

    return render(request,"f1.html",{"name":name,"li":li,"dict":myli})


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/',index),
    url(r'^aaa/',f1)

    
#模板渲染函数,html文件存于templates
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>来自f1的数据</title>
</head>
<body>
    // 1.变量渲染
    <h1>{{name}}</h1>
    // 2.列表渲染
    <h1>{{ li.0 }}</h1>
    <h1>{{ li.1 }}</h1>
    <h1>{{ li.2 }}</h1>
    <hr>
    //列表循环
    <ul>
        {% for items in li %}
            <li>{{ items }}</li>
        {% endfor %}
    </ul>
    <hr>
    //字典的渲染
    <h1>{{ dict.name }}</h1>
    //字典循环
    <ul>
        {% for key,value in dict.items %}
            <li>{{ key }}---{{ value }}</li>
        {% endfor %}
    </ul>
    //列表套字典渲染
    <table border = "1" width="500" height="300" rules = "all"  >
        <thead>
            <tr>
                <th>name</th>
                <th>age</th>
            </tr>
        </thead>
        <tbody>
            {% for item in dict %}
               <tr>
                   <td>{{item.name}}</td>
                   <td>{{item.age}}</td>
               </tr>
            {% endfor %}
        </tbody>
    </table>
</body>
</html>

创建Django项目的时候,需提前操作:

  1. 手动创建static文件夹(含css,js,img文件夹)等静态资源
  2. STATIC_URL = '/static/'
    STATICFILES_DIRS =( (os.path.join(BASE_DIR, 'static'),)
  3. 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')]
posted @ 2019-08-07 23:49  wanjiang  阅读(133)  评论(1编辑  收藏  举报