Django【二】自定义web框架
自定义web框架
1、准备登录的html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="icon" href="favicon.ico"> </head> <body> <!--提交的位置 点击提交按钮相当于请求了这个网址--> <form action="http://127.0.0.1:9000/auth" method="get"> <input type="text" name="username" placeholder="username"> <input type="password" name="password" placeholder="password"> <button>提交</button> </form> </body> </html> 登录页面
2、将HTML页面发送到服务端
# -*- coding: utf-8 -*- # @Time : 2019/5/16 19:16 import webauth from wsgiref.simple_server import make_server from urllib.parse import parse_qs def auth(environ): # 判断提交按钮的请求是什么请求 if environ.get("REQUEST_METHOD")=="GET": # 获取用户输入的信息 username=xiaohei&password=123 request_data = environ['QUERY_STRING'] # 对信息进行解析 {'username': ['xiaohei'], 'password': ['123']} re_data = parse_qs(request_data) # 分别取出用户名和密码 username = re_data['username'][0] password = re_data['password'][0] # 提交给服务器进行验证 ret = webauth.auth(username,password) # 服务器返回验证信息 if ret: with open("websuccess.html", "rb") as f: content = f.read() return [content] else: # 验证失败 return [b"login failure"] def login(environ): with open("login.html","rb") as f: content = f.read() return [content] def log(environ): with open("favicon.ico","rb") as f: content = f.read() return [content] li = [ ("/login",login), ("/favicon.ico",log), ("/auth",auth), ] def app(environ, start_response): # 封装响应信息 start_response('200 OK', [('Content-Type', 'text/html'), ('k1', 'v1')]) # environ 封装好的请求数据,字典的格式 path = environ["PATH_INFO"] for i in li: # 判断用户输入的url if i[0] == path: # 调用url对应的函数 ret = i[1](environ) return ret break else: # 用户输入的网址不合法 return [b"404 not found"] # 绑定ip和端口,有人连接就调用app函数 httpp = make_server("127.0.0.1",9000,app) # 开始监听http请求 httpp.serve_forever() 服务端页面
3、数据库验证登录信息
# -*- coding: utf-8 -*- # @Time : 2019/5/16 19:42 import pymysql # 数据库信息验证,验证用户名和密码 def auth(username,password): db = pymysql.connect( host="127.0.0.1", port=3306, user="root", password="root", database="day53", charset="utf8" # 不能写- ) cursor = db.cursor(pymysql.cursors.DictCursor) sql = "select * from info where username=%s and password=%s;" res = cursor.execute(sql,[username,password]) print(res) if res: return True else: return False 验证登录
4、返回登录成功页面