python web框架学习笔记


Posted in Python onMay 03, 2016

一、web框架本质

1.基于socket,自己处理请求

#!/usr/bin/env python3
#coding:utf8
import socket
def handle_request(client):
 #接收请求
 buf = client.recv(1024)
 print(buf)
 #返回信息
 client.send(bytes('<h1>welcome liuyao webserver</h1>','utf8'))
def main():
 #创建sock对象
 sock = socket.socket()
 #监听80端口
 sock.bind(('localhost',8000))
 #最大连接数
 sock.listen(5)
 print('welcome nginx')
 #循环
 while True:
 #等待用户的连接,默认accept阻塞当有请求的时候往下执行
 connection,address = sock.accept()
 #把连接交给handle_request函数
 handle_request(connection)
 #关闭连接
 connection.close()
if __name__ == '__main__':
 main()

2.基于wsgi

WSGI,全称 Web Server Gateway Interface,或者 Python Web Server Gateway Interface ,是为 Python 语言定义的 Web 服务器和 Web 应用程序或框架之间的一种简单而通用的接口。自从 WSGI 被开发出来以后,许多其它语言中也出现了类似接口。

WSGI 的官方定义是,the Python Web Server Gateway Interface。从名字就可以看出来,这东西是一个Gateway,也就是网关。网关的作用就是在协议之间进行转换。

WSGI 是作为 Web 服务器与 Web 应用程序或应用框架之间的一种低级别的接口,以提升可移植 Web 应用开发的共同点。WSGI 是基于现存的 CGI 标准而设计的。

很多框架都自带了 WSGI server ,比如 Flask,webpy,Django、CherryPy等等。当然性能都不好,自带的 web server 更多的是测试用途,发布时则使用生产环境的 WSGI server或者是联合 nginx 做 uwsgi 。

python标准库提供的独立WSGI服务器称为wsgiref。

#!/usr/bin/env python
#coding:utf-8
#导入wsgi模块
from wsgiref.simple_server import make_server

def RunServer(environ, start_response):
 start_response('200 OK', [('Content-Type', 'text/html')])
 return [bytes("welcome webserver".encode('utf8'))]

if __name__ == '__main__':
 httpd = make_server('', 8000, RunServer)
 print ("Serving HTTP on port 8000...")
 httpd.serve_forever()
 #接收请求
 #预处理请求(封装了很多http请求的东西)

请求过来后就执行RunServer这个函数。

原理图:

python web框架学习笔记

当用户发送请求,socket将请求交给函数处理,之后再返回给用户。

二、自定义web框架

python标准库提供的wsgiref模块开发一个自己的Web框架

之前的使用wsgiref只能访问一个url
下面这个可以根据你访问的不同url请求进行处理并且返回给用户

#!/usr/bin/env python
#coding:utf-8
from wsgiref.simple_server import make_server
def RunServer(environ, start_response):
 start_response('200 OK', [('Content-Type','text/html')])
 #根据url的不同,返回不同的字符串
 #1 获取URL[URL从哪里获取?当请求过来之后执行RunServer,
 #wsgi给咱们封装了这些请求,这些请求都封装到了,environ & start_response]
 request_url = environ['PATH_INFO']
 print (request_url)
 #2 根据URL做不同的相应
 #print environ #这里可以通过断点来查看它都封装了什么数据
 if request_url == '/login':
  return [bytes("welcome login",'utf8')]
 elif request_url == '/reg':
  return [bytes("welcome reg",'utf8')]
 else:
  return [bytes('<h1>404! no found</h1>','utf8')]

if __name__ == '__main__':
 httpd = make_server('', 8000, RunServer)
 print ("Serving HTTP on port 8000...")
 httpd.serve_forever()

当然 以上虽然根据不同url来进行处理,但是如果大量url的话,那么代码写起来就很繁琐。
所以使用下面方法进行处理

#!/usr/bin/env python
#coding:utf-8
from wsgiref.simple_server import make_server
def index():
 return [bytes('<h1>index</h1>','utf8')]
def login():
 return [bytes('<h1>login</h1>','utf8')]
def reg():
 return [bytes('<h1>reg</h1>','utf8')]
def layout():
 return [bytes('<h1>layout</h1>','utf8')]
