Django 08.07

1.web应用本质

hexo + gitee

socket网络编程:

  • 架构:CS架构
  • 协议:TCP/UDP
  • 传输层

web应用:

  • 架构:B/S架构
  • 协议:http协议
  • 应用层

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

字节转字符串: str(res,encoding='utf-8')

#server.py

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

def f2():
    fp =open('index.html','r',encoding ='utf-8')
    data =fp.read()
    
    return bytes(data,encoding='utf-8')

def f3():
    fp = open('f3.html','r',encoding='utf-8')
    data = fp.read()
    import time
    ctime = time.time()
    data = data.replace('@@content@@',str(ctime))
    return bytes(data,encoding='utf-8')

def f4():
    import pymysql
    connect = pymysql.connect(host='localhost',user='root',password='123',database='t2')
    cursor = connect.cursor(cursor=pymysql.cursors.DictCursor)
    
    sql = 'select *from users'
    cursor.execute(sql)
    
    users = cursor.fetchall()
    print(users)
    
    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)
        
    s = "".join(res_list)
    data = open('users.html','r',encoding='utf-8').read()
    data = data.replace('@@content@@',s)
    
    return bytes(data,encoding='utf-8')

def f5():
    import pymysql
    conn = pymysql.connenct(host='localhost',users='root',password='123',database='t2')
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    
    sql = "select * from users"
    cursor.execute(sql)
    
    users = cursor.fetchall()
    
    users2 = open('users2.html','r',encoding='utf-8').read()
    
    from jinja2 import Template
    template = Template(users2)
    
    data = template.render(users=users)
    return bytes(data,encoding='utf-8')

routes = [
    ('/xxx',f1),
    ('/ooo',f2),
    ('/aaa',f3),
    ('/kkk',f4),
    ('/f5',f5)
]
def run():
    import socket
    server = socket.socket()
    server.bind(('127.0.0.1',8080))
    sock.listen(5)
    
    while True:
        connect,addres = server.accept()
        data = connenc.recv(4)
        #获取URL
        data_str = str(data,encoding='utf-8')
        header_list = data_str.spllit('\r\n\r\n')
        headers = header_list[0]
        url = headers.split('\r\n')[0].split(' ')[1]
        
        #判断URL
        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')
            
        connect.send(bytes("HTTP/1.1 200 OK\r\n\r\n"),encoding='utf-8')
        connect.send(res)
        connect.close()
        
if __name__ == '__main__':
    run()
#index html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Title</title>
</head>
<body>
    <h1>hello world</h1>
</body>
</html>
#f3.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Title</title>
</head>
<body>

    @@content@@

</body>
</html>
#users.html
<!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>
        @@content@@
    </tbody>
</table>
</body>
</html>
<!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>

2.自定义一个web框架

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 

请求体: hello world

响应头: HTTP/1.1 200 OK

响应体: "hello world"(用户看到的内容)
web 框架:
a.自己写socket服务端
b.路由系统:  URL ===> 函数
c.模板引擎渲染:
1.自己定义的规则
2.使用第三方的工具(jinja2)

web框架的分类:
第一种维度的分类:
1、a.b.c ---> tornado
2、a(引入第三方),b,c ----> django(wsgiref/uwsg)
3、a(引入第三方), b, c(引入第三方)   ------> flask

第二种维度的分类:
1、Django -ORM; -session; -form表单验证 ......
2、其它

3.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目录结构:
			day08:
				day08:
					settings.py: 配置文件
					urls.py: 路由映射关系
					wsgi.py : socket服务端文件
					
				manage.py: 管理文件
		
启动django服务:
	pycharm启动

4.Django的路由介绍

def index(request):
    return HttpRseponse('index')

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

5.Django的模板介绍

模板渲染函数:
    def f1(request):
        return render(request,'f1.html')
变量替换:
    name = 'name1'
    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')]
		

6.Django的连接数据库操作

a.pymysql连接

b.Django的ORM连接

posted @ 2019-08-07 23:30  海森t  阅读(41)  评论(0)    收藏  举报