杰瑞科技汇

Flask中如何用curl发送请求?

Of course! This is a very common and fundamental task in web development. Here’s a comprehensive guide covering how to use curl to interact with a Python Flask application, broken down into simple steps.

Flask中如何用curl发送请求?-图1
(图片来源网络,侵删)

We'll build a simple Flask app and then use curl to test its endpoints.

The Plan

  1. Part 1: Create a Flask App. We'll create a basic API with a few endpoints (GET, POST, PUT, DELETE).
  2. Part 2: Run the Flask App. We'll run it in a way that makes it accessible to curl.
  3. Part 3: Use curl to Interact. We'll test each endpoint from the command line, explaining the flags and the expected output.

Part 1: Create the Flask Application

First, let's create a simple Flask application. This app will manage a list of "tasks".

  1. Install Flask: If you don't have Flask installed, open your terminal and run:

    pip install Flask
  2. Create the Python File: Create a file named app.py and paste the following code into it.

    Flask中如何用curl发送请求?-图2
    (图片来源网络,侵删)
    # app.py
    from flask import Flask, jsonify, request
    # Create a Flask application instance
    app = Flask(__name__)
    # A simple in-memory "database" for our tasks
    tasks = [
        {'id': 1, 'title': 'Buy groceries', 'done': False},
        {'id': 2, 'title': 'Learn Flask', 'done': True}
    ]
    next_task_id = 3
    # --- API Endpoints ---
    # 1. Get all tasks (GET)
    @app.route('/tasks', methods=['GET'])
    def get_tasks():
        return jsonify({'tasks': tasks})
    # 2. Get a single task by ID (GET)
    @app.route('/tasks/<int:task_id>', methods=['GET'])
    def get_task(task_id):
        task = next((t for t in tasks if t['id'] == task_id), None)
        if task is None:
            # Return a 404 Not Found error if the task doesn't exist
            return jsonify({'error': 'Task not found'}), 404
        return jsonify(task)
    # 3. Create a new task (POST)
    @app.route('/tasks', methods=['POST'])
    def create_task():
        global next_task_id
        if not request.json or 'title' not in request.json:
            return jsonify({'error': 'Request must be JSON and contain a title'}), 400
        new_task = {
            'id': next_task_id,
            'title': request.json['title'],
            'done': False
        }
        tasks.append(new_task)
        next_task_id += 1
        # Return the newly created task with a 201 Created status code
        return jsonify(new_task), 201
    # 4. Update an existing task (PUT)
    @app.route('/tasks/<int:task_id>', methods=['PUT'])
    def update_task(task_id):
        task = next((t for t in tasks if t['id'] == task_id), None)
        if task is None:
            return jsonify({'error': 'Task not found'}), 404
        if not request.json:
            return jsonify({'error': 'Request must be JSON'}), 400
        task['title'] = request.json.get('title', task['title'])
        task['done'] = request.json.get('done', task['done'])
        return jsonify(task)
    # 5. Delete a task (DELETE)
    @app.route('/tasks/<int:task_id>', methods=['DELETE'])
    def delete_task(task_id):
        global tasks
        task = next((t for t in tasks if t['id'] == task_id), None)
        if task is None:
            return jsonify({'error': 'Task not found'}), 404
        tasks = [t for t in tasks if t['id'] != task_id]
        return jsonify({'result': True})
    # This is the standard boilerplate to run the app
    if __name__ == '__main__':
        # Use debug=True for development. It auto-reloads on code changes.
        # host='0.0.0.0' makes the server accessible from any IP address on your machine.
        app.run(debug=True, host='0.0.0.0', port=5000)

Part 2: Run the Flask App

  1. Open your terminal or command prompt.
  2. Navigate to the directory where you saved app.py.
  3. Run the application:
    python app.py

You should see output similar to this, indicating the server is running:

 * 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 all addresses (0.0.0.0)
 * Running on http://127.0.0.1:5000
 * Running on http://<your_local_ip>:5000
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: ...

Your Flask API is now live and listening for requests on port 5000.


Part 3: Use curl to Interact with the API

Now, open a new terminal window (don't close the one running the Flask app!). We will use curl from this new terminal.

All commands will use http://127.0.0.1:5000 as the base URL.

Flask中如何用curl发送请求?-图3
(图片来源网络,侵删)

A. GET All Tasks

This endpoint retrieves the list of all tasks.

curl http://127.0.0.1:5000/tasks

Expected Output:

{
  "tasks": [
    {
      "done": false,
      "id": 1,
      "title": "Buy groceries"
    },
    {
      "done": true,
      "id": 2,
      "title": "Learn Flask"
    }
  ]
}

B. POST (Create) a New Task

This endpoint adds a new task. We need to send JSON data in the request body.

curl -X POST \
     -H "Content-Type: application/json" \
     -d '{"title": "Finish the project"}' \
     http://127.0.0.1:5000/tasks

Explanation of Flags:

  • -X POST: Specifies the HTTP method to use (POST).
  • -H "Content-Type: application/json": Sets a request header. It tells the server that we are sending JSON data. This is crucial for the Flask app to correctly parse request.json.
  • -d '{"title": "Finish the project"}': The data (payload) to send with the request. curl automatically encodes this for you.

Expected Output:

{
  "done": false,
  "id": 3,: "Finish the project"
}

If you run the GET all tasks command again, you will now see the new task in the list.

C. GET a Single Task

This endpoint retrieves one task by its ID.

curl http://127.0.0.1:5000/tasks/3

Expected Output:

{
  "done": false,
  "id": 3,: "Finish the project"
}

D. PUT (Update) a Task

This endpoint modifies an existing task. Let's update task #1 to mark it as done.

curl -X PUT \
     -H "Content-Type: application/json" \
     -d '{"done": true}' \
     http://127.0.0.1:5000/tasks/1

Expected Output:

{
  "done": true,
  "id": 1,: "Buy groceries"
}

E. DELETE a Task

This endpoint removes a task from the list.

curl -X DELETE http://127.0.0.1:5000/tasks/2

Expected Output:

{
  "result": true
}

If you run the GET all tasks command again, you will see that task #2 is gone.


Bonus: Useful curl Flags

  • -i or --include: Show the HTTP response headers. This is very useful for debugging status codes.

    curl -i http://127.0.0.1:5000/tasks/99

    You'll see the HTTP/1.0 404 NOT FOUND header before the JSON body.

  • -v or --verbose: Show the entire request and response, including headers. Extremely useful for debugging.

    curl -v http://127.0.0.1:5000/tasks
  • -s or --silent: Don't show progress meter or error messages. Only prints the actual response body. Great for scripting.

    curl -s http://127.0.0.1:5000/tasks | jq .  # (if you have `jq` for pretty-printing JSON)
  • Saving output to a file:

    curl -o response.json http://127.0.0.1:5000/tasks

Common Pitfalls

  1. Server Not Running: The most common error. Make sure your Flask app is running in one terminal before you run curl in another.
  2. Wrong URL/Port: Double-check that you're using the correct IP (0.0.1 or localhost) and port (5000).
  3. Missing Headers: For POST and PUT requests with JSON, you must include -H "Content-Type: application/json". Without it, Flask's request.json will be None.
  4. Syntax Errors in curl: A missing backslash \ or quote can break the command. Pay attention to the command structure.
分享:
扫描分享到社交APP
上一篇
下一篇