如何将Jupyter中编写的Python推荐引擎代码接入C#网站?
Absolutely! You don’t have to rewrite your Python recommendation engine from scratch to get it working with your C# website. Here are several practical, battle-tested approaches you can pick based on your project’s needs:
1. Expose the Python Engine as a REST API
This is the most common and scalable approach—turn your Python code into a standalone web service that your C# site can call over HTTP.
Step 1: Wrap your engine with a lightweight framework
Use Flask or FastAPI to create an endpoint that accepts user data and returns recommendations. Here’s a quick Flask example:from flask import Flask, request, jsonify # Import your existing recommendation engine module import your_recommendation_engine app = Flask(__name__) @app.route('/api/get-recommendations', methods=['POST']) def recommend(): # Receive user data from C# (sent as JSON) user_input = request.get_json() # Run your recommendation logic results = your_recommendation_engine.generate_recommendations(user_input) # Send results back as JSON return jsonify(results) if __name__ == '__main__': # Run the API on a specific port (e.g., 5000) app.run(host='0.0.0.0', port=5000, debug=False)Step 2: Call the API from C#
UseHttpClientin your C# code to send requests and parse the response:using System.Net.Http; using System.Text; using Newtonsoft.Json; // Inside your C# controller/service public async Task<List<string>> GetRecommendationsForUser(int userId, List<string> preferences) { using var httpClient = new HttpClient(); var userData = new { UserId = userId, Preferences = preferences }; var jsonPayload = new StringContent( JsonConvert.SerializeObject(userData), Encoding.UTF8, "application/json" ); var response = await httpClient.PostAsync( "http://your-python-api-url:5000/api/get-recommendations", jsonPayload ); response.EnsureSuccessStatusCode(); var recommendationsJson = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<List<string>>(recommendationsJson); }Pros: Full separation between Python and C# codebases; easy to scale the Python service independently; works well for high-traffic sites.
2. Use Python.NET to Call Python Directly from C#
If you prefer a more tightly integrated approach, Python.NET lets you embed the Python runtime directly into your C# application and call your Python code as if it were a C# library.
Step 1: Set up Python.NET
Install the NuGet package in your C# project:Install-Package Python.RuntimeStep 2: Configure and call your Python module
Make sure your C# project can access your Python environment and recommendation module. Here’s a code snippet:using Python.Runtime; public List<string> GetRecommendations(int userId, List<string> preferences) { // Initialize the Python runtime (do this once at app startup) PythonEngine.Initialize(); // Acquire the Global Interpreter Lock (required for Python thread safety) using (Py.GIL()) { // Import your Python recommendation module var engineModule = Py.Import("your_recommendation_engine"); // Convert C# objects to Python-compatible types var pyUserData = new PyDict(); pyUserData.SetItem("user_id", userId); pyUserData.SetItem("preferences", preferences.ToPython()); // Call your Python function var pyRecommendations = engineModule.generate_recommendations(pyUserData); // Convert the Python result back to a C# list return pyRecommendations.As<List<string>>(); } // Shutdown the runtime when your app exits (optional in long-running apps) // PythonEngine.Shutdown(); }Pros: No need for a separate API service; lower latency compared to HTTP calls.
Cons: Tighter coupling between C# and Python environments; requires managing Python dependencies in your C# deployment.
3. Run Python Scripts as Subprocesses
For simpler use cases where you don’t need high performance, you can have your C# app execute your Python script as a separate process, pass input via command-line arguments or stdin, and read the output.
Example C# code:
using System.Diagnostics; using Newtonsoft.Json; public List<string> GetRecommendations(int userId, List<string> preferences) { var processStartInfo = new ProcessStartInfo { FileName = "python", // Or the full path to your Python executable Arguments = $"path/to/your_recommendation_script.py --user-id {userId} --preferences {string.Join(",", preferences)}", RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }; using var process = Process.Start(processStartInfo); var output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); // Parse the script's output (assuming it returns JSON) return JsonConvert.DeserializeObject<List<string>>(output); }Pros: Extremely simple to set up; no extra frameworks needed.
Cons: Poor performance for frequent calls; error handling is more cumbersome.
Pick the approach that best fits your scalability needs, latency requirements, and deployment workflow. All of these let you keep your existing Python code intact!
内容的提问来源于stack exchange,提问作者Sami

