内容回顾
python基础
网络编程
-
OSI七层模型 TCP/IP五层
- 应用层 应用层 HTTP HTTPS FTP
- 表示层
- 会话层
- 传输层 传输层 TCP UDP
- 网络层 网络层 IP
- 数据链路层 数据链路层 ARP
- 物理层 物理层
-
socket 套接字 处于应用层与传输层之间的一个虚拟层,是一个接口
-
百度(socket服务端)
1、启动
2、绑定IP和端口
3、监听
6、接收数据
7、返回数据
断开连接
-
浏览器(socket客户端)
4、连接服务端
5、发送数据
8、接收数据
断开连接
#! /usr/bin/env python # -*- coding:utf-8 -*- import socket #创建socket对象 sk = socket.socket() #绑定IP和端口 sk.bind(('127.0.0.1',8000)) #监听 sk.listen() while True: #等待连接 conn,addr = sk.accept() #接收数据 data = conn.recv(8096) #返回状态行 conn.send(b'HTTP/1.1 200 OK\r\n\r\n') conn.send(b'<h1>ok</h1>') #关闭 conn.close()
并发编程
前端
数据库
今日内容
HTTP协议:超文本协议
-
HTTP是一个客户端和服务端请求和应答的标准(TCP),默认端口为80
-
工作原理:
- 客户端连接到web服务器,创建一个TCP套接字连接
- 发送HTTP请求,客户端向服务器发送一个文本请求,由请求行、请求头部、空行、请求数据4部分组成
- 服务器接受请求并返回HTTP响应;服务器将资源副本写到TCP套接字,由客户读取,一个响应由状态行、响应头部、空行和响应数据组成
- 释放TCP连接,若connection模式为close,则服务器主动关闭TCP连接,客户端被动关闭连接,释放TCP连接,若connection模式为keepalive,则该连接会保持一段时间,在该时间内可以继续接收请求
- 客户端浏览器解析HTML内容
-
HTTP请求方法:
- GET:向指定资源发出'显示'请求
- HEAD
- POST:向指定资源提交数据
- PUT
- DELETE
- TRACE
- OPTIONS
- CONNECT
-
HTTP状态码
- 1xx消息---请求已被服务器接收,继续处理
- 2xx成功--请求已成功被服务器接收、理解、并接受
- 3xx重定向--需要后操作才能完成这一请求
- 4xx请求错误--请求含有语法错误或无法被执行
- 5xx服务器错误--服务器在处理某个正确请求时发生错误
-
URL:https://www.cnblogs.com/leiyu567567/p/14953942.html
- 传输协议
- 层级URL标记符号
- 访问资源需要的凭证信息(可省略)
- 服务器(通常为域名,有时为IP地址)
- 端口号(以数字方式表示,若为HTTP默认值80可省略)
- 路径,(以'/'字符区别路径中的每一个目录结构)
- 查询(GET模式的窗口参数,以'?'字符为起点,每个参数以'&'隔开,再以'='分开参数名称与数据,通常以UTF8的URL编码,避开字符冲突的问题)
- 片段,以'#'字符为起点
-
请求的格式(request)
请求方式 URL HTTP/1.1 K1:V1 K1:V1 请求数据
-
响应的格式(response)
HTTP/1.1 状态码 状态描述 K1:v1 k2:v2 响应数据(响应体)-HTML
根据不同路径返回不同内容
import socket
# 创建socket对象
sk = socket.socket()
# 绑定IP和端口
sk.bind(('127.0.0.1', 8000))
# 监听
sk.listen()
def oumei(url):
ret = 'oumei - {}'.format(url)
return ret.encode('utf-8')
def rihan(url):
ret = 'rihan//// - {}'.format(url)
return ret.encode('utf-8')
def guochan(url):
ret = 'guochan - {}'.format(url)
return ret.encode('utf-8')
list = [
('/oumei', oumei),
('/rihan', rihan),
('/guochan', guochan),
]
while True:
# 等待连接
conn, addr = sk.accept()
# 接收数据
data = conn.recv(8096)
data = data.decode('utf-8')
url = data.split()[1]
print(url)
# 返回状态行
conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
func = None
for i in list:
if i[0] == url:
func = i[1]
break
if func:
ret = func(url)
else:
ret = b'404 not found'
conn.send(ret)
# 关闭连接
conn.close()
返回HTML页面
#! /usr/bin/env python
# -*- coding:utf-8 -*-
import socket
# 创建socket对象
sk = socket.socket()
# 绑定IP和端口
sk.bind(('127.0.0.1', 8000))
# 监听
sk.listen()
def oumei(url):
ret = 'oumei - {}'.format(url)
return ret.encode('utf-8')
def rihan(url):
ret = 'rihan//// - {}'.format(url)
return ret.encode('utf-8')
def guochan(url):
ret = 'guochan - {}'.format(url)
return ret.encode('utf-8')
def index(url):
with open('index.html', 'rb') as f:
ret = f.read()
return ret
list = [
('/oumei', oumei),
('/rihan', rihan),
('/guochan', guochan),
('/index', index),
]
while True:
# 等待连接
conn, addr = sk.accept()
# 接收数据
data = conn.recv(8096)
data = data.decode('utf-8')
url = data.split()[1]
print(url)
# 返回状态行
conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
func = None
for i in list:
if i[0] == url:
func = i[1]
break
if func:
ret = func(url)
else:
ret = b'404 not found'
conn.send(ret)
# 关闭连接
conn.close()
###index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<h1>这是index页面</h1>
</div>
</body>
</html>
返回动态页面
import socket
import time
# 创建socket对象
sk = socket.socket()
# 绑定IP和端口
sk.bind(('127.0.0.1', 8000))
# 监听
sk.listen()
def oumei(url):
ret = 'oumei - {}'.format(url)
return ret.encode('utf-8')
def rihan(url):
ret = 'rihan//// - {}'.format(url)
return ret.encode('utf-8')
def guochan(url):
ret = 'guochan - {}'.format(url)
return ret.encode('utf-8')
def index(url):
with open('index.html', 'rb') as f:
ret = f.read()
return ret
def timer(url):
now = time.strftime('%Y-%m-%d %H:%M:%S')
with open('time.html','r',encoding='utf-8') as f:
data = f.read()
data = data.replace('@@time@@',now)
return data.encode('utf-8')
list = [
('/oumei', oumei),
('/rihan', rihan),
('/guochan', guochan),
('/index', index),
('/time', timer),
]
while True:
# 等待连接
conn, addr = sk.accept()
# 接收数据
data = conn.recv(8096)
data = data.decode('utf-8')
url = data.split()[1]
print(url)
# 返回状态行
conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
func = None
for i in list:
if i[0] == url:
func = i[1]
break
if func:
ret = func(url)
else:
ret = b'404 not found'
conn.send(ret)
# 关闭连接
conn.close()
###time.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>当前时间是:@@time@@</h1>
</body>
</html>
web框架
-
web框架 就是一个socket服务端
-
功能
- a、socket收发消息
- b、根据不同的路径返回不同的内容
- c、可以返回动态页面(字符串的替换 - 模板的渲染)
-
分类
- Django b c
- flash b
- tornado a b c
-
另类分类
- Django
- 其他
-
WSGI(Web Server Gateway Interface)web应用程序与web服务器程序之间的接口格式,实现web应用程序与web服务器程序间的解耦
#! /usr/bin/env python # -*- coding:utf-8 -*- """ 根据URL中不同的路径返回不同的内容--函数进阶版 返回HTML页面 让网页动态起来 wsgiref模块版 """ from wsgiref.simple_server import make_server # 将返回不同的内容部分封装成函数 def index(url): # 读取index.html页面的内容 with open("index.html", "r", encoding="utf8") as f: s = f.read() # 返回字节数据 return bytes(s, encoding="utf8") def home(url): with open("home.html", "r", encoding="utf8") as f: s = f.read() return bytes(s, encoding="utf8") def timer(url): import time with open("time.html", "r", encoding="utf8") as f: s = f.read() s = s.replace('@@time@@', time.strftime("%Y-%m-%d %H:%M:%S")) return bytes(s, encoding="utf8") # 定义一个url和实际要执行的函数的对应关系 list1 = [ ("/index/", index), ("/home/", home), ("/time/", timer), ] def run_server(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html;charset=utf8'), ]) # 设置HTTP响应的状态码和头信息 url = environ['PATH_INFO'] # 取到用户输入的url func = None for i in list1: if i[0] == url: func = i[1] break if func: response = func(url) else: response = b"404 not found!" return [response, ] if __name__ == '__main__': httpd = make_server('127.0.0.1', 8090, run_server) print("我在8090等你哦...") httpd.serve_forever()
-
jinja2模板
#! /usr/bin/env python # -*- coding:utf-8 -*- from wsgiref.simple_server import make_server from jinja2 import Template def index(url): # 读取HTML文件内容 with open("index2.html", "r", encoding="utf8") as f: data = f.read() template = Template(data) # 生成模板文件 ret = template.render({'name': 'wusir', 'hobby_list': ['马杀鸡', '喝酒', '烫头']}) # 把数据填充到模板中 return bytes(ret, encoding="utf8") def home(url): with open("home.html", "r", encoding="utf8") as f: s = f.read() return bytes(s, encoding="utf8") # 定义一个url和实际要执行的函数的对应关系 list1 = [ ("/index/", index), ("/home/", home), ] def run_server(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html;charset=utf8'), ]) # 设置HTTP响应的状态码和头信息 url = environ['PATH_INFO'] # 取到用户输入的url func = None for i in list1: if i[0] == url: func = i[1] break if func: response = func(url) else: response = b"404 not found!" return [response, ] if __name__ == '__main__': httpd = make_server('127.0.0.1', 8090, run_server) print("我在8090等你哦...") httpd.serve_forever() ###index2.html <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> </head> <body> <h1>姓名:{{name}} </h1> <h1>爱好:</h1> <ul> {% for hobby in hobby_list %} <li>{{hobby}}</li> {% endfor %} </ul> </body> </html>
-
Django
1.下载
- 官网下载:https://www.djangoproject.com/download/
- 命令行:pip install django1.11.16 或 pip install django1.11.16 -i https://pypi.doubanio.com/simple/
- pycharm方式下载->settings
2.创建项目
-
命令行(windows PowerShell):django-admin startproject mysite
-
pycharm方式创建->创建项目
-
目录介绍:
- mysite/
- manage.py #管理文件
- 项目目录
- __ init __.py
- settings.py #配置
- urls.py #路由-->URL和函数的对应关系
- wsgi.py #runserver命令就使用wsgiref模块做简单的web server
- mysite/
- 启动项目
-
命令行(windows PowerShell),切换到项目目录下 manage.py:
- python ./manage.py runserver #http://127.0.0.1:8000/
- python ./manage.py runserver 80 #http://127.0.0.1
- python ./manage.py runserver 192.168.1.3:80 #http://192.168.1.3
PS C:\PycharmProjects\pythonProject\web_pro\mysite> python ./manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. July 06, 2021 - 16:43:02 Django version 3.2.4, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK.
-
pycharm方式启动
-
配置:
-
TEMPLATES
'DIRS': [os.path.join(BASE_DIR,'templates')],
-
DATABASE 数据库
-
静态文件的配置
STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static'), ]
-
-
-