1
while True: print('server is waiting...') conn, addr = server.accept() data = conn.recv(1024) print('data:', data) # 1.得到请求的url路径 # ------------dict/obj d=["path":"/login"] # d.get(”path“) # 按着http请求协议解析数据 # 专注于web业务开发 path = d.get('path') if path == "/login": return login.html # 按着http响应协议封装数据
2
# 报错信息 C:Windowssystem32>pip install wsgiref Collecting wsgiref Using cached https://files.pythonhosted.org/packages/41/9e/309259ce8dff8c596e8c26df86dbc4e848b9249fd36797fd60be456f03fc/wsgiref-0.1.2.zip Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:UsersVenicidAppDataLocalTemppip-build-f8zmzqr9wsgirefsetup.py", line 5, in <module> import ez_setup File "C:UsersVenicidAppDataLocalTemppip-build-f8zmzqr9wsgirefez_setup\__init__.py", line 170 print "Setuptools version",version,"or greater has been installed." ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Setuptools version",version,"or greater has been installed.")? ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:UsersVenicidAppDataLocalTemppip-build-f8zmzqr9wsgiref
# wsgiref 是标准库,不需要安装 C:Windowssystem32>python Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC >>> import wsgiref
from wsgiref.simple_server import make_server def application(environ,start_response): # 按着http协议解析数据:environ # 按着http协议组装数据:start_response print(environ) print(type(environ)) start_response('200 OK', []) return [b"<h3>hello wsgiref</h3>"] # 1.封装socket httpd = make_server("",8802,application) # 2.等待用户连接: conn,addr = server.accept() httpd.serve_forever() # application(environ,start_response)
根据path进行响应不同的html
方案1:
from wsgiref.simple_server import make_server def application(environ,start_response): # 按着http协议解析数据:environ # 按着http协议组装数据:start_response print(environ) print(type(environ)) # 当前的请求路径 path = environ.get('PATH_INFO') print(path) start_response('200 OK', []) if path == "/login": with open('login.html','r') as f: data = f.read() elif path == '/index': with open('index.html','r') as f: data = f.read() elif path == '/favicon.ico': # icon图标 with open('favicon.ico','rb') as f: data = f.read() return [data] return [data.encode('utf8')] # 1.封装socket httpd = make_server("",8802,application) # 2.等待用户连接: conn,addr = server.accept() httpd.serve_forever() # application(environ,start_response)
方案2:解耦
from wsgiref.simple_server import make_server def login(): with open('login.html', 'rb') as f: data = f.read() return data def index(): with open('index.html', 'rb') as f: data = f.read() return data def favi(): with open('favicon.ico', 'rb') as f: data = f.read() return data def application(environ, start_response): # 按着http协议解析数据:environ # 按着http协议组装数据:start_response print(environ) print(type(environ)) # 当前的请求路径 path = environ.get('PATH_INFO') start_response('200 OK', []) url_patterns = [ ("/login",login), ('/index',index), ('/favicon.ico',favi) ] func = None for item in url_patterns: if path == item[0]: func = item[1] break if func: return [func()] else: return [b'404'] # 1.封装socket httpd = make_server("", 8805, application) # 2.等待用户连接: conn,addr = server.accept() httpd.serve_forever() # application(environ,start_response)
添加新的reg模块:快速方便
添加请求environ
from wsgiref.simple_server import make_server def login(environ): with open('login.html', 'rb') as f: data = f.read() return data def index(environ): with open('index.html', 'rb') as f: data = f.read() return data def reg(environ): with open('reg.html', 'rb') as f: data = f.read() return data def favi(environ): with open('favicon.ico', 'rb') as f: data = f.read() return data def application(environ, start_response): # 按着http协议解析数据:environ # 按着http协议组装数据:start_response print(environ) print(type(environ)) # 当前的请求路径 path = environ.get('PATH_INFO') start_response('200 OK', []) url_patterns = [ ("/login",login), ('/index',index), ('/favicon.ico',favi), ('/reg',reg) ] func = None for item in url_patterns: if path == item[0]: func = item[1] break if func: return [func(environ)] else: return [b'404'] # 1.封装socket httpd = make_server("", 8805, application) # 2.等待用户连接: conn,addr = server.accept() httpd.serve_forever() # application(environ,start_response)
3、yun框架
main.py 启动程序
from wsgiref.simple_server import make_server def application(environ, start_response): path = environ.get('PATH_INFO') start_response('200 OK', []) from urls import url_patterns # 导入路由表 func = None for item in url_patterns: if path == item[0]: func = item[1] break if func: result = func(environ) # 执行视图函数 return [result] else: return [b'404'] print('start yun框架...') # 1.封装socket httpd = make_server("", 8806, application) # 2.等待用户连接: conn,addr = server.accept() httpd.serve_forever() # application(environ,start_response)
urls.py路由分发
from views import * url_patterns = [ ("/login", login), # 视图函数 ('/index', index), ('/favicon.ico', fav), ('/reg', reg), ('/timer', timer) ]
views.py 视图函数
def login(environ): with open('./templates/login.html', 'rb') as f: data = f.read() return data def index(environ): with open('./templates/index.html', 'rb') as f: data = f.read() return data def reg(environ): with open('./templates/reg.html', 'rb') as f: data = f.read() return data def fav(environ): with open('./templates/favicon.ico', 'rb') as f: data = f.read() return data def timer(environ): import datetime now_time = datetime.datetime.now().strftime('%y-%m-%d %X') return now_time.encode('utf8') # bytes类型
4、
新建 models.py 数据交换py文件
# 数据库交互文件 # 生成用户表 import pymysql # 连接数据库 conn = pymysql.connect( host='127.0.0.1', port=3306, user='root', password='root', db='db61', charset='utf8' ) # 获取游标 cursor = conn.cursor() # 执行sql语句 sql = """ create table userinfo( id int primary key, name varchar(32), password varchar(32) ) """ cursor.execute(sql) # 提交 conn.commit() # 关闭 cursor.close() conn.close()
插入一个username password
views.py中的auth函数
def auth(request): from urllib.parse import parse_qs # 分割取参数 try: request_body_size = int(request.get('CONTENT_LENGTH',0)) except (ValueError): request_body_size = 0 request_body = request['wsgi.input'].read(request_body_size) data = parse_qs(request_body) user = data.get(b'username')[0].decode('utf8') pwd = data.get(b'password')[0].decode('utf8') # 连接数据库 import pymysql conn = pymysql.connect( host='127.0.0.1', port=3306, user='root', passwd='root', db='db61', charset='utf8' ) # 创建游标 cursor = conn.cursor() # 执行sql sql = "select * from userinfo where name='%s' and password='%s'" % (user, pwd) cursor.execute(sql) if cursor.fetchone(): # 执行成功,返回一条信息 result = index(request) # 登录成功,进入index页面 return result else: return 'Error username or passwrod'.encode('utf8')
5、总结