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

为何Python2的uWSGI插件可正常获取请求值,Python3插件却不行?

Fixing uWSGI Python3 Plugin's GET/POST Data Retrieval Issue

Let's break down why your Python3 uWSGI setup isn't capturing form data correctly, and how to fix it:

Key Issues in Your Current Code

  1. WSGI Compliance for Python3: The WSGI spec for Python3 requires your application to return an iterable of byte strings, not Unicode strings. Your current code returns a list of regular strings, which will cause silent failures or incorrect handling in uWSGI's Python3 plugin.
  2. Raw Body vs. Parsed Form Data: When sending multipart/form-data (via curl --form), reading the raw request body gives you the raw boundary-encoded data—not the parsed form fields you're likely expecting. Your Python2 setup might have worked by coincidence, but it's not the right way to handle form data.

Modified Code for Python3

Here's an updated version of your WSGI app that fixes both issues and properly parses form data:

import cgi

def application(environ, start_response):
    # Send 200 OK response header
    start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')])
    
    # Extract GET query string
    get_values = environ.get('QUERY_STRING', 'No GET parameters')
    
    # Initialize POST data storage
    post_values = 'No POST parameters'
    
    # Handle POST requests (like your curl --form call)
    if environ.get('REQUEST_METHOD') == 'POST':
        try:
            # Use cgi.FieldStorage to parse multipart/form-data
            form = cgi.FieldStorage(
                fp=environ['wsgi.input'],
                environ=environ,
                keep_blank_values=True
            )
            
            # Extract all form fields and their values
            post_data = []
            for field_name in form:
                field = form[field_name]
                # Handle file uploads separately if needed
                if field.filename:
                    post_data.append(f"{field_name}: Uploaded file '{field.filename}' (size: {len(field.value)} bytes)")
                else:
                    post_data.append(f"{field_name}: {field.value}")
            
            post_values = "\n".join(post_data)
        except Exception as e:
            post_values = f"Failed to parse POST data: {str(e)}"
    
    # Combine all output and encode to bytes (required for Python3 WSGI)
    output = f"Hello There!\n\nGET Values:\n{get_values}\n\nPOST Values:\n{post_values}"
    return [output.encode('utf-8')]

What Changed?

  • Byte String Return: The final output is encoded to UTF-8 bytes with .encode('utf-8'), which aligns with Python3's WSGI requirements.
  • Proper Form Parsing: Using cgi.FieldStorage (built into Python's standard library) correctly parses multipart/form-data requests, extracting both regular form fields (like your q=c parameter) and file upload details.
  • Error Handling: Added basic error handling for form parsing to help debug any unexpected issues.

Verify Your uWSGI Command

Ensure your uWSGI startup command is using the correct Python3 plugin path (adjust the path if needed for your system):

uwsgi --socket myapp.sock --plugins /usr/lib/uwsgi/plugins/python3_plugin.so --module wsgi --chmod-socket=664

Test with Your curl Command

Run your original curl request again:

curl -v --form 'file=@testfile;filename=newfilename' --form 'q=c' localhost?q=x

You should now see both the GET parameter (q=x) and POST parameters (q=c and file details) correctly displayed in the response.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:45:27