Python HTTP Server

1. Python HTTP Server

1.1. Python 内置

Python 2:

$ python -m SimpleHTTPServer 9000

If you are running Python 3, you will get error as No module named SimpleHTTPServer. It’s because in python 3, SimpleHTTPServer has been merged into http.server module. You can use below command to run python http server in Python 3.

$ python3 -m http.server
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...

To explicitly set the port number that your HTTP server should be listening on, append it as a parameter:

$ python3 -m http.server 8080
Serving HTTP on 0.0.0.0 port 8080 (http://0.0.0.0:8080/) ...

Port 80 is a standard port reserved for HTTP traffic. However, if you’d like to start a local web server on that special port, then you’ll have to run the corresponding command as the superuser with administrative privileges. Otherwise, you’ll get another error:

$ python3 -m http.server 80
Traceback (most recent call last):
  ...
PermissionError: [Errno 13] Permission denied

You can bind a specific network interface or IP address by using the -b option:

$ python3 -m http.server -b 127.0.0.42 8080
Serving HTTP on 127.0.0.42 port 8080 (http://127.0.0.42:8080/) ...

To enforce a different address, you can use the -b option:

$ python -m http.server -b "::"
Serving HTTP on :: port 8000 (http://[::]:8000/) ...

You may instruct the server to associate its home address (/) with a completely different directory by specifying the optional -d parameter:

$ python3 -m http.server -d ~/Pictures/
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...

The -d option may be your only choice in some cases. For instance, if you try to start the HTTP server in a directory where you installed your Python interpreter, then you may face the following problem:

$ cd /usr/lib/python3.8/
$ python3 -m http.server
Traceback (most recent call last):
  ...
AssertionError: SRE module mismatch

You can work around this issue by changing your working directory so that Python will no longer find this module in the file system. Then, start the server using the -d option to point it back to the desired directory:

$ cd ..
$ python3 -m http.server -d /usr/lib/python3.8/
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云满笔记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值