一、路由

1.1 什么是路由

 简单说,就是路怎么走。就是按照不同的路径分发数据。

 URL就是不同资源的路径,不同路径应该对应不同的应用程序来处理。

 所以,代码中要增加对路径的分支处理。

 一个简单的路由需求:

路径 内容
/ 返回欢迎信息
/python 返回Hello Python
其它路径 返回404

1.2 什么时候处理路由

 路由的处理需要在WSGI Server接收到HTTP请求后,WSGI Server解包封装服务器环境变量,随后就应该对request.path做处理,根据path调用相应的应用程序。

1.3 如何处理路由

 路由处理最简单的就是条件判断,但需要判断严谨。

二、路由处理

2.1 条件判断

from wsgiref.simple_server import make_server
from webob import Request, Response, dec @dec.wsgify
def app(request) -> Response:
print(request.method)
print(request.path)
print(request.query_string)
print(request.GET)
print(request.POST)
print(request.params) res = Response() if request.path == '/':
res.status_code = 200
res.content_type = 'text/html'
res.charset = 'utf-8'
res.body = '<h1>北京欢迎您</h1>'.encode()
elif request.path == '/python':
res.content_type = 'text/plain'
res.charset = 'gb2312'
res.body = '<h1>Hello Python</h1>'.encode()
else:
res.status_code = 404
res.body = '<h1>Not found</h1>'.encode()
return res if __name__ == '__main__':
ip = '127.0.0.1'
port = 9999
server = make_server(ip, port, app)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.shutdown()
server.server_close()

  

2.2 函数化条件匹配

from wsgiref.simple_server import make_server
from webob import Request, Response, dec def index(request: Request):
return Response('<h1>Welcome to BeiJing</h1>') def showpython(request: Request):
return Response('<h1>Hello Python</h1>') def notfound(request: Request):
res = Response()
res.body = '<h1>Not found</h1>'.encode()
res.status_code = 404
return res ROUTETABLE = {
'/': index,
'/python': showpython
} @dec.wsgify
def app(request) -> Response:
# if request.path == '/':
# return index(request)
# elif request.path == '/python':
# return showpython(request)
# else:
# return notfound(request)
return ROUTETABLE.get(request.path, notfound)(request) if __name__ == '__main__':
ip = '127.0.0.1'
port = 9999
server = make_server(ip, port, app)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.shutdown()
server.server_close()

  

2.3 增加路由动态注册

from wsgiref.simple_server import make_server
from webob import Request, Response, dec def index(request: Request):
return Response('<h1>Welcome to BeiJing</h1>') def showpython(request: Request):
return Response('<h1>Hello Python</h1>') def notfound(request: Request):
res = Response()
res.body = '<h1>Not found</h1>'.encode()
res.status_code = 404
return res ROUTETABLE = {} def register(path, handler):
ROUTETABLE[path] = handler register('/', index)
register('/python', showpython) @dec.wsgify
def app(request) -> Response:
return ROUTETABLE.get(request.path, notfound)(request) if __name__ == '__main__':
ip = '127.0.0.1'
port = 9999
server = make_server(ip, port, app)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.shutdown()
server.server_close()

  

2.4 路由封装成类

from wsgiref.simple_server import make_server
from webob import Request, Response, dec, exc class Application:
def notfound(self, request: Request):
res = Response()
res.status_code = 404
res.body = '<h1>Not found</h1>'.encode()
return res ROUTETABLE = {} @classmethod
def register(cls, path):
def _register(handler):
cls.ROUTETABLE[path] = handler
return handler return _register @dec.wsgify
def __call__(self, request) -> Response:
return self.ROUTETABLE.get(request.path, self.notfound)(request) @Application.register('/')
def index(request: Request):
return Response('<h1>Welcome to BeiJing</h1>') @Application.register('/python')
def showpython(request: Request):
return Response('<h1>Hello Python</h1>') if __name__ == '__main__':
ip = '127.0.0.1'
port = 9999
server = make_server(ip, port, Application())
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.shutdown()
server.server_close()

  

2.5 简化路由类

from wsgiref.simple_server import make_server
from webob import Request, Response, dec, exc class Application: ROUTETABLE = {} @classmethod
def register(cls, path):
def _register(handler):
cls.ROUTETABLE[path] = handler
return handler return _register @dec.wsgify
def __call__(self, request) -> Response:
try:
return self.ROUTETABLE[request.path](request)
except:
raise exc.HTTPNotFound('你访问的页面被外星人劫持了') @Application.register('/')
def index(request: Request):
return Response('<h1>Welcome to BeiJing</h1>') @Application.register('/python')
def showpython(request: Request):
return Response('<h1>Hello Python</h1>') if __name__ == '__main__':
ip = '127.0.0.1'
port = 9999
server = make_server(ip, port, Application())
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.shutdown()
server.server_close()

  

