Web框架(Web framework)是一种开发框架,用来支持动态网站、网络应用和网络服务的开发。这大多数的web框架提供了一套开发和部署网站的方式,也为web行为提供了一套通用的方法
一 web框架
二 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()
三 DIY一个web框架
3.1 启动文件:manage.py
from wsgiref.simple_server import make_server
from views import *
from urls import urlpatterns
def application(environ, start_response):
#print("environ",environ)
start_response('200 OK', [('Content-Type', 'text/html')])
# 获取当前请求路径
print("PATH_INFO",environ.get("PATH_INFO"))
path=environ.get("PATH_INFO")
# 分支
func=None
for item in urlpatterns:
if path == item[0]:
func=item[1]
break
if not func:
ret=notFound(environ)
else:
ret=func(environ)
return [ret]
httpd = make_server('', 8080, application)
# 开始监听HTTP请求:
httpd.serve_forever()
3.2 url控制文件:urls.py
from views import *
urlpatterns = [
("/login", login),
("/index", home),
]
3.3 视图文件:views.py
# 视图函数
def home(environ):
with open("templates/home.html", "rb") as f:
data = f.read()
return data
def login(environ):
with open("templates/login.html", "rb") as f:
data = f.read()
return data
def notFound(environ):
return b"<h1>404...</h1>"
3.4 模板文件Templates
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://127.0.0.1:8800" method="post">
用户名 <input type="text" name="user">
密码 <input type="text" name="pwd">
<input type="submit">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>This is index!</h3>
</body>
</html>
("/timer", timer),
def timer(request):
import datetime
now=datetime.datetime.now().strftime("%Y-%m-%d")
return now.encode()