python&django程序练习

--进度  P19

 

---------------------------------01 socket----------------------------------------

__author__="Hunter"

import socket

sock=socket.socket()
sock.bind(('127.0.0.1',8080))
sock.listen(5)

while True:
conn,addr = sock.accept()
data=conn.recv(8096)
conn.send(b'Hunter reply')
conn.close()

---------------------------------02 添加响应头----------------------------------------
__author__="Hunter"

import socket

sock=socket.socket()
sock.bind(('127.0.0.1',8080))
sock.listen(5)

while True:
conn,addr = sock.accept()
data=conn.recv(8096)
print(data)
conn.send(b"HTTP/1.1 200 OK\r\n\r\n")
conn.send(b'Hunter reply')
conn.close()

打印出的请求头数据格式:

b'GET / HTTP/1.1\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nAccept-Language: zh-Hans-CN,zh-Hans;q=0.5\r\nUpgrade-Insecure-Requests: 1\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362\r\nAccept-Encoding: gzip, deflate\r\nHost: 127.0.0.1:8080\r\nConnection: Keep-Alive\r\n\r\n'

 

---------------------------------03 识别URL----------------------------------------

__author__="Hunter"

import socket

sock=socket.socket()
sock.bind(('127.0.0.1',8080))
sock.listen(5)

while True:
conn,addr = sock.accept()
data=conn.recv(8096)
#print(data)
data=str(data,encoding='utf-8')
header,body=data.split('\r\n\r\n')
print('HEAD:',header)
print('BODY:',body)
temp_list=header.split('\r\n')
method,url,protocol=temp_list[0].split(' ')
print("METHOD IS:",method)
print("URL IS:",url)
conn.send(b"HTTP/1.1 200 OK\r\n\r\n")
if url == '/404':
conn.send(bytes('404 Page Not Found',encoding='utf-8'))
else:
send_content="your inputted URL is:"+url
conn.send(bytes(send_content,encoding='utf-8'))
conn.close()

---------------------------------04 加入简单路由功能----------------------------------------
__author__="Hunter"

import socket

def f1():
return 'function f1'

def f2():
return 'function f2'

url_pattens = [
('/aaa',f1),
('/bbb',f2),
]

def run_web():
sock=socket.socket()
sock.bind(('127.0.0.1',8080))
sock.listen(5)

while True:
conn,addr = sock.accept()
data=conn.recv(8096)
#print(data)
data=str(data,encoding='utf-8')
header,body=data.split('\r\n\r\n')
print('HEAD:',header)
print('BODY:',body)
temp_list=header.split('\r\n')
method,url,protocol=temp_list[0].split(' ')
print("METHOD IS:",method)
print("URL IS:",url)
conn.send(b"HTTP/1.1 200 OK\r\n\r\n")

func_name = None
for items in url_pattens:
if items[0] == url:
func_name = items[1]
break

if func_name:
response=func_name()
else:
response='404 Page Not Found'

conn.send(bytes(response, encoding='utf-8'))
conn.close()

if __name__ == '__main__':
run_web()
---------------------------------05 f1返回html文本----------------------------------------
__author__="Hunter"

import socket

def f1(request):
f=open("index.html","rb")
data=f.read()
f.close()
return data

def f2(request):
return b'function f2'

url_pattens = [
('/aaa',f1),
('/bbb',f2),
]

def run_web():
sock=socket.socket()
sock.bind(('127.0.0.1',8080))
sock.listen(5)

while True:
conn,addr = sock.accept()
data=conn.recv(8096)
#print(data)
data=str(data,encoding='utf-8')
header,body=data.split('\r\n\r\n')
print('HEAD:',header)
print('BODY:',body)
temp_list=header.split('\r\n')
method,url,protocol=temp_list[0].split(' ')
print("METHOD IS:",method)
print("URL IS:",url)
conn.send(b"HTTP/1.1 200 OK\r\n\r\n")

func_name = None
for items in url_pattens:
if items[0] == url:
func_name = items[1]
break

if func_name:
response=func_name(data)
else:
response=b'404 Page Not Found'

conn.send(response)
conn.close()

if __name__ == '__main__':
run_web()


-- /aaa路由

 

---------------------------------06 f1,f2均返回html页面----------------------------------------
__author__="Hunter"

import socket

def f1(request):
f=open("index.html","rb")
data=f.read()
f.close()
return data

def f2(request):
f=open("data_list_table.html","rb")
data=f.read()
f.close()
return data

url_pattens = [
('/aaa',f1),
('/bbb',f2),
]