三、总结

 路由功能在设计时应该从最简单的方式开始,然后一步步的完善,比如:避免路由逻辑写死在代码中,代码优化。

[Python web开发] 路由实现 (三)的更多相关文章

  1. Redis的Python实践,以及四中常用应用场景详解——学习董伟明老师的《Python Web开发实践》

    首先,简单介绍:Redis是一个基于内存的键值对存储系统,常用作数据库.缓存和消息代理. 支持:字符串,字典,列表,集合,有序集合,位图(bitmaps),地理位置,HyperLogLog等多种数据结 ...

  2. windows下python web开发环境的搭建

    windows下python web开发环境: python2.7,django1.5.1,eclipse4.3.2,pydev3.4.1 一. python环境安装 https://www.pyth ...

  3. python web 开发学习路线

    转载,备着 自己目前学习python web 开发, 经过两个月的摸索,目前对web开发有了浅显的认识,把自己的学习过程贴出来.1.python入门推荐老齐<从零开始学python>,&l ...

  4. 转载:Python Web开发最难懂的WSGI协议,到底包含哪些内容?

    原文:PSC推出的第二篇文章-<Python Web开发最难懂的WSGI协议,到底包含哪些内容?>-2017.9.27 我想大部分Python开发者最先接触到的方向是WEB方向(因为总是有 ...

  5. Python Web开发:Django+BootStrap实现简单的博客项目

    创建blog的项目结构 关于如何创建一个Django项目,请查看[Python Web开发:使用Django框架创建HolleWorld项目] 创建blog的数据模型 创建一个文章类 所有开发都是数据 ...

  6. 2020 python web开发就业要求锦集

    郑州 Python程序员 河南三融云合信息技术有限公司 6-8k·12薪 7个工作日内反馈 郑州 1个月前 本科及以上2年以上语言不限年龄不限 微信扫码分享 收藏 Python程序员 河南三融云合信息 ...

  7. 《Python Web开发实战》|百度网盘免费下载|Python Web开发

    <Python Web开发实战>|百度网盘免费下载|Python Web开发 提取码:rnz4 内容简介 这本书涵盖了Web开发的方方面面,可以分为如下部分: 1. 使用最新的Flask ...

  8. Java Web开发和Python Web开发之间的区别

    今天的文章讨论了Java Web开发和Python Web开发之间的区别.我不鼓励我们在这里从Java Web迁移到Python Web开发.我只是想谈谈我的感受.它不一定适合所有情况,仅供我们参考. ...

  9. Python Web开发中的WSGI协议简介

    在Python Web开发中,我们一般使用Flask.Django等web框架来开发应用程序,生产环境中将应用部署到Apache.Nginx等web服务器时,还需要uWSGI或者Gunicorn.一个 ...

随机推荐

  1. spring 事务管理机制

    1. spring 事务管理抽象 spring 的事务策略机制的核心就是 org.springframework.transaction.PlatformTransactionManager 接口. ...

  2. ArcGISPlotSilverlightAPI For WPF

    这两天有个需求,在地图上做标绘箭头,效果如下图. Arcgis for WPF 10.2.5.0版本,然而官方文档中没有这种API,自己去写一个呢,又感觉无从下手.无奈去网上搜索了一下,发现一篇好文: ...

  3. 使用WICleanup清理Windows Installer 冗余文件

    使用WICleanup清理Windows Installer 冗余文件 | 浏览:816 | 更新:2015-11-02 10:43 | 标签:Win7 Win10 1 2 3 4 5 6 7 分步阅 ...

  4. Climbing Stairs 爬楼梯问题,每次可以走1或2步,爬上n层楼梯总方法 (变相fibonacci)

    You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb ...

  5. python item repr doc format slots doc module class 析构 call 描述符

    1.item # __getitem__ __setitem__ __delitem__ obj['属性']操作触发 class Foo: def __getitem__(self, item): r ...

  6. restful知识点之五解析器_响应器_分页器

    解析器 request.post:当数据时content-type urlencoded类型时才有数据 当content-type:是formdata时需要从request.body里取数据 requ ...

  7. leetcode summary-section II

    151 Reverse Words in a String class Solution { public: void reverseWords(string &s) { string res ...

  8. winfrom 实现窗体圆角

    在窗体中加入一下代码 #region 窗体圆角的实现 private void ComFrmBase_Resize(object sender, EventArgs e) { if (this.Win ...

  9. String str = "1,2,3,4,5,6" 如何将这个字符串转换成int数组

    String str = "1,2,3,4,5,6"; string[] strS = str.Split(','); int[] num = new int[strS.Lengt ...

  10. Java学习---基础知识学习

    2016-07-23  周六 利用键盘输入的时候需要抛出异常 ,直接快捷键 ctrl + 1 ;定义数组 int score[] = new int[4]  ;  只有4个数字BufferedRead ...