web框架引入
1. web请求的本质就是一个socket。
2.http:一次请求,一次响应,断开链接。如下程序:必须先运行服务器端,然后客户端才能去连接。所有web框架的本质就是如下:
import socket def handle_request(client):
but = client.recv(1024)
client.send(bytes('Http/1.1 200 OK\r\n\r\n', encoding='utf-8'))
client.send(bytes('Hello Seven', encoding='utf-8')) def main():
sock = socket.socket()
sock.bind(('localhost', 8000))
sock.listen(5)
while True:
conn, addr = sock.accept()
handle_request(conn)
conn.close() if __name__ == '__main__':
main()
必须先运行服务器端,然后客户端才能去连接。必须先运行服务器端,然后客户端才能去连接。必须先运行服务器端,然后客户端才能去连接。重要的事说三遍,否则会报错。
3.wsgiref 模块就封装了server-client的功能。
上述通过socket来实现了其本质,而对于真实开发中的python web程序来说,一般会分为两部分:服务器程序和应用程序。服务器程序负责对socket服务器进行封装,并在请求到来时,对请求的各种数据进行整理。应用程序则负责具体的逻辑处理。为了方便应用程序的开发,就出现了众多的Web框架,例如:Django、Flask、web.py 等。不同的框架有不同的开发方式,但是无论如何,开发出的应用程序都要和服务器程序配合,才能为用户提供服务。这样,服务器程序就需要为不同的框架提供不同的支持。这样混乱的局面无论对于服务器还是框架,都是不好的。对服务器来说,需要支持各种不同框架,对框架来说,只有支持它的服务器才能被开发出的应用使用。这时候,标准化就变得尤为重要。我们可以设立一个标准,只要服务器程序支持这个标准,框架也支持这个标准,那么他们就可以配合使用。一旦标准确定,双方各自实现。这样,服务器可以支持更多支持标准的框架,框架也可以使用更多支持标准的服务器。
WSGI(Web Server Gateway Interface)是一种规范,它定义了使用python编写的web app与web server之间接口格式,实现web app与web server间的解耦。
python标准库提供的独立WSGI服务器称为wsgiref。
from wsgiref.simple_server import make_server def RunServer(environ, start_response): #environ 封装了客户发来的所有数据
#start_response 封装了要返回给用户的数据,响应头状态。
start_response('200 OK', [('Content-Type', 'text/html')])
#返回的内容
return [bytes('<h1>Hello, web!</h1>', encoding='utf-8'), ] if __name__ == '__main__':
httpd = make_server('', 8000, RunServer) print("Serving HTTP on port 8000...") httpd.serve_forever()
效果:
4. 插播字符串转字节的3种方式。Python2里面有unicode, python3里面有bytes.
#字符串变字节的3种方式
# b'ffff'
# bytes('ffff',encoding='utf-8')
# 'fffff'.encode('utf-8') import hashlib
m=hashlib.md5()
m.update(b'ffff')
ret=m.hexdigest()
print(ret)
5. 统一资源定位器(URL)指的是Internet文件在网上的地址。好比一个街道在城市地理上的地址。通俗点讲URL就是你的IE地址栏上的那串字符 。针对客户不同的URL,服务器端应该返回不同的内容。
如果URL=index,则返回index;如果URL=date,则返回date;否则返回404
from wsgiref.simple_server import make_server def handle_index():
return [bytes('<h1>Hello, Index!</h1>', encoding='utf-8'), ] def handle_date():
return [bytes('<h1>Hello, Date!</h1>', encoding='utf-8'), ] def RunServer(environ, start_response):
#environ 客户端发来的所有数据
#start_response 封装要返回给用户的数据,响应头状态
start_response('200 OK', [('Content-Type', 'text/html')])
current_url=environ['PATH_INFO']
if current_url=='/index':
return handle_index()
elif current_url=='/date':
return handle_date()
else:
return [bytes('<h1>404!</h1>', encoding='utf-8'), ] if __name__ == '__main__':
httpd = make_server('', 8000, RunServer)
print("Serving HTTP on port 8000...")
httpd.serve_forever()
先启动服务器端,然后测试运行效果:
6. 一个一个写太麻烦了。在Python中,会把所有的URL都放到一个列表里面。运行结果同上。
from wsgiref.simple_server import make_server def handle_index():
return [bytes('<h1>Hello, Index!</h1>', encoding='utf-8'), ] def handle_date():
return [bytes('<h1>Hello, Date!</h1>', encoding='utf-8'), ] URL_DICT={
"/index":handle_index,
"/date":handle_date,
} def RunServer(environ, start_response):
#environ 客户端发来的所有数据
#start_response 封装要返回给用户的数据,响应头状态
start_response('200 OK', [('Content-Type', 'text/html')])
current_url=environ['PATH_INFO']
func=None
if current_url in URL_DICT:
func=URL_DICT[current_url]
if func:
return func()
else:
return [bytes('<h1>404!</h1>', encoding='utf-8'), ] if __name__ == '__main__':
httpd = make_server('', 8000, RunServer)
print("Serving HTTP on port 8000...")
httpd.serve_forever()
7. 把1类写成1个函数,这样可以省略代码。
8. 也可以把要返回的内容写到一个文件里面。如下图:新建一个index.html文件,内容如下:
修改程序:
from wsgiref.simple_server import make_server def handle_index():
f=open('index.html','rb')
data=f.read()
f.close()
return [data,] def handle_date():
return [bytes('<h1>Hello, Date!</h1>', encoding='utf-8'), ] URL_DICT={
"/index":handle_index,
"/date":handle_date,
} def RunServer(environ, start_response):
#environ 客户端发来的所有数据
#start_response 封装要返回给用户的数据,响应头状态
start_response('200 OK', [('Content-Type', 'text/html')])
current_url=environ['PATH_INFO']
func=None
if current_url in URL_DICT:
func=URL_DICT[current_url]
if func:
return func()
else:
return [bytes('<h1>404!</h1>', encoding='utf-8'), ] if __name__ == '__main__':
httpd = make_server('', 8000, RunServer)
print("Serving HTTP on port 8000...")
httpd.serve_forever()
运行结果:
9. 为了整洁,可以把所有的html都放到一个文件夹下。
10. 再建立一个文件夹Controller,把所有的业务代码都放进去。
相应的调用方式修改为:
主函数里面的代码:
from wsgiref.simple_server import make_server
from Controller import account
URL_DICT={
"/index":account.handle_index,
"/date":account.handle_date,
} def RunServer(environ, start_response):
#environ 客户端发来的所有数据
#start_response 封装要返回给用户的数据,响应头状态
start_response('200 OK', [('Content-Type', 'text/html')])
current_url=environ['PATH_INFO']
func=None
if current_url in URL_DICT:
func=URL_DICT[current_url]
if func:
return func()
else:
return [bytes('<h1>404!</h1>', encoding='utf-8'), ] if __name__ == '__main__':
httpd = make_server('', 8000, RunServer)
print("Serving HTTP on port 8000...")
httpd.serve_forever()
account函数里面的代码:
def handle_index():
f=open('View/index.html','rb')
data=f.read()
f.close()
return [data,] def handle_date():
return [bytes('<h1>Hello, Date!</h1>', encoding='utf-8'), ]
把模板放到了一个文件夹里面,把处理请求的函数放到了另外一个文件夹里面。
11. 处理请求的函数里面的内容,可以跟数据库进行替换。
主程序不变:
from wsgiref.simple_server import make_server
from Controller import account
URL_DICT={
"/index":account.handle_index,
"/date":account.handle_date,
} def RunServer(environ, start_response):
#environ 客户端发来的所有数据
#start_response 封装要返回给用户的数据,响应头状态
start_response('200 OK', [('Content-Type', 'text/html')])
current_url=environ['PATH_INFO']
func=None
if current_url in URL_DICT:
func=URL_DICT[current_url]
if func:
return func()
else:
return [bytes('<h1>404!</h1>', encoding='utf-8'), ] if __name__ == '__main__':
httpd = make_server('', 8000, RunServer)
print("Serving HTTP on port 8000...")
httpd.serve_forever()
处理请求的函数修改为:
def handle_index():
f=open('View/index.html','rb')
data=f.read()
f.close()
data=data.replace(b'@123','今天天气好晴朗'.encode('utf-8'))
return [data,] def handle_date():
return [bytes('<h1>Hello, Date!</h1>', encoding='utf-8'), ]
运行效果:
12. 类似于每次访问数据库,都可以从数据库中拿到不同的数据。下面以time为例,将处理请求的函数修改如下:
def handle_index():
import time
v=str(time.time()) f=open('View/index.html','rb')
data=f.read()
f.close()
data=data.replace(b'@123',v.encode('utf-8'))
return [data,] def handle_date():
return [bytes('<h1>Hello, Date!</h1>', encoding='utf-8'), ]
运行结果:
13. 为了规整,把数据库都放到另外一个文件夹下面。命名为model.
本节笔记:MVC与MTV的区别在仅仅于文件名的不同。上述例子是基于MVC创建的,只要把文件名一改,就成为了MTV的框架格式了。
3.WEB框架 MVC
Model View Controller
数据库 模板文件 业务处理 MTV
Model Template View
数据库 模板文件 业务处理 ###########################WEB:MVC,MTV
web框架引入的更多相关文章
- Web框架的引入
为什么会有web框架 有了上一篇内容,静态.动态web服务器的实现,已经掌握了客户端请求到服务器处理的机制.在动态资源处理中,根据请求 .py 导入模块应用,然后调用应用入口程序实现动态处理.但是在真 ...
- Python之Web框架Django
Python之Web框架: Django 一. Django Django是一个卓越的新一代Web框架 Django的处理流程 1. 下载地址 Python 下载地址:https://www.pyt ...
- Spring 5 新特性:函数式Web框架
举例 我们先从示例应用程序的一些摘录开始.下面是暴露Person对象的响应信息库.很类似于传统的,非响应信息库,只不过它返回Flux<Person>而传统的返回List<Person ...
- 关于Python的web框架
uliwebhttp://git.oschina.net/limodou/uliweb uliweb 吸取了其他框架的经验,集成了orm.总的来说一般.这个安装后有个exe文件,命令行工具.不绿色.个 ...
- python_way day17 html-day3 前端插件(fontawsome,easyui,bootstrap,jqueryui,bxslider,jquerylazyload),web框架
python_way day17 一.模板插件 图标的插件 fontawsome: 后台管理: easyui jqueryui 很多网站都会用: bootstrap :引入jQuery:(2.x,1. ...
- Day17 表单验证、滚动菜单、WEB框架
一.表单验证的两种实现方式 1.DOM绑定 <!DOCTYPE html> <html lang="en"> <head> <meta c ...
- Python开发【第二十二篇】:Web框架之Django【进阶】
Python开发[第二十二篇]:Web框架之Django[进阶] 猛击这里:http://www.cnblogs.com/wupeiqi/articles/5246483.html 博客园 首页 ...
- python运维开发(十七)----jQuery续(示例)web框架django
内容目录: jQuery示例 前端插件 web框架 Django框架 jQuery示例 dom事件绑定,dom绑定在form表单提交按钮地方都会绑定一个onclick事件,所有查看网站的人都能看到代码 ...
- Python超级明星WEB框架Flask
Flask简介 Flask是一个相对于Django而言轻量级的Web框架. 和Django大包大揽不同,Flask建立于一系列的开源软件包之上,这其中 最主要的是WSGI应用开发库Werkzeug和模 ...
随机推荐
- 【vijos1049】送给圣诞夜的礼品
题面 描述 当小精灵们把贺卡都书写好了之后.礼品准备部的小精灵们已经把所有的礼品都制作好了.可是由于精神消耗的缘故,他们所做的礼品的质量越来越小,也就是说越来越不让圣诞老人很满意.可是这又是没有办法的 ...
- hive 日志
hive中日志分为两种: 1 系统日志,记录hive运行情况,错误状态 2 job日志 , 记录hive中 job执行的历史过程 系统日志存储位置: 配置在 hive/conf/hive-log4j. ...
- javaweb(二十一)——JavaWeb的两种开发模式
一.JSP+JavaBean开发模式 1.1.jsp+javabean开发模式架构 jsp+javabean开发模式的架构图如下图(图1-1)所示
- Raft 一致性协议算法 《In search of an Understandable Consensus Algorithm (Extended Version)》
<In search of an Understandable Consensus Algorithm (Extended Version)> Raft是一种用于管理日志复制的一致性算 ...
- Redis 指令
一个key可以存放将近40亿条数据 选择库 select 2 (代表选择第三个库) 增加key set db_number 11 删除key del key 获取值 get db_n ...
- 4.openldap创建索引
1.索引的意义 提高对Openldap目录树的查询速度 提高性能 减轻对服务器的压力 2.搜索索引 ldapsearch -Q -LLL -Y EXTERNAL -H ldapi:/// -b cn= ...
- iOS开发 常见错误
一.NSAppTransportSecurity 错误提示:NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL ...
- 团队Alpha冲刺(十)
目录 组员情况 组员1(组长):胡绪佩 组员2:胡青元 组员3:庄卉 组员4:家灿 组员5:凯琳 组员6:翟丹丹 组员7:何家伟 组员8:政演 组员9:黄鸿杰 组员10:刘一好 组员11:何宇恒 展示 ...
- lintcode-387-最小差
387-最小差 给定两个整数数组(第一个是数组 A,第二个是数组 B),在数组 A 中取 A[i],数组 B 中取 B[j],A[i] 和 B[j]两者的差越小越好(|A[i] - B[j]|).返回 ...
- erlang随机排列数组
参考karl's answer 1> L = lists:seq(1,10). [1,2,3,4,5,6,7,8,9,10] Associate a random number R with e ...