def run_web():
sock=socket.socket()
sock.bind(('127.0.0.1',8080))
sock.listen(5)

while True:
conn,addr = sock.accept()
data=conn.recv(8096)
#print(data)
data=str(data,encoding='utf-8')
header,body=data.split('\r\n\r\n')
print('HEAD:',header)
print('BODY:',body)
temp_list=header.split('\r\n')
method,url,protocol=temp_list[0].split(' ')
print("METHOD IS:",method)
print("URL IS:",url)
conn.send(b"HTTP/1.1 200 OK\r\n\r\n")

func_name = None
for items in url_pattens:
if items[0] == url:
func_name = items[1]
break

if func_name:
response=func_name(data)
else:
response=b'404 Page Not Found'

conn.send(response)
conn.close()

if __name__ == '__main__':
run_web()

-------------index.html--------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Python&Django练习程序</title>
</head>
<body>
<h1>用户登录</h1>
<form>
<p><input type="text" placeholder="用户名" /></p>
<p><input type="password" placeholder="密码" /></p>
</form>
</body>
</html>


-------------data_list_table.html----------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>表格展示界面</h1>
<table border="1">
<thead>
<tr>
<th>用户名</th>
<th>密码</th>
<th>邮箱</th>
</tr>
</thead>
<tbody>
<tr>
<th>HunterHuang</th>
<th>8888</th>
<th>8888@qq.com</th>
</tr>
</tbody>

</table>

</body>
</html>


 

 

---------------------------------07 从数据库获取数据并展示----------------------------------------
__author__="Hunter"

import socket

def f1(request):
f=open("index.html", "rb")
data=f.read()
f.close()
return data

def f2(request):
f=open("data_list_table.html", "rb")
data=f.read()
f.close()
return data

def f3(request):
import pymysql

# 创建连接
conn = pymysql.connect(host='192.168.56.57', port=3306, user='hunter', passwd='oracle', db='hunter')
# 创建游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 执行SQL,并返回收影响行数
#effect_row = cursor.execute("update hosts set host = '1.1.1.2'")
cursor.execute("select id,name,addr from user_list_tb")
user_list = cursor.fetchall()
print(user_list)

# 执行SQL,并返回受影响行数
# effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,))

# 执行SQL,并返回受影响行数
# effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])

# 提交,不然无法保存新建或者修改的数据
conn.commit()

# 关闭游标
cursor.close()
# 关闭连接
conn.close()

f=open("user_list.html", "r",encoding="utf-8")
template=f.read()
f.close()
content_list=""
for item in user_list:
tp="<tr><td>%s</td><td>%s</td><td>%s</td></tr>" %(item['id'],item['name'],item['addr'])
content_list += tp
data = template.replace("@@web_content@@",content_list)
return bytes(data,encoding="utf-8")

url_pattens = [
('/aaa',f1),
('/bbb',f2),
('/user_list',f3),
]

def run_web():
sock=socket.socket()
sock.bind(('127.0.0.1',8080))
sock.listen(5)

while True:
conn,addr = sock.accept()
data=conn.recv(8096)
#print(data)
data=str(data,encoding='utf-8')
header,body=data.split('\r\n\r\n')
print('HEAD:',header)
print('BODY:',body)
temp_list=header.split('\r\n')
method,url,protocol=temp_list[0].split(' ')
print("METHOD IS:",method)
print("URL IS:",url)
conn.send(b"HTTP/1.1 200 OK\r\n\r\n")

func_name = None
for items in url_pattens:
if items[0] == url:
func_name = items[1]
break

if func_name:
response=func_name(data)
else:
response=b'404 Page Not Found'

conn.send(response)
conn.close()

if __name__ == '__main__':
run_web()
#f3('aa')

------------------------------user_list.html-------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>表格展示界面</h1>
<table border="1">
<thead>
<tr>
<th>用户ID</th>
<th>用户名</th>
<th>地址</th>
</tr>
</thead>
<tbody>
@@web_content@@
</tbody>

</table>

</body>
</html>

 

---------------------------------08 通过jinja2渲染页面----------------------------------------

 

__author__="Hunter"

import socket

def f1(request):
f=open("index.html", "rb")
data=f.read()
f.close()
return data

def f2(request):
f=open("data_list_table.html", "rb")
data=f.read()
f.close()
return data

def f3(request):
import pymysql

# 创建连接
conn = pymysql.connect(host='192.168.56.57', port=3306, user='hunter', passwd='oracle', db='hunter')
# 创建游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 执行SQL,并返回收影响行数
#effect_row = cursor.execute("update hosts set host = '1.1.1.2'")
cursor.execute("select id,name,addr from user_list_tb")
user_list = cursor.fetchall()
print(user_list)

