python-web框架
2019-03-13 本文已影响7人
wangcc_sd
一个简单的web框架,web框架的概念。
main.py 启动文件,封装了socket
1、urls.py 路径和视图函数的映射关系 -----url控制器
2、views.py 视图函数,固定有一个形式参数 :environ -视图函数
3、templates 文件夹 html文件夹
4、models :在项目启动前,在数据库中创建表结构
------->main.py
# -*-coding:utf-8 -*-
# BY WANGCC
# -*-coding:utf-8 -*-
# BY WANGCC
from wsgiref.simple_server import make_server
from views import *
import urls import URLpattern
def routers():
URLpattern=urls.URLpattern
return URLpattern
def applications(environ,start_response):
path=environ.get("PATH_INFO")
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>"]
if __name__ == '__main__':
server=make_server("",8889,applications)
print("server is working...")
server.serve_forever()
------->models.py
# -*-coding:utf-8 -*-
# BY WANGCC
import pymysql
#连接数据库
conn = pymysql.connect(host='127.0.0.1',port= 3306,user = 'root',passwd='xxxxxxx#)t',db='web') #db:库名
#创建游标
cur = conn.cursor()
sql='''
create table userinfo(
id INT PRIMARY KEY ,
name VARCHAR(32) ,
password VARCHAR(32)
)
'''
cur.execute(sql)
#提交
conn.commit()
#关闭指针对象
cur.close()
#关闭连接对象
conn.close()
------->urls.py
# -*-coding:utf-8 -*-
# BY WANGCC
from views import *
URLpattern = (
("/login/", login),
)
------->views.py
# -*-coding:utf-8 -*-
# BY WANGCC
import pymysql
from urllib.parse import parse_qs
def login(request):
if request.get("REQUEST_METHOD")=="POST":
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("utf8")
pwd=data.get(b"pwd")[0].decode("utf8")
#连接数据库
conn = pymysql.connect(host='127.0.0.1',port= 3306,user = 'root',passwd='xxxxx#)t',db='web') # db:库名
#创建游标
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"
else:
f = open("templates/login.html", "rb")
data = f.read()
f.close()
return data
with open('templates/reg.html','rb') as f:
date = f.read()
return date
------->login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h4>登录页面</h4>
<form action="" method="post">
用户名 <input type="text" name="user">
密码 <input type="text" name="pwd">
<input type="submit">
</form>
</body>
</html>