杰瑞科技汇

Python simpleserver如何快速搭建本地服务?

Of course! The "simple server" in Python most commonly refers to the built-in http.server module. It's a fantastic tool for quickly sharing files, testing websites locally, or debugging web applications without needing to install a complex web server like Apache or Nginx.

Python simpleserver如何快速搭建本地服务?-图1
(图片来源网络,侵删)

Here’s a complete guide, from the absolute basics to more advanced usage.


The Easiest Way: Serving Files from a Directory

This is the most common use case. You want to share the contents of a folder (e.g., a website project) over your local network.

Step 1: Open Your Terminal

Open a command prompt or terminal.

Step 2: Navigate to Your Directory

Use the cd command to go to the folder you want to share. For example, if you have a project folder called my-website on your Desktop:

Python simpleserver如何快速搭建本地服务?-图2
(图片来源网络,侵删)
# On macOS or Linux
cd ~/Desktop/my-website
# On Windows
cd C:\Users\YourUsername\Desktop\my-website

Step 3: Run the Python Command

Now, run the following Python command. Python 3 is recommended.

# For Python 3
python -m http.server

If you have both Python 2 and 3 installed and python points to Python 2, you can use python3:

# For Python 3 (explicit)
python3 -m http.server

Step 4: Access Your Files!

That's it! The server is now running. You'll see output like this in your terminal:

Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
  • On your own machine: Open a web browser and go to http://localhost:8000 or http://127.0.0.1:8000.
  • On other devices on the same network: Find your computer's local IP address (e.g., 168.1.15). Other devices on your Wi-Fi can then access your files by going to http://YOUR_IP_ADDRESS:8000.

You can stop the server at any time by pressing Ctrl + C in the terminal.

Python simpleserver如何快速搭建本地服务?-图3
(图片来源网络,侵删)

Customizing Your Simple Server

The basic command is great, but you can easily customize it.

Change the Port

The default port is 8000. If that port is already in use, or if you just want to use a different one, add a number at the end.

# Serve on port 8080
python -m http.server 8080

Now you would access it at http://localhost:8080.

Change the Directory (Host Path)

What if you don't want to cd into the directory first? You can specify the path directly.

# Serve the contents of /var/www/html from your home directory
python -m http.server /var/www/html

Make the Server Accessible from Other Machines (Bind to All Interfaces)

By default, the server only listens on localhost (127.0.0.1). To allow other devices on your network to connect, you need to tell it to listen on all available network interfaces using the --bind option.

# Serve on port 8000, accessible from any device on the network
python -m http.server --bind 0.0.0.0

Note: The 0.0.0 is a special address that means "all available interfaces".


The "Better" Way: Using a Script

Running the command from the terminal is quick, but for more control or for use in scripts, it's better to write a small Python file.

Create a file named run_server.py and paste this code into it:

# run_server.py
import http.server
import socketserver
PORT = 8000
# You can change the directory here if you want
#DIRECTORY = "/path/to/your/website" 
class Handler(http.server.SimpleHTTPRequestHandler):
    # This is an optional customization to serve files from a specific directory
    def __init__(self, *args, **kwargs):
        # If you uncomment the DIRECTORY line above, you can use this:
        # super().__init__(*args, directory=DIRECTORY, **kwargs)
        super().__init__(*args, **kwargs)
Handler.directory = "." # This makes it serve files from the current directory
with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print(f"Serving at port {PORT}")
    print(f"Access it locally at: http://localhost:{PORT}")
    print("Press Ctrl+C to stop the server.")
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("\nServer stopped.")
        httpd.server_close()

How to run it:

  1. Save the code as run_server.py in the directory you want to serve.
  2. Run it from your terminal:
    python run_server.py

This script gives you more control and is easier to modify for more complex needs.


When to Use http.server

  • Pros:

    • Built-in: No installation required.
    • Extremely fast to set up.
    • Perfect for quickly sharing files or testing static HTML/CSS/JS sites.
    • Great for learning about web servers and HTTP.
  • Cons:

    • Not for production: It's not secure, optimized, or robust enough for a public-facing website.
    • No dynamic content: It can only serve static files. It cannot run Python code, connect to databases, or create dynamic pages (like a login system or a blog).
    • Performance is basic. It will struggle under heavy load.

Alternatives for More Serious Projects

If you need to build a real web application, you should use a dedicated web framework.

  1. Flask: A lightweight and "micro" web framework. Perfect for smaller applications and APIs. It's very easy to get started with.

    pip install Flask
    # (Then you'd create a simple app.py file)
  2. Django: A "batteries-included" web framework. It's more comprehensive and provides a lot of tools out-of-the-box (admin panel, ORM, etc.), making it great for larger, more complex projects.

    pip install Django
    # (Then you'd run 'django-admin startproject myproject')
  3. FastAPI: A modern, high-performance framework for building APIs with Python 3.6+ based on standard Python type hints. It's very fast and easy to use.

    pip install "fastapi[all]"

Summary Table

Method Command Best For
Terminal (Quick & Easy) python -m http.server Instantly sharing files from the current directory.
Terminal (Custom Port) python -m http.server 9000 When the default port 8000 is already in use.
Terminal (Network Access) python -m http.server --bind 0.0.0.0 Sharing files with other devices on your network.
Script (More Control) See run_server.py example above. When you need to customize behavior or run as a service.
Production Web App Use Flask, Django, or FastAPI Building real, dynamic, and scalable websites.
分享:
扫描分享到社交APP
上一篇
下一篇