python web框架学习笔记

一、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这个函数。

原理图:

 

当用户发送请求,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被独特的发展起来用于映射传统的输入、处理和输出功能在一个逻辑的图形化用户界面的结构中。

将路由规则放入urls.py

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

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

将html页面等放入views里

原理图:

2.MTV

Models 处理DB操作

Templates html模板

Views 处理函数请求

原理图:

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

时间: 2024-08-16 00:16:46

python web框架学习笔记的相关文章

Python Web框架学习【Flask】

了解flask flask 是利用Python编写的轻量级Web应用框架 Flask也被称为 "microframework" ,因为它使用简单的核心,用 extension 增加其他功能. Flask没有默认使用的数据库.窗体验证工具. 其 WSGI 工具箱采用 Werkzeug 模板引擎则使用 Jinja2 Flask使用 BSD 授权 WSGI(PythonWeb服务器网关接口) Python Web Server Gateway InterfacePython应用程序或框架和W

python web 服务器学习笔记(四)

在开始新内容之前,我们先解决socket error 98:Address already in use问题 很容易发现可能是由于端口被占用导致的,端口被占用又有很多可能,比如说的关闭你挂上去的服务器,然后又秒开,你会发现这个错误. 此时似乎是由于tcp本身的特性,端口未来得及释放导致的 我们可以通过以下命令查看端口的使用情况,并试着处理它 kill -9 [进程id] 杀死该进程 lsof -i:[端口号]查看端口属于哪个程序 netstrat tln | grep [端口号]查看端口使用情况

python web服务器学习笔记(五) 并发尝试之popen原理探究

使用popen新开进程能实现并发吗?像这样的cgi处理程序 def run_cgi(self,handler): cmd = "python" +handler.full_path child_stdin,child_stdout=os.popen2(cmd) child_stdin.close() data=child_stdout.read() child_stdout.close() handler.send_content(data) 我让它跑 for i in range(1

python django框架学习笔记(三)--大结局

一.数据库同步操作技巧 1.认识一个目录 目录名:migatations 作用,用来存放通过makemigrations命令生成的数据库脚本.app目录下必须要有migrations目录切目录下必须要有__init__.py才能正常的使用数据库同步功能. 2.认识一张数据表(django_migrations) 表中的字段: app:app名字 name:脚本的文件名称 applied:脚本执行时间 3.数据库相关的命令 flush:清空数据库-恢复数据库到最初的状态 makemigration

python web框架分析和学习篇_彭友

分析篇: 刚好到网上搜到了一篇<浅谈Python web框架>,里面系统的分析了五种主流的Python框架,现在python的主流框架有Django.Pylons&TurboGears&repose.bfg.Tornado&web.py&Bottle&Flask和Quixote.它从宏观角度分析了这五种框架的优劣,看完之后我们决定选择Django,因为: Django: 概述:可谓是python框架里面最大的一家,它是里面文档最完善.市场占有率最高.招聘

Django Web开发学习笔记(5)

第五部分 Model 层 创建一个app工程.app和project的区别引用DjangoBook的说法是: 一个project包含很多个Django app以及对它们的配置. 技术上,project的作用是提供配置文件,比方说哪里定义数据库连接信息, 安装的app列表, TEMPLATE_DIRS ,等等. 一个app是一套Django功能的集合,通常包括模型和视图,按Python的包结构的方式存在. 例如,Django本身内建有一些app,例如注释系统和自动管理界面. app的一个关键点是它

windows下scrapy框架学习笔记—&#39;scrapy&#39; 不是内部或外部命令

最近几天在深入的学习scrapy框架,但是装完各种需要的基础包之后却发现scrapy命令在别的路径下都用不了,我一开始是把python安装在F:\Python路径下的,安装了scrapy后它默认都会安装在这个路径下,scrapy在路径F:\Python\Scripts路径下,我的scrapy命令只能在此路径下用,因此创建什么工程也都只能在此文件下. 想了一下它的工作原理:它在F:\Python\Scripts路径下,就会在Scripts文件下存在一个scrapy批处理文件,那么在DOS下想要命令

Python web 框架 Sanci如何使用?

本文和大家分享的主要是python web 框架 Sanci 相关内容,一起来看看吧,希望对大家学习python有所帮助. Sanic 是一个和类Flask 的基于Python3.5+的web框架,它编写的代码速度特别快. 除了像Flask 以外,Sanic 还支持以异步请求的方式处理请求.这意味着你可以使用新的 async/await 语法,编写非阻塞的快速的代码. 既然它说速度特别快,我们先看下官方提供的 基准测试结果. Sanic基准测试 这个测试的程序运行在 AWS 实例上,系统是Ubu

Web框架——Django笔记

Web框架——Django笔记 MVC和MTV MVC:Model.View.Controller MTV:Model.Template.View Django——MTV 1.创建Django程序   (注:创建前需注意配置Django环境变量,python2.7和3.5环境变量) a.命令(使用cmd命令创建) django-admin startproject mysite      创建project cd mysite python manage.py startapp app01