如何使用Python创建简单的Web服务器
Python自带HTTP服务器,可快速搭建本地服务。使用python -m http.server 8000命令即可在指定端口启动文件共享服务,浏览器访问http://localhost:8000查看目录内容;如需自定义响应,可通过BaseHTTPRequestHandler编写处理逻辑,运行脚本后实现简单Web服务,适用于测试与开发,但不推荐用于生产环境。
Python comes with a built-in HTTP server, making it easy to set up a simple web server in seconds—perfect for testing, sharing files, or local development.
Using the Built-in HTTP Server (Python 3)
If you just want to serve files from a directory, Python’s http.server module is all you need. No extra installation required.
Follow these steps:
- Open a terminal or command prompt.
- Navigate to the directory you want to serve: cd /path/to/your/folder
- Run the HTTP server on a specific port (e.g., 8000): python -m http.server 8000
Now open your browser and go to:
http://localhost:8000You’ll see a file listing of the directory. Anyone on your network can access it if your firewall allows the connection.
Creating a Custom Web Server with BaseHTTPServer
If you need more control, like handling specific routes or returning custom responses, you can write a small script using BaseHTTPRequestHandler.
Create a file called server.py with this code:
from http.server import HTTPServer, BaseHTTPRequestHandlerclass SimpleHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b"Hello, this is my web server!")
if __name__ == "__main__":
server = HTTPServer(('localhost', 8000), SimpleHandler)
print("Server running at http://localhost:8000")
server.serve_forever()
Run it with:
python server.pyVisit http://localhost:8000 to see your custom message.
Notes and Tips
This approach works great for learning and basic tasks, but don’t use it in production. It's single-threaded and not secure or fast enough for real websites.
- Change localhost to 0.0.0.0 if you want others on your network to access the server.
- Always stop the server with Ctrl C in the terminal.
- Make sure the port you choose isn’t already in use.
Basically, that’s all it takes to run a simple web server with Python. It’s lightweight, quick, and handy when you need something up fast.
以上是如何使用Python创建简单的Web服务器的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undress AI Tool
免费脱衣服图片

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Stock Market GPT
人工智能驱动投资研究,做出更明智的决策

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

运行pipinstall-rrequirements.txt可安装依赖包,建议先创建并激活虚拟环境以避免冲突,确保文件路径正确且pip已更新,必要时使用--no-deps或--user等选项调整安装行为。

Pytest是Python中简单强大的测试工具,安装后按命名规则自动发现测试文件。编写以test_开头的函数进行断言测试,使用@pytest.fixture创建可复用的测试数据,通过pytest.raises验证异常,支持运行指定测试和多种命令行选项,提升测试效率。

theargparsemodulestherecommondedwaywaytohandlecommand-lineargumentsInpython,提供式刺激,typeValidation,helpmessages anderrornhandling; useSudys.argvforsimplecasesRequeRequeRingminimalSetup。

对于数据科学的初学者而言,从“毫无经验”到“行业专家”的跃迁之路,其核心就是不断地实践。而实践的基础,正是丰富多样的数据集。幸运的是,网络上有大量提供免费公共数据集的网站,它们是提升技能、磨练技术的宝贵资源。

目录什么是比特币改进提案(BIP)?为什么BIP如此重要?比特币改进提案(BIP)的历史BIP流程如何运作?BIP类型什么是信号以及矿工如何发出信号?Taproot快速试用BIP的利与弊结语自2011年以来,对比特币的任何改进都通过称为比特币改进提案或“BIP”的系统进行。比特币改进提案(BIP)为比特币如何发展提供了指导方针一般来说,BIP有三种可能的类型,其中两种与比特币的技术变革有关每个BIP都是从比特币开发者之间的非正式讨论开始的,他们可以在任何地方聚集,包括Twi

大数据分析需侧重多核CPU、大容量内存及分层存储。首选多核处理器如AMDEPYC或RyzenThreadripper,兼顾核心数量与单核性能;内存建议64GB起步,优先选用ECC内存保障数据完整性;存储采用NVMeSSD(系统与热数据)、SATASSD(常用数据)和HDD(冷数据)组合,提升整体处理效率。

Import@contextmanagerfromcontextlibanddefineageneratorfunctionthatyieldsexactlyonce,wherecodebeforeyieldactsasenterandcodeafteryield(preferablyinfinally)actsas__exit__.2.Usethefunctioninawithstatement,wheretheyieldedvalueisaccessibleviaas,andthesetup

Identifyrepetitivetasksworthautomating,suchasorganizingfilesorsendingemails,focusingonthosethatoccurfrequentlyandtakesignificanttime.2.UseappropriatePythonlibrarieslikeos,shutil,glob,smtplib,requests,BeautifulSoup,andseleniumforfileoperations,email,w
