찾다
백엔드 개발파이썬 튜토리얼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 id="welcome-liuyao-webserver">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从哪里获取&#63;当请求过来之后执行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 id="no-found">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 id="index">index</h1>','utf8')]
def login():
 return [bytes('<h1 id="login">login</h1>','utf8')]
def reg():
 return [bytes('<h1 id="reg">reg</h1>','utf8')]
def layout():
 return [bytes('<h1 id="layout">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从哪里获取&#63;当请求过来之后执行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 id="not-found">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 id="welcome-index">welcome index</h1>
</body>
</html>

login.html页面

内容:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>login</title>
</head>
<body>
 <h1 id="welcome-login">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从哪里获取&#63;当请求过来之后执行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 id="not-found">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 id="name">{{ name }}</h1>
 <h1 id="age">{{ age }}</h1>
 <h1 id="time">{{ time }}</h1>

 <!--for circular replace-->
 <ul>
  {% for item in user_list %}
   <li>{{ item }}</li>
  {% endfor %}
 </ul>
 <!--if else judge-->
 {% if num == 1 %}
  <h1 id="num">num == 1</h1>
 {% else %}
  <h1 id="num">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从哪里获取&#63;当请求过来之后执行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 id="not-found">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 处理函数请求

原理图:

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

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
목록과 배열 사이의 선택은 큰 데이터 세트를 다루는 파이썬 응용 프로그램의 전반적인 성능에 어떤 영향을 미칩니 까?목록과 배열 사이의 선택은 큰 데이터 세트를 다루는 파이썬 응용 프로그램의 전반적인 성능에 어떤 영향을 미칩니 까?May 03, 2025 am 12:11 AM

forhandlinglargedatasetsinpython, usenumpyarraysforbetterperformance.1) numpyarraysarememory-effic andfasterfornumericaloperations.2) leveragevectorization foredtimecomplexity.4) managemoryusage withorfications data

Python의 목록 대 배열에 대한 메모리가 어떻게 할당되는지 설명하십시오.Python의 목록 대 배열에 대한 메모리가 어떻게 할당되는지 설명하십시오.May 03, 2025 am 12:10 AM

inpython, listsusedyammoryAllocation과 함께 할당하고, whilempyarraysallocatefixedMemory.1) listsAllocatemememorythanneedInitiality.

파이썬 어레이에서 요소의 데이터 유형을 어떻게 지정합니까?파이썬 어레이에서 요소의 데이터 유형을 어떻게 지정합니까?May 03, 2025 am 12:06 AM

Inpython, youcansspecthedatatypeyfelemeremodelerernspant.1) usenpynernrump.1) usenpynerp.dloatp.ploatm64, 포모 선례 전분자.

Numpy 란 무엇이며 Python의 수치 컴퓨팅에 중요한 이유는 무엇입니까?Numpy 란 무엇이며 Python의 수치 컴퓨팅에 중요한 이유는 무엇입니까?May 03, 2025 am 12:03 AM

numpyissentialfornumericalcomputinginpythonduetoitsspeed, memory-efficiency 및 comperniveMathematicaticaltions

'연속 메모리 할당'의 개념과 배열의 중요성에 대해 토론하십시오.'연속 메모리 할당'의 개념과 배열의 중요성에 대해 토론하십시오.May 03, 2025 am 12:01 AM

contiguousUousUousUlorAllocationScrucialForraysbecauseItAllowsOfficationAndFastElementAccess.1) ItenableSconstantTimeAccess, o (1), DuetodirectAddressCalculation.2) Itimprovesceeffiency theMultipleementFetchespercacheline.3) Itsimplififiesmomorym

파이썬 목록을 어떻게 슬라이스합니까?파이썬 목록을 어떻게 슬라이스합니까?May 02, 2025 am 12:14 AM

slicepaythonlistisdoneusingthesyntaxlist [start : step : step] .here'showitworks : 1) startistheindexofthefirstelementtoinclude.2) stopistheindexofthefirstelemement.3) stepisincrementbetwetweentractionsoftortionsoflists

Numpy Array에서 수행 할 수있는 일반적인 작업은 무엇입니까?Numpy Array에서 수행 할 수있는 일반적인 작업은 무엇입니까?May 02, 2025 am 12:09 AM

NumpyAllowsForVariousOperationsOnArrays : 1) BasicArithmeticLikeadDition, Subtraction, A 및 Division; 2) AdvancedOperationsSuchasmatrixmultiplication; 3) extrayintondsfordatamanipulation; 5) Ag

파이썬으로 데이터 분석에 어레이가 어떻게 사용됩니까?파이썬으로 데이터 분석에 어레이가 어떻게 사용됩니까?May 02, 2025 am 12:09 AM

Arraysinpython, 특히 Stroughnumpyandpandas, areestentialfordataanalysis, setingspeedandefficiency

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구