杰瑞科技汇

Python HTTP服务器如何搭建与配置?

Of course! Creating an HTTP server in Python is a common task, and Python's built-in libraries make it incredibly simple. I'll guide you through it, starting from the absolute basics and moving to more practical, real-world examples.

Python HTTP服务器如何搭建与配置?-图1
(图片来源网络,侵删)

We'll focus on two main approaches:

  1. The Simple, Built-in Way: Using Python's http.server module. Perfect for quick tests, sharing files, or learning the basics.
  2. The Powerful, Production-Ready Way: Using the Flask framework. The standard for building robust web applications and APIs.

Method 1: The Simple http.server Module

This is the fastest way to get a server running. It's great for:

  • Quickly sharing files from a directory on your network.
  • Testing a simple HTML/CSS/JavaScript project.
  • Understanding the fundamentals of how an HTTP server works.

Example 1: A Simple File Server

This server will serve files from the directory you run it in.

Step 1: Open your terminal or command prompt.

Python HTTP服务器如何搭建与配置?-图2
(图片来源网络,侵删)

Step 2: Navigate to the directory you want to share. For example, if you have a project folder named my_website:

cd /path/to/my_website

Step 3: Run the Python server command.

  • For Python 3:
    python3 -m http.server
  • For Python 2 (less common now):
    python -m SimpleHTTPServer

Step 4: See the output. You'll see something like this:

Serving HTTP on 0.0.0.0 port 8000 ...
http://0.0.0.0:8000/

Your server is now running! You can access it by opening your web browser and navigating to http://localhost:8000 or http://127.0.0.1:8000.

Python HTTP服务器如何搭建与配置?-图3
(图片来源网络,侵删)

You'll see a directory listing of the files in your my_website folder. Clicking on a file will open it.

Example 2: A Custom Handler with http.server

What if you want to do more than just serve files? You can create a custom handler to respond to specific URLs.

Let's create a server that responds with "Hello, World!" to any request.

File: my_server.py

from http.server import BaseHTTPRequestHandler, HTTPServer
# Define the address and port
HOST = "localhost"
PORT = 8080
# Create a custom request handler by inheriting from BaseHTTPRequestHandler
class MyServer(BaseHTTPRequestHandler):
    # The do_GET method is called whenever a GET request is received
    def do_GET(self):
        # Send a response code
        self.send_response(200)
        # Send headers
        self.send_header("Content-type", "text/html")
        self.end_headers()
        # The actual response content
        message = "Hello, World! This is a custom Python server."
        # Encode the message to bytes and send it
        self.wfile.write(bytes(message, "utf8"))
# Create and start the server
if __name__ == "__main__":
    server = HTTPServer((HOST, PORT), MyServer)
    print(f"Server started at http://{HOST}:{PORT}")
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass
    server.server_close()
    print("Server stopped.")

How to run it:

  1. Save the code as my_server.py.
  2. Run it from your terminal:
    python3 my_server.py
  3. Open your browser and go to http://localhost:8080.

You will see the "Hello, World!" message.


Method 2: The Powerful Flask Framework

For any real application (like a blog, an API, or a dynamic website), you should use a web framework. Flask is a lightweight and popular choice. It handles routing, templates, and much more.

Step 1: Install Flask

If you don't have it installed, open your terminal and run:

pip install Flask

Example 3: A Basic Flask App

This example shows how to create a simple page and a page that takes input.

File: app.py

from flask import Flask, request, render_template_string
# Create a Flask application instance
app = Flask(__name__)
# Define a route for the root URL ('/')
# The @app.route decorator links a URL to a function
@app.route('/')
def home():
    # This function returns the content for the home page
    return "<h1>Welcome to the Flask App!</h1><p>This is a simple page.</p>"
# Define a dynamic route that accepts a name in the URL
# e.g., /greet/Alice
@app.route('/greet/<name>')
def greet(name):
    return f"<h2>Hello, {name}!</h2>"
# Define a route that handles form data
@app.route('/submit', methods=['GET', 'POST'])
def submit():
    # If the request is a GET request, just show the form
    if request.method == 'GET':
        return render_template_string('''
            <h2>Submit Your Name</h2>
            <form method="post">
                Name: <input type="text" name="username">
                <input type="submit" value="Submit">
            </form>
        ''')
    # If the request is a POST request, process the form data
    elif request.method == 'POST':
        username = request.form['username']
        return f'<h1>Thanks for submitting, {username}!</h1>'
# This block allows you to run the app directly
if __name__ == '__main__':
    # debug=True will auto-reload the server when you change the code
    app.run(debug=True)

How to run it:

  1. Save the code as app.py.
  2. Run it from your terminal:
    python3 app.py
  3. You'll see output like this:
     * Serving Flask app 'app'
     * Debug mode: on
     WARNING: This is a development server. Do not use it in a production deployment.
     Use a production WSGI server instead.
     * Running on http://127.0.0.1:5000
    Press CTRL+C to quit
  4. Open your browser and visit the URLs:
    • http://127.0.0.1:5000: Shows the home page.
    • http://127.0.0.1:5000/greet/Alice: Shows a personalized greeting.
    • http://127.0.0.1:5000/submit: Shows a form. Fill it out and submit to see the results.

Summary: Which One Should You Use?

Feature http.server Flask
Use Case Quick file sharing, simple tests, learning. Building web apps, APIs, dynamic websites.
Ease of Use Extremely simple for basic serving. Very easy to start, but powerful for complex apps.
Features Minimal. Just serves files or lets you write raw HTTP responses. Rich ecosystem: routing, templates, security helpers, session management, etc.
Production Not suitable. It's a single-threaded, slow development server. Suitable. Can be deployed with production-grade WSGI servers (like Gunicorn or uWSGI).
Dependencies None. It's built into Python. Requires installing the Flask library.

Final Recommendation:

  • If you just need to share some files or run a quick test, use http.server.
  • If you are building any kind of interactive or data-driven application, use Flask (or another framework like Django or FastAPI). It will save you a massive amount of time and effort in the long run.
分享:
扫描分享到社交APP
上一篇
下一篇