# 执行SQL,并返回受影响行数
# effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,))

# 执行SQL,并返回受影响行数
# effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])

# 提交,不然无法保存新建或者修改的数据
conn.commit()

# 关闭游标
cursor.close()
# 关闭连接
conn.close()

f=open("user_list.html", "r",encoding="utf-8")
template=f.read()
f.close()
content_list=""
for item in user_list:
tp="<tr><td>%s</td><td>%s</td><td>%s</td></tr>" %(item['id'],item['name'],item['addr'])
content_list += tp
data = template.replace("@@web_content@@",content_list)
return bytes(data,encoding="utf-8")

def f4(request):
import pymysql

# 创建连接
conn = pymysql.connect(host='192.168.56.57', port=3306, user='hunter', passwd='oracle', db='hunter')
# 创建游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 执行SQL,并返回收影响行数
#effect_row = cursor.execute("update hosts set host = '1.1.1.2'")
cursor.execute("select id,name,addr from user_list_tb")
user_list = cursor.fetchall()
print(user_list)

# 执行SQL,并返回受影响行数
# effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,))

# 执行SQL,并返回受影响行数
# effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])

# 提交,不然无法保存新建或者修改的数据
conn.commit()

# 关闭游标
cursor.close()
# 关闭连接
conn.close()

f=open("customer_list.html", "r",encoding="utf-8")
customer_data=f.read()
f.close()

from jinja2 import Template
template = Template(customer_data)
data = template.render(customer_list=user_list)
return data.encode('utf-8')

url_pattens = [
('/aaa',f1),
('/bbb',f2),
('/user_list',f3),
('/customer_list',f4),
]

def run_web():
sock=socket.socket()
sock.bind(('127.0.0.1',8080))
sock.listen(5)

while True:
conn,addr = sock.accept()
data=conn.recv(8096)
#print(data)
data=str(data,encoding='utf-8')
header,body=data.split('\r\n\r\n')
print('HEAD:',header)
print('BODY:',body)
temp_list=header.split('\r\n')
method,url,protocol=temp_list[0].split(' ')
print("METHOD IS:",method)
print("URL IS:",url)
conn.send(b"HTTP/1.1 200 OK\r\n\r\n")

func_name = None
for items in url_pattens:
if items[0] == url:
func_name = items[1]
break

if func_name:
response=func_name(data)
else:
response=b'404 Page Not Found'

conn.send(response)
conn.close()

if __name__ == '__main__':
run_web()


---------------------customer_list.html----------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>客户信息系统</title>
</head>
<body>
<h1>表格展示界面</h1>
<table border="1">
<thead>
<tr>
<th>用户ID</th>
<th>用户名</th>
<th>地址</th>
</tr>
</thead>
<tbody>
{% for row in customer_list%}
<tr>
<td>{{row.id}}</td>
<td>{{row.name}}</td>
<td>{{row.addr}}</td>
</tr>
{% endfor %}
</tbody>

</table>

</body>
</html>

 ==========================================================================Django=========================================================================================

django-admin startproject mysite

python manage.py runserver 0.0.0.0:8000

 

 

 

-----------------01 读取输出html文件-------------

"""mysite URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.http import HttpResponse
from django.urls import path


def login(request):
f = open("mysite/hunter.html", "r", encoding="utf-8")
customer_data = f.read()
f.close()
return HttpResponse(customer_data)

urlpatterns = [
#path('admin/', admin.site.urls),
path('login/', login),
]

 

-----------------02 读取数据库数据并渲染模板------------- 

from django.shortcuts import render


def login(request):
import pymysql

# 创建连接
conn = pymysql.connect(host='192.168.56.57', port=3306, user='hunter', passwd='oracle', db='hunter')
# 创建游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 执行SQL,并返回收影响行数
# effect_row = cursor.execute("update hosts set host = '1.1.1.2'")
cursor.execute("select id,name,addr from user_list_tb")
customer_list = cursor.fetchall()
print(customer_list)

# 执行SQL,并返回受影响行数
# effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,))

# 执行SQL,并返回受影响行数
# effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])

# 提交,不然无法保存新建或者修改的数据
conn.commit()

# 关闭游标
cursor.close()
# 关闭连接
conn.close()
print(locals())

return render(request,'customer_list.html',locals())






posted @ 2021-08-28 09:59  HunterHuang  阅读(51)  评论(0编辑  收藏  举报