How to build

A Web Framework

From Scratch

Jiayuan Zhang CSDN Python Developer's Day 2019.04

Who am I

  • Backend Developer at iQiyi.Inc
  • Work with Python (Flask) and JavaScript (TypeScript, Vue.js)
  • Open Source Contributor (requests, werkzeug)

Contact

Outline

  • 什么是 Web 框架
  • 什么是 WSGI
  • 从零开始构建一个 Web 框架

什么是 Web 框架

A web framework (WF) or web application framework (WAF) is a software framework that is designed to support the development of web applications including web services, web resources, and web APIs.

-- from Wikipedia

什么是 Web 框架

A web framework (WF) or web application framework (WAF) is a software framework that is designed to support the development of web applications including web services, web resources, and web APIs.

-- from Wikipedia

什么是 Web 框架

简单来讲,Web 框架能够让你更方便地编写 Web Application。

Web 框架提供的功能

  • Request & Response 对象
  • 路由管理
  • 模板引擎
  • 对象关系映射(ORM)
  • ...

什么是 WSGI

  • Web Server Gateway Interface
  • PEP 333 & PEP 3333
  • 定义了 Web server, application, middleware 之间通讯的接口协议
  • 不是某个具体的框架,只是一种协议

WSGI 协议的目的

The goal of WSGI is to faciliate easy interconnection of existing server and applications or frameworks , not to create a new web framework.

提供了通用的规范,保证 Web Application 能够运行在各种符合协议的 Web Server 上。

Application/Framework 端协议

  • App 必须是一个可调用(callable)对象
  • 接受两个参数:environstart_response
  • 返回值是一个字节序列:List[bytes]

可调用对象

  • 函数
  • 实现了 __call__ 方法的类实例

缺失的功能

  • 需要处理复杂的 request 和 response
  • 只能请求根路由 /

1. 封装 Request 和 Response 对象

Request

Response

2. 添加路由匹配规则

  • 访问 http://127.0.0.1:8080/,返回 Hello world.
  • 访问 http://127.0.0.1:8080/csdn, 返回 Hello, developers.

Live Coding

后续扩展

  • 支持动态路由
  • 完善的错误处理
  • 上下文管理机制
  • 模板引擎
  • ORM
  • ...

Thank You