当前位置:   article > 正文

python web.py服务器与客户端

web.py

        web.py是python中一个相对容易上手的web服务器搭建工具。

1 安装方式

        web.py可以直接通过pip install 的方式安装即可,即:

pip install web.py

2 服务器

        2.1 完整程序

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Mon May 10 20:37:00 2021
  4. @author: Administrator
  5. """
  6. import web #web.py
  7. urls = (
  8. '/server' , 'server',
  9. '/.*', 'notfound' #localhost:port/其他任意界面,访问notfound类
  10. )
  11. class MyApplication(web.application):
  12. def run(self, port=8080, *middleware):
  13. func = self.wsgifunc(*middleware)
  14. return web.httpserver.runsimple(func, ('0.0.0.0', port))
  15. class server:
  16. def __init__(self):
  17. self.return_msg = {'errorCode': 0, 'msg': '系统正常!'}
  18. def POST(self): #POST处理方式与GET一致
  19. content = web.input()
  20. print('收到消息:', content.key1, content.key2, content.key3)
  21. return str(self.return_msg).replace('\'', '\"')
  22. class notfound:
  23. def GET(self):
  24. print('--from notfound')
  25. return '404 not found'
  26. def POST(self):
  27. print('--from notfound')
  28. return '404 not found'
  29. if __name__ == "__main__":
  30. app = MyApplication(urls ,globals())
  31. app.run(port=8090)

        2.2 url页面与响应类

        url页面是指网页访问地址,响应类是指定页面做出的响应。如上所示,url页面用一个小括号元组形式来定义。'/server', 'server' 表示url地址为127.0.0.1:port/server或者localhost:port/server页面对应函数处理类为class server。'/.*', 'notfound'表示除了server页面之外,且在指定端口port下的地址时均由class notfound类来表示。可以按照上述方法,定义多个页面。

        在响应函数类处理消息过程中,POST与GET处理方法基本一致。

  1. urls = (
  2. '/server' , 'server',
  3. '/.*', 'notfound' #localhost:port/其他任意界面,访问notfound类
  4. )

        2.3 自定义端口

         web.py默认端口为8080端口,但是有时候8080已经被占用了,所以需要自定义端口。

        自定义端口的方式可以用两种方式来实现,第一种是在命令行运行脚本,采用如下方式:

python main.py 8090

        另一种方式是按照上述代码的方式,重载web.application类。

  1. class MyApplication(web.application):
  2. def run(self, port=8080, *middleware):
  3. func = self.wsgifunc(*middleware)
  4. return web.httpserver.runsimple(func, ('0.0.0.0', port))
  5. if __name__ == "__main__":
  6. app = MyApplication(urls ,globals())
  7. app.run(port=8090)

3 客户端

        3.1 完整程序

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Thu Aug 18 22:35:53 2022
  4. @author: Administrator
  5. """
  6. import requests
  7. def client_post(url, data):
  8. rep = requests.post(url, data=data)
  9. return rep.text
  10. if __name__ == '__main__':
  11. url1 = 'http://127.0.0.1:8090/server'
  12. url2 = 'http://127.0.0.1:8090/'
  13. data = {'key1': '测试', 'key2': 'test', 'key3': 1}
  14. res1 = client_post(url1, data)
  15. res2 = client_post(url2, data)
  16. print('127.0.0.1:8090/server(返回结果):', res1)
  17. print('127.0.0.1:8090/xxx(返回结果):', res2)

4 测试结果

        4.1 客户端测试

        python客户端运行结果如下:

        也可以在浏览器中输入网址:

 

        4.2 服务器端测试结果

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/454909
推荐阅读
相关标签
  

闽ICP备14008679号