一、web框架
web框架(web framwork)是一种开发框架,用来支持动态网站,网络应用和网络服务的开发。这大多数的web框架提供了一套开发和部署网站的方式,也为web行为提供了一套通用的方法。web框架已经实现了很多功能,开发人员使用框架提供的方法并且完成自己的业务逻辑,就能快速开发web应用了。浏览器和服务器的是基于HTTP协议进行通信的。也可以说web框架就是在以上十几行代码基础张扩展出来的,有很多简单方便使用的方法,大大提高了开发的效率。
二、wsgir模块
最简单的Web应用就是先把HTML用文件保存好,用一个现成的HTTP服务器软件,接收用户请求,从文件中读取HTML,返回。
如果要动态生成HTML,就需要把上述步骤自己来实现。不过,接受HTTP请求、解析HTTP请求、发送HTTP响应都是苦力活,如果我们自己来写这些底层代码,还没开始写动态HTML呢,就得花个把月去读HTTP规范。
正确的做法是底层代码由专门的服务器软件实现,我们用Python专注于生成HTML文档。因为我们不希望接触到TCP连接、HTTP原始请求和响应格式,所以,需要一个统一的接口协议来实现这样的服务器软件,让我们专心用Python编写Web业务。这个接口就是WSGI:Web Server Gateway Interface。而wsgiref模块就是python基于wsgi协议开发的服务模块。
wsgiref
1 2 3 4 5 6 7 8 9 10 11 12 13 | from wsgiref.simple_server import make_server def application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) return [b'< h1 >Hello, Web!</ h1 >'] httpd = make_server('127.0.0.1', 8080, application) print('Servering HTTP on port 8080...') # 开始监听HTTP请求 httpd.serve_forever() |
三、DIY一个web框架
models.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | import pymysql # 连接数据库 conn = pymysql.connect(host='IP', port=3306, user='root', passwd='123', db='blog') #db:库名 #创建游标 cur = conn.cursor() # sql=''' # create table userinfo( # id int primary key, # name varchar(32), # password varchar(32) # )''' # cur.execute(sql) # sql = "insert into userinfo values (%s,%s,%s)" # var = [(1, 'mike', 123), (2, 'tom', 123)] # cur.executemany(sql, var) sql = ("select * from userinfo where name='mike'") cur.execute(sql) # 提交 conn.commit() # 关闭指针对象 cur.close() # 关闭连接对象 conn.close() |
启动文件manage.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | from wsgiref.simple_server import make_server from urls import URLpattern def applications(environ, start_response): # 当前请求路径 path = environ.get("PATH_INFO") print(path) start_response('200 OK', [('Content-Type', 'text/html'), ("Charset", "utf8")]) func = None for item in URLpattern: if path == item[0]: func = item[1] break if func: return [func(environ)] else: return [b"< h1 >404!< h1 >"] if __name__ == '__main__': server = make_server("127.0.0.1", 8889, applications) print("服务器开始启动") server.serve_forever() |
urls.py
1 2 3 4 | URLpattern = ( ("/login", login), ("/favicon.ico", fav), ) |
views.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | import datetime import pymysql from urllib.parse import parse_qs 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 fav(environ): with open("templates/favicon.ico", "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 timer(environ): now = datetime.datetime.now().strftime("%y-%m-%d %x") return now.encode("utf8") def auth(request): 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"user")[0].decode("utf-8") pwd = data.get(b"pwd")[0].decode("utf-8") # 连接数据库 conn = pymysql.connect(host='10.1.2.71', port=3306, user='root', passwd='testjfz', db='blog') # 创建游标 cur = conn.cursor() SQL="select * from userinfo where name='%s' and password='%s'" %(user,pwd) cur.execute(SQL) if cur.fetchone(): f = open("templates/backend.html", "rb") data = f.read() data = data.decode("utf8") return data.encode("utf8") else: print("OK456") return b"user or pwd is wrong" |
login.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <! DOCTYPE html> < html lang="en"> < head > < meta charset="UTF-8"> < title >Title</ title > </ head > < body > < form action="http://127.0.0.1:8889/auth" method="post"> username:< input type="text" name="user">< br > password: < input type="password" name="pwd">< br > < input type="submit" name="btnsbt" value="commit"> </ form > </ body > </ html > |
backend.html
1 2 3 4 5 6 7 8 9 10 11 | <! DOCTYPE html> < html lang="en"> < head > < meta charset="UTF-8"> < title >Title</ title > </ head > < body > < h4 >欢迎来到登录页面</ h4 > </ body > </ html > |