python web.py服务器与客户端的实现示例
作者:Coding的叶子
本文介绍了使用Python的web.py库搭建一个简单的Web服务器,并演示了自定义端口、URL映射以及POST和GET请求的处理,具有一定的参考价值,感兴趣的可以了解一下
web.py是python中一个相对容易上手的web服务器搭建工具。
1 安装方式
web.py可以直接通过pip install 的方式安装即可,即:
pip install web.py
2 服务器
2.1 完整程序
# -*- coding: utf-8 -*-
"""
Created on Mon May 10 20:37:00 2021
@author: Administrator
"""
import web #web.py
urls = (
'/server' , 'server',
'/.*', 'notfound' #localhost:port/其他任意界面,访问notfound类
)
class MyApplication(web.application):
def run(self, port=8080, *middleware):
func = self.wsgifunc(*middleware)
return web.httpserver.runsimple(func, ('0.0.0.0', port))
class server:
def __init__(self):
self.return_msg = {'errorCode': 0, 'msg': '系统正常!'}
def POST(self): #POST处理方式与GET一致
content = web.input()
print('收到消息:', content.key1, content.key2, content.key3)
return str(self.return_msg).replace('\'', '\"')
class notfound:
def GET(self):
print('--from notfound')
return '404 not found'
def POST(self):
print('--from notfound')
return '404 not found'
if __name__ == "__main__":
app = MyApplication(urls ,globals())
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处理方法基本一致。
urls = (
'/server' , 'server',
'/.*', 'notfound' #localhost:port/其他任意界面,访问notfound类
)2.3 自定义端口
web.py默认端口为8080端口,但是有时候8080已经被占用了,所以需要自定义端口。
自定义端口的方式可以用两种方式来实现,第一种是在命令行运行脚本,采用如下方式:
python main.py 8090
另一种方式是按照上述代码的方式,重载web.application类。
class MyApplication(web.application):
def run(self, port=8080, *middleware):
func = self.wsgifunc(*middleware)
return web.httpserver.runsimple(func, ('0.0.0.0', port))
if __name__ == "__main__":
app = MyApplication(urls ,globals())
app.run(port=8090)3 客户端
3.1 完整程序
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 18 22:35:53 2022
@author: Administrator
"""
import requests
def client_post(url, data):
rep = requests.post(url, data=data)
return rep.text
if __name__ == '__main__':
url1 = 'http://127.0.0.1:8090/server'
url2 = 'http://127.0.0.1:8090/'
data = {'key1': '测试', 'key2': 'test', 'key3': 1}
res1 = client_post(url1, data)
res2 = client_post(url2, data)
print('127.0.0.1:8090/server(返回结果):', res1)
print('127.0.0.1:8090/xxx(返回结果):', res2)4 测试结果
4.1 客户端测试
python客户端运行结果如下:

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

4.2 服务器端测试结果

到此这篇关于python web.py服务器与客户端的实现示例的文章就介绍到这了,更多相关python web.py服务器与客户端内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
您可能感兴趣的文章:
- python web.py启动https端口的方式
- python3.x中安装web.py步骤方法
- python web.py开发httpserver解决跨域问题实例解析
- 浅析Python的web.py框架中url的设定方法
- Linux系统上Nginx+Python的web.py与Django框架环境
- 详细解读Python的web.py框架下的application.py模块
- 使用Python的web.py框架实现类似Django的ORM查询的教程
- 安装Python的web.py框架并从hello world开始编程
- Python开发WebService系列教程之REST,web.py,eurasia,Django
