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

部署在Apache服务器的Python代码为何返回500内部错误?

Troubleshooting 500 Error with OpenAI CGI Script on Apache

Here are the critical issues and fixes for your script:

1. Fix Invalid Syntax in HTTP Header Output

Your print statement for the Content-Type header has invalid Python syntax. Strings can't be split across lines without proper formatting. Replace that line with:

print("Content-type: text/html\n")

Or use triple quotes to ensure the required blank line after headers:

print("""Content-type: text/html

""")

2. Upgrade to Python 3

Python 2 is end-of-life and no longer supported by OpenAI's official library. Update your shebang line to use Python 3:

#!/usr/bin/env python3

Confirm Python 3 is installed on your server before proceeding.

3. Install OpenAI Library for Apache's Execution Environment

Apache runs scripts as the web server user (e.g., www-data), which may not have the openai module installed. Install it system-wide with:

sudo pip3 install openai

If using a virtual environment, configure Apache to use the virtual environment's Python executable or activate it directly in your script.

4. Correctly Set the OpenAI API Key

Environment variables from your user shell don't apply to Apache. Use one of these methods:

  • Set in Apache config: Add this to httpd.conf or .htaccess (ensure mod_env is enabled):
    SetEnv API_KEY "your-openai-api-key"
    
  • Read from a secure config file: Store the key in a restricted file and load it into your script (avoid hardcoding in production).

5. Add Error Handling for Debugging

Generic 500 errors hide root causes. Add try-except blocks to catch and display issues:

#!/usr/bin/env python3

import os
import openai
import sys

try:
    openai.api_key = os.getenv("API_KEY")
    if not openai.api_key:
        raise ValueError("API_KEY environment variable not set")

    response = openai.Completion.create(
        model="text-davinci-003",
        prompt="List 10 science fiction books:",
        temperature=0.5,
        max_tokens=200,
        top_p=1,
        frequency_penalty=0.52,
        presence_penalty=0.5,
        stop=["11."]
    )

    print("Content-type: text/html\n")
    print("<html><body>")
    print("<h1>Science Fiction Books</h1>")
    # Extract clean text from OpenAI response
    print("<p>", response.choices[0].text.strip(), "</p>")
    print("</body></html>")

except Exception as e:
    print("Content-type: text/html\n")
    print("<html><body>")
    print("<h1>Error</h1>")
    print("<p>", str(e), "</p>")
    print("</body></html>")
    # Log error to Apache's error log
    print("Error:", str(e), file=sys.stderr)

6. Check Apache Error Logs

If issues persist, review Apache's error logs for detailed failure messages. Common locations:

  • /var/log/apache2/error.log (Debian/Ubuntu)
  • /var/log/httpd/error_log (CentOS/RHEL)

7. Verify Script Permissions

Ensure your script has executable permissions and the web server user can read it:

chmod +x /path/to/cgi-bin/script.py

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 21:31:08