杰瑞科技汇

Python如何运行服务器?

Of course! "Running a server" in Python can mean several things, from a simple development server to a full-fledged production application. I'll guide you through the most common scenarios, starting with the basics and moving to more robust solutions.

Python如何运行服务器?-图1
(图片来源网络,侵删)

Scenario 1: The Simplest Case - http.server (Python's Built-in)

This is the quickest way to create a basic web server. It's perfect for testing, sharing files locally, or serving a simple static website.

Use Case: You have a folder of HTML, CSS, and JS files and want to view them in a browser.

How to do it:

  1. Open your terminal or command prompt.

    Python如何运行服务器?-图2
    (图片来源网络,侵删)
  2. Navigate to the directory you want to serve. For example, if you have a folder named my_project on your Desktop:

    cd ~/Desktop/my_project
  3. Run the server command.

    • For Python 3:
      python3 -m http.server
    • For Python 2 (less common now):
      python -m SimpleHTTPServer
  4. See the output. You'll see something like this:

    Serving HTTP on 0.0.0.0 port 8000 ...
    http://127.0.0.1:8000/ ... press ^C to quit
  5. Access your server. Open your web browser and go to http://localhost:8000 or http://127.0.0.1:8000. You will see a directory listing of the files in your my_project folder.

Key Options:

  • Change the Port: If port 8000 is taken, use a different one (e.g., 8080):
    python3 -m http.server 8080
  • Change the Interface: To make it accessible from other devices on your network (not just your own machine), use 0.0.0:
    python3 -m http.server 8000 --bind 0.0.0.0

Scenario 2: The Standard - Flask

Flask is a lightweight and popular "micro-framework" for building web applications. It's much more powerful than http.server because it allows you to write Python code to handle dynamic requests.

Use Case: You're building a small web app, an API, or a personal project.

Step-by-Step Guide:

  1. Install Flask:

    pip install Flask
  2. Create a Python file. Let's call it app.py.

  3. Write the code. Here's a simple "Hello, World!" example.

    # app.py
    from flask import Flask
    # Create an instance of the Flask class
    app = Flask(__name__)
    # Define a route and a view function
    # The @app.route decorator tells Flask what URL should trigger our function
    @app.route('/')
    def home():
        return "Hello, World! This is a Flask server."
    @app.route('/user/<username>')
    def show_user_profile(username):
        # You can use variables in the route
        return f'Hello, {username}!'
    # This block is run when you execute the script directly
    if __name__ == '__main__':
        # app.run() starts the development server
        app.run(debug=True)
  4. Run the Flask server.

    python app.py
  5. See the output.

     * Serving Flask app 'app'
     * Running on http://127.0.0.1:5000
    Press CTRL+C to quit
    * Restarting with stat
    * Debugger is active!
    * Debugger PIN: ...
  6. Access your server.

    • Go to http://localhost:5000 to see "Hello, World!".
    • Go to http://localhost:5000/user/Alice to see "Hello, Alice!".

Note: app.run(debug=True) is great for development because it automatically reloads the server when you save changes and provides a debugger. Do not use debug=True in a production environment.


Scenario 3: The Powerful - Django

Django is a high-level, "batteries-included" framework. It's excellent for building complex, database-driven websites quickly. It has its own development server.

Use Case: Building a large-scale web application like a social network, e-commerce site, or content management system (CMS).

Step-by-Step Guide:

  1. Install Django:

    pip install Django
  2. Create a new Django project.

    django-admin startproject myproject

    This creates a folder named myproject with several files, including manage.py.

  3. Navigate into the project directory.

    cd myproject
  4. Create a new Django app. Apps are the modules of your Django project.

    python manage.py startapp myapp
  5. Run the development server.

    python manage.py runserver
  6. See the output.

    Watching for file changes with StatReloader
    Performing system checks...
    System check identified no issues (0 silenced).
    May 20, 2025 - 15:30:00
    Django version 4.2.7, using settings 'myproject.settings'
    Starting development server at http://127.0.0.1:8000/
    Quit the server with CONTROL-C.
  7. Access your server. Go to http://localhost:8000. You'll see the Django welcome page.


Scenario 4: The Production-Grade - Gunicorn with a WSGI App

The built-in Flask/Django servers are not suitable for production. They are slow and not designed to handle many concurrent users. For production, you need a proper WSGI (Web Server Gateway Interface) server.

Use Case: Deploying your Flask or Django app to a real server so it can be accessed by the public.

Example with Flask:

  1. Install Gunicorn:

    pip install gunicorn
  2. Navigate to your project directory (the one containing app.py).

  3. Run Gunicorn. You need to tell it which module to load and which variable holds the application instance.

    # The format is: <module_name>:<variable_name>
    gunicorn --bind 0.0.0.0:8000 app:app
    • app:app: The first app is the name of your Python file (app.py). The second app is the name of the Flask instance inside that file (app = Flask(__name__)).
    • --bind 0.0.0.0:8000: Makes the server listen on all network interfaces on port 8000.
  4. Run behind a Reverse Proxy (Highly Recommended). Gunicorn is great at running Python code, but it's not great at serving static files or handling HTTPS. A reverse proxy like Nginx sits in front of Gunicorn.

    • Nginx handles incoming requests, serves static files (CSS, JS, images), and manages SSL/TLS certificates (HTTPS).
    • Gunicorn handles the dynamic Python application logic.

    A typical production setup looks like this:

    User's Browser -> Nginx (Reverse Proxy) -> Gunicorn (WSGI Server) -> Your Flask/Django App

Summary Table

Method Best For How to Run Key Features
http.server Quick file sharing, local testing, static sites python3 -m http.server Built-in, no dependencies, very simple.
Flask Small web apps, APIs, prototypes python app.py Lightweight, flexible, easy to learn.
Django Large, complex, database-driven sites python manage.py runserver "Batteries-included," admin panel, ORM.
Gunicorn Production deployment of WSGI apps gunicorn <module>:<app> Fast, robust, handles concurrent requests.

For most beginners, start with Flask. It gives you the power to build dynamic web applications without the complexity of a larger framework.

分享:
扫描分享到社交APP
上一篇
下一篇