Jasper Ji

开口不在舌头上

0%

Python简单Http服务器

Python自带Http服务器,我一般是在共享文件时使用,直接在需要共享的目录下运行命令即可启动服务,不过有时候传输不是很稳定,重启一下就好了。

Python2 版本

1
python -m SimpleHTTPServer 8080

Python3 版本

之前主要用Python 2.7的版本,随着2.7的终结加上macOS 12.3已经彻底移除了python 2.x的版本,只能使用3的版本了,Python 3的这个Http服务器命令似乎更简单一些。

1
python3 -m http.server 8001

跨域配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/env python
try:
# Python 3
from http.server import HTTPServer, SimpleHTTPRequestHandler, test as test_orig
import sys
def test (*args):
test_orig(*args, port=int(sys.argv[1]) if len(sys.argv) > 1 else 8000)
except ImportError: # Python 2
from BaseHTTPServer import HTTPServer, test
from SimpleHTTPServer import SimpleHTTPRequestHandler

class CORSRequestHandler (SimpleHTTPRequestHandler):
def end_headers (self):
self.send_header('Access-Control-Allow-Origin', '*')
SimpleHTTPRequestHandler.end_headers(self)

if __name__ == '__main__':
test(CORSRequestHandler, HTTPServer)