0
点赞
收藏
分享

微信扫一扫

sanic使用中间件(Middleware)实现拦截ip黑名单

白衣蓝剑冰魄 2022-03-31 阅读 68

文章目录


前言

python sanic这个框架感觉参考内容好少作为一个面向CTRL C V编程的我来说很难受
记录下学习python过程

例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。


一、sanic是什么?

异步 Python 3.7+ web 框架…算了 自己看官方中文文档吧
地址:https://sanic.dev/zh/

二、使用步骤

pip3 install sanic

1.引入库

代码如下(示例):

import sanic
app = Sanic("***")
@app.get("/helloworld")
#@app.route('/helloworld', methods=['GET'])两种方式
async def foo_handler(request):
    return text("helloworld")

2.中间件

代码如下(示例):

@app.on_request
async def send_request(request):
	pass	

这就是中间件 我理解就是request发送过来首先是先进入中间件,然后再由中间件调用路由函数

import sanic
from sanic import response
app = Sanic("***")
@app.get("/helloworld")
#@app.route('/helloworld', methods=['GET'])两种方式
async def foo_handler(request):
    return text("helloworld")
iplist = ["1.2.3.4","2.3.4.5","127.0.0.1"]
#ip黑名单拦截 (修改下逻辑想拦截什么应该都没问题吧)
@app.on_request
async def send_request(request):
	if request.ip in iplist:
		return response.json({"code":302,"msg":"请联系系统管理员***"})
	return
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=12345)

#这时我们访问 http://127.0.0.1:12345/helloworld
#{“code”:302,“msg”:“请联系系统管理员***”}
#就成功拦截啦
#那么把127.0.0.1从数组删除之后再次访问
#helloworld


总结

sanic挺好用的,就是相关的文档比较少,也不知道是不是我没找到的原因
另外还有个监听器 暂未看懂是怎么用的 有大佬知道可以告诉我一下 蟹蟹

举报

相关推荐

0 条评论