web应用与web框架(Day65)
Web应用
对于所有的web应用,本质上其实就是一个socket服务端,用户的浏览器其实就是一个socket客户端
import socket def handle_request(client): buf = client.recv(1024) client.send("HTTP/1.1 200 OK\r\n\r\n".encode("utf8")) client.send("<h1 style='color:red'>Hello, yuan</h1>".encode("utf8")) def main(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('localhost',8001)) sock.listen(5) while True: connection, address = sock.accept() handle_request(connection) connection.close() if __name__ == '__main__': main()
最简单的web应用就是先把HTML用文件保存好,用一个现成的HTTP服务器软件,接受用户请求,接受用户请求并返回
如果要动态生成HTML,就需要把上述步骤自己来实现。不过,接受HTTP请求、解析HTTP请求、发送HTTP响应都是苦力活,如果我们自己来写这些底层代码,还没开始写动态HTML呢,就得花个把月去读HTTP规范。
正确的做法是底层代码由专门的服务器软件实现,我们用Python专注于生成HTML文档。因为我们不希望接触到TCP连接、HTTP原始请求和响应格式,所以,需要一个统一的接口,让我们专心用Python编写Web业务。
这个接口就是WSGI:Web Server Gateway Interface。
wsgiref模块
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('', 8080, application) print('Serving HTTP on port 8000...') # 开始监听HTTP请求: httpd.serve_forever()
对比socketserver模块
DIY一个自己的web框架
manage.py
from wsgiref.simple_server import make_server # request response from app01.views import * from app01 import urls def routers(): URLpattern=urls.URLpattern return URLpattern def applications(environ,start_response): path=environ.get("PATH_INFO") print("path",path) start_response('200 OK', [('Content-Type', 'text/html'),('Charset', 'utf8')]) urlpattern=routers() 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>"] # return [b"<h1>hello world<h1>"] if __name__ == '__main__': t=make_server("",8810,applications) print("server is working...") t.serve_forever()
urls
from app01.views import * URLpattern = ( ("/login/", login), )
views
import pymysql from urllib.parse import parse_qs def login(request): if request.get("REQUEST_METHOD")=="POST": print("+++++",request) #当请求方式是GET时 # user_union,pwd_union=request.get("QUERY_STRING").split("&") # _,user=user_union.split("=") # _,pwd=pwd_union.split("=") # 环境变量 CONTENT_LENGTH 可能是空值 或者 值丢失 try: request_body_size = int(request.get('CONTENT_LENGTH', 0)) except (ValueError): request_body_size = 0 # 当请求方式是POST时, 变量将会被放在存在域wsgi.input文件中的HTTP请求信息中, 由WSGI 服务器一起发送. request_body = request['wsgi.input'].read(request_body_size) d = parse_qs(request_body) user=d.get(b"user")[0].decode("utf8") pwd=d.get(b"pwd")[0].decode("utf8") print("user",user,pwd) #连接数据库 conn = pymysql.connect(host='',port= 3306,user = 'root',passwd='',db='s6') #db:库名 #创建游标 cur = conn.cursor() SQL="select * from userinfo2 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"))%user return data.encode("utf8") else: return b"user or pwd is wrong" else: f = open("templates/login.html", "rb") data = f.read() f.close() return data
models
import pymysql import pymysql #连接数据库 conn = pymysql.connect(host='',port= 3306,user = 'root',passwd='',db='s6') #db:库名 #创建游标 cur = conn.cursor() # sql=''' # create table userinfo2( # id INT PRIMARY KEY , # name VARCHAR(32) , # password VARCHAR(32) # ) # # ''' # # cur.execute(sql) # # cur.executemany("insert into userinfo2 values(%s,%s,%s)", [(1,"yuan","123"), # (2,"alex","456"), # (3,"egon","789")]) cur.execute("select * from userinfo2 WHERE NAME='yuan' AND PASSWORD ='123'") #提交 conn.commit() #关闭指针对象 cur.close() #关闭连接对象 conn.close()
有一种能力,是持续不断的努力