#定义一个列表 把url和上面的函数做一个对应
urllist = [
 ('/index',index),
 ('/login',login),
 ('/reg',reg),
 ('/layout',layout),
]
def RunServer(environ, start_response):
 start_response('200 OK', [('Content-Type','text/html')])
 #根据url的不同,返回不同的字符串
 #1 获取URL[URL从哪里获取?当请求过来之后执行RunServer,wsgi给咱们封装了这些请求,这些请求都封装到了,environ & start_response]
 request_url = environ['PATH_INFO']
 print (request_url)
 #2 根据URL做不同的相应
 #print environ #这里可以通过断点来查看它都封装了什么数据
 #循环这个列表 找到你打开的url 返回url对应的函数
 for url in urllist:
  if request_url == url[0]:
   return url[1]()
 else:
  #url_list列表里都没有返回404
  return [bytes('<h1>404 not found</h1>','utf8')] 
if __name__ == '__main__':
 httpd = make_server('', 8000, RunServer)
 print ("Serving HTTP on port 8000...")
 httpd.serve_forever()

三、模板引擎
对应上面的操作 都是根据用户访问的url返回给用户一个字符串的 比如return xxx

案例:

首先写一个index.html页面

内容:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<h1>welcome index</h1>
</body>
</html>

login.html页面

内容:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>login</title>
</head>
<body>
 <h1>welcome login</h1>
 <form>
  user:<input type="text"/>
  pass:<input type="password"/>
  <button type="button">login in</button>
 </form>
</body>
</html>

python代码:

#!/usr/bin/env python 
#coding:utf-8
from wsgiref.simple_server import make_server
def index():
 #把index页面读进来返回给用户
 indexfile = open('index.html','r+').read()
 return [bytes(indexfile,'utf8')]
def login():
 loginfile = open('login.html','r+').read()
 return [bytes(loginfile,'utf8')]
urllist = [
 ('/login',login),
 ('/index',index),
]
def RunServer(environ, start_response):
 start_response('200 OK', [('Content-Type','text/html')])
 #根据url的不同,返回不同的字符串
 #1 获取URL[URL从哪里获取?当请求过来之后执行RunServer,wsgi给咱们封装了这些请求,这些请求都封装到了,environ & start_response]
 request_url = environ['PATH_INFO']
 print (request_url)
 #2 根据URL做不同的相应
 #print environ #这里可以通过断点来查看它都封装了什么数据
 for url in urllist:
  #如果用户请求的url和咱们定义的rul匹配
  if request_url == url[0]:
   #执行
   return url[1]()
 else:
  #url_list列表里都没有返回404
  return [bytes('<h1>404 not found</h1>','utf8')]
if __name__ == '__main__':
 httpd = make_server('', 8000, RunServer)
 print ("Serving HTTP on port 8000...")
 httpd.serve_forever()

但是以上内容只能返回给静态内容,不能返回动态内容
那么如何返回动态内容呢

自定义一套特殊的语法,进行替换

使用开源工具jinja2,遵循其指定语法

index.html 遵循jinja语法进行替换、循环、判断

先展示大概效果,具体jinja2会在下章django笔记来进行详细说明

index.html页面

内容:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
</head>
<body>
 <!--general replace-->
 <h1>{{ name }}</h1>
 <h1>{{ age }}</h1>
 <h1>{{ time }}</h1>

 <!--for circular replace-->
 <ul>
  {% for item in user_list %}
   <li>{{ item }}</li>
  {% endfor %}
 </ul>
 <!--if else judge-->
 {% if num == 1 %}
  <h1>num == 1</h1>
 {% else %}
  <h1>num == 2</h1>
 {% endif %}
</body>
</html>

python代码:

#!/usr/bin/env python
#-*- coding:utf-8 -*-
import time 
#导入wsgi模块
from wsgiref.simple_server import make_server
#导入jinja模块
from jinja2 import Template
def index():
 #打开index.html
 data = open('index.html').read()
 #使用jinja2渲染
 template = Template(data)
 result = template.render(
  name = 'yaoyao',
  age = '18',
  time = str(time.time()),
  user_list = ['linux','python','bootstarp'],
  num = 1
 )
 #同样是替换为什么用jinja,因为他不仅仅是文本的他还支持if判断 & for循环 操作
 #这里需要注意因为默认是的unicode的编码所以设置为utf-8
 return [bytes(result,'utf8')]
urllist = [
 ('/index',index),
]
def RunServer(environ, start_response):
 start_response('200 OK', [('Content-Type', 'text/html')])
 #根据url的不同,返回不同的字符串
 #1 获取URL[URL从哪里获取?当请求过来之后执行RunServer,
 # wsgi给咱们封装了这些请求,这些请求都封装到了,environ & start_response]
 request_url = environ['PATH_INFO']
 print(request_url)
 #2 根据URL做不同的相应
 #循环这个列表
 for url in urllist:
  #如果用户请求的url和咱们定义的rul匹配
  if request_url == url[0]:
   print (url)
   return url[1]()
 else:
  #urllist列表里都没有返回404
  return [bytes('<h1>404 not found</h1>','utf8')]
