You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Python(P4Python)从Flask服务器向远程Perforce仓库发送JSON集合?

Absolutely! You can absolutely build this workflow using P4Python and Flask. I’ll break down a practical, tested implementation that lets your Flask server accept a JSON collection and push it to a remote Perforce repository.

Prerequisites

First, make sure you have the required packages installed:

pip install flask p4python

You’ll also need:

  • A valid Perforce user account with write access to the target repository
  • The Perforce server’s address (e.g., perforce.example.com:1666)
  • A pre-configured Perforce client workspace (or you can create one dynamically in code)
Step-by-Step Implementation

1. Flask Endpoint to Receive JSON

First, set up a Flask POST endpoint that accepts your JSON collection. We’ll validate the input and pass it to our Perforce handling logic.

from flask import Flask, request, jsonify
import tempfile
import os
from P4 import P4, P4Exception

app = Flask(__name__)

@app.route('/submit-json-to-perforce', methods=['POST'])
def submit_json():
    # Get JSON data from request
    json_data = request.get_json()
    if not json_data:
        return jsonify({"error": "No JSON data provided"}), 400

    # Define Perforce parameters (load these from env vars in production!)
    p4_config = {
        "server": "perforce.example.com:1666",
        "user": "your-perforce-username",
        "password": "your-perforce-password",
        "client": "your-client-workspace",
        "target_file": "//depot/path/to/your/collection.json"  # Path in Perforce depot
    }

    try:
        # Submit JSON to Perforce
        submit_result = push_json_to_perforce(json_data, p4_config)
        return jsonify({"success": True, "message": submit_result}), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

2. P4Python Logic to Push JSON

Next, create a function that handles connecting to Perforce, writing the JSON to a file, and submitting it to the depot. We’ll use a temporary file to avoid cluttering your filesystem.

import json

def push_json_to_perforce(json_data, p4_config):
    p4 = P4()
    p4.port = p4_config["server"]
    p4.user = p4_config["user"]
    p4.client = p4_config["client"]

    try:
        # Connect to Perforce server
        p4.connect()
        p4.login(p4_config["password"])

        # Create a temporary file with formatted JSON content
        with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.json') as temp_file:
            json.dump(json_data, temp_file, indent=2)
            temp_file_path = temp_file.name

        try:
            # Get the local workspace path mapped to the depot file
            local_file = p4.run("where", p4_config["target_file"])[0]["path"]
            # Ensure the local directory exists
            os.makedirs(os.path.dirname(local_file), exist_ok=True)
            # Move temp file to the client workspace location
            os.replace(temp_file_path, local_file)

            # Mark the file for edit in Perforce
            p4.run("edit", local_file)

            # Prepare and submit the change
            change = p4.fetch_change()
            change["Description"] = "Automated submission of JSON collection from Flask server"
            change["Files"] = [p4_config["target_file"]]
            p4.run_submit(change)

            return f"JSON collection submitted to {p4_config['target_file']} successfully"
        finally:
            # Clean up temporary file if it still exists
            if os.path.exists(temp_file_path):
                os.unlink(temp_file_path)
    except P4Exception as e:
        raise Exception(f"Perforce error: {e}")
    finally:
        # Always disconnect from Perforce when done
        if p4.connected():
            p4.disconnect()
Critical Considerations
  • Security: Never hardcode Perforce credentials in your code. Use environment variables (e.g., os.getenv("P4_PASSWORD")) or a secure secrets manager in production.
  • Client Workspace: Ensure your client workspace has the correct mapping for the target depot path. If you need a dynamic workspace, you can create one on-the-fly using p4.run_client().
  • Error Handling: The example includes basic error handling, but you might want to add granular checks (e.g., handling file locks, duplicate submissions, or permission denied errors).
  • Concurrency: If multiple requests hit your Flask endpoint at once, use unique temporary filenames or implement a locking mechanism to avoid file conflicts.
  • JSON Validation: Add schema validation (using libraries like pydantic) for incoming JSON to ensure the data meets your requirements before sending it to Perforce.

内容的提问来源于stack exchange,提问作者Zargham Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 22:37:47