1

I am using the Python C library and FastCGI to run code in a file and return the output to NGINX. The problem is PyRun_SimpleString outputs to stdout, which is fine for a CLI, but is ignored by FastCGI.

The code I tried was this:

#include <Python.h>
#include <string.h>
#include <fcgi_stdio.h>

int main() {
    Py_Initialize();

    while (FCGI_Accept() >= 0) {
        printf("Content-type: text/plain\r\n\r\n");
        PyRun_SimpleString("print('hey')");
    }

    Py_Finalize();

    return 0;
}

My NGINX config:

location / {
    fastcgi_pass unix:/tmp/sock-fcgi.sock;
    include fastcgi_params;
    fastcgi_param  REQUEST_URI $uri;
    fastcgi_param SCRIPT_FILENAME $request_filename;
}

The returned value (from both curling the NGINX server and cgi-fcgi -connect /tmp/sock-fcgi.sock ./COMPILED_FILE):

Content-type: text/plain

What I was expecting:

Content-type: text/plain

hey

EDIT: Running COMPILED_FILE without cgi-fcgi as you would run any other C programme outputs the expected values.

11
  • The question does not make sense. In both traditional CGI and FastCGI, the standard output is the primary channel for CGI code to deliver response data to the web server. And that's where printf sends its output, so it looks like that's working for you. The issue might be that Python is sending its output somewhere else, but my guess would be that the embedded Python interpreter is not generating output at all. Commented May 25, 2023 at 14:32
  • fcgi_stdio provides the printf function, as well as the other functions in the stdio header. Commented May 25, 2023 at 14:34
  • Ok. Not exactly. It looks like fcgi_stdio hijacks the stdio function names by providing macros that redirect calls to its own replacement functions. For many purposes, that will look the same, but there are ways in which the differences will manifest. Commented May 25, 2023 at 14:45
  • 1
    If you're stuck with the C wrapper and your particular fastCGI library, then your best bet may be to have your Python code return its output to C as a (Python) string instead of printing it directly. Let the C code then print the string. Commented May 25, 2023 at 14:50
  • 1
    If you don't control the Python code, then it is better in every way to run it in a separate process, preferably well sandboxed, and capture its output. You can then forward that output to the fastCGI library. I don't think it's feasible to get Python to write directly, because my take is that your fastCGI library relies on output going through its functions, not just going to the correct underlying sink. Commented May 25, 2023 at 15:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.