if __name__ == '__main__':
 httpd = make_server('', 8000, RunServer)
 print ("Serving HTTP on port 8000...")
 httpd.serve_forever()

四、MVC和MTV

1.MVC

全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。MVC被独特的发展起来用于映射传统的输入、处理和输出功能在一个逻辑的图形化用户界面的结构中。

python web框架学习笔记

将路由规则放入urls.py

操作urls的放入controller里的func函数

将数据库操作党风model里的db.py里

将html页面等放入views里

原理图:

python web框架学习笔记

2.MTV

Models 处理DB操作

Templates html模板

Views 处理函数请求

python web框架学习笔记

原理图:

python web框架学习笔记

以上就是本文的全部内容,希望对大家的学习有所帮助。

Python 相关文章推荐
在Linux系统上通过uWSGI配置Nginx+Python环境的教程
Dec 25 Python
python 图像平移和旋转的实例
Jan 10 Python
python实现多层感知器
Jan 18 Python
Python制作微信好友背景墙教程(附完整代码)
Jul 17 Python
python3.8下载及安装步骤详解
Jan 15 Python
python通过文本在一个图中画多条线的实例
Feb 21 Python
windows、linux下打包Python3程序详细方法
Mar 17 Python
Java如何基于wsimport调用wcf接口
Jun 17 Python
Python爬虫教程知识点总结
Oct 19 Python
python实现三种随机请求头方式
Jan 05 Python
将Python代码打包成.exe可执行文件的完整步骤
May 12 Python
Pytorch使用shuffle打乱数据的操作
May 20 Python
Python批量修改文本文件内容的方法
Apr 29 #Python
Python+Opencv识别两张相似图片
Mar 23 #Python
Python实现包含min函数的栈
Apr 29 #Python
Python二叉搜索树与双向链表转换实现方法
Apr 29 #Python
Python实现简单字典树的方法
Apr 29 #Python
Python中操作符重载用法分析
Apr 29 #Python
Python中绑定与未绑定的类方法用法分析
Apr 29 #Python
You might like
DOMXML函数笔记
2006/10/09 PHP
用PHP和ACCESS写聊天室(八)
2006/10/09 PHP
php面向对象全攻略 (八)重载新的方法
2009/09/30 PHP
微盾PHP脚本加密专家php解密算法
2020/09/13 PHP
让PHP显示Facebook的粉丝数量方法
2014/01/08 PHP
thinkPHP实现将excel导入到数据库中的方法
2016/04/22 PHP
PHP基于双向链表与排序操作实现的会员排名功能示例
2017/12/26 PHP
JQuery 无废话系列教程(一) jquery入门 [推荐]
2009/06/23 Javascript
选择TreeView控件的树状数据节点的JS方法(jquery)
2010/02/06 Javascript
自己封装的javascript事件队列函数版
2014/06/12 Javascript
Js制作点击输入框时默认文字消失的效果
2015/09/05 Javascript
浅谈bootstrap使用中的一些问题以及解决过程
2016/10/18 Javascript
详解vue-cli + webpack 多页面实例应用
2017/04/25 Javascript
Vue.js 中的实用工具方法【推荐】
2019/07/04 Javascript
Vue学习之组件用法实例详解
2020/01/06 Javascript
使用vue打包进行云服务器上传的问题
2020/03/02 Javascript
Python基础语法(Python基础知识点)
2016/02/28 Python
Python简单格式化时间的方法【strftime函数】
2016/09/18 Python
python实现多线程抓取知乎用户
2016/12/12 Python
python实现两张图片的像素融合
2019/02/23 Python
python图形绘制奥运五环实例讲解
2019/09/14 Python
python matplotlib中的subplot函数使用详解
2020/01/19 Python
Python requests获取网页常用方法解析
2020/02/20 Python
Python如何读取、写入JSON数据
2020/07/28 Python
Python classmethod装饰器原理及用法解析
2020/10/17 Python
Django如何继承AbstractUser扩展字段
2020/11/27 Python
HTML5混合开发二维码扫描以及调用本地摄像头
2017/12/27 HTML / CSS
美国益智玩具购物网站:Fat Brain Toys
2017/11/03 全球购物
解释下面关于J2EE的名词
2013/11/15 面试题
党员公开承诺践诺书
2014/03/25 职场文书
党员个人党性分析材料
2014/12/18 职场文书
财产保全担保书
2015/01/20 职场文书
五一劳动节慰问信
2015/02/14 职场文书
2015年大学生入党自荐书
2015/03/24 职场文书
诚实守信主题班会
2015/08/13 职场文书
简单聊聊TypeScript只读修饰符
2022/04/06 Javascript