python 启动一个本地web服务
2025-03-12 本文已影响0人
celineWong7
web有些处理事需要在本地调试的,如果没有通过vue等构建,可能需要自己快速启动个本地web服务环境。这个时候可以借助python快速启动一个本地服务。
当然,你也可以用node.js或者php等的其他后端语言启动本地服务。也可以下载phpadmin构建。
首先要安装下python开发环境。
然后如下操作:
- 编写代码,保存为
python.py.
import http.server
import socketserver
# 定义服务器端口
PORT = 50000
# 定义 HTML 页面文件(使用资源路径)
# index_file = 'iat-js-demo/example/wxl/index.html'
index_file = 'index.html'
class MyHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.path = '/' + index_file
# 修改为使用super()调用父类方法
return super().do_GET()
with socketserver.TCPServer(("", PORT), MyHandler) as httpd:
print(f"服务器已启动,访问地址: http://localhost:{PORT}")
# 启动服务器,开始监听请求
httpd.serve_forever()
-
同时编写一个index.html,存放在和py文件同级目录。
-
打开cmd窗口(或powershell)切换到py文件所在目录,执行如下指令
python server.py
-
如果成功启动,在控制台上就可以看到提示语:
“服务器已启动,访问地址: http://localhost:50000” -
在浏览器里输入http://localhost:50000即可访问到index.html。
-
如果要监听50000端口有没有被占用,可以cmd窗口执行指令:
# Windows
netstat -ano | findstr :<port>
要杀掉对应进程
# Windows
# pid替换成上面查询到的进程pid
taskkill /F /PID <pid>
参考内容:
上面代码都是通过AI编码工具Trae(CN)Chat模式整理出来的。