5

I'm trying to run Flask as a simple CGI app through IIS.

I have the following code:

from wsgiref.handlers import CGIHandler
from flask import Flask
app = Flask(__name__)

@app.route('/')
def main():
    return 'Woo woo!'

CGIHandler().run(app)

I'm runing Python 3.3 on Windows. I get the following error:

File "C:\Python33\lib\wsgiref\handlers.py", 
line 509, in __init__(self, sys.stdin.buffer, sys.stdout.buffer, sys.stderr, )
AttributeError: 'NoneType' object has no attribute 'buffer' ".

I added some logging code, and it turns out that sys.stdin is None.

Python is added to IIS as a CGI Handler as follows:

Request path: *.py
Executable: C:\Windows\py.exe -3 %s %s

So, why is sys.stdin None, and how can I fix it?

EDIT

It looks like sys.stdin is None because the file descriptor is invalid.

Wayne Werner
  • 49,299
  • 29
  • 200
  • 290
  • While migrating an existing website with multiple Python CGI scripts from Apache to IIS, I noticed that stdin is None for the POST requests without any Form Data provided – Sergey Nudnov May 08 '20 at 15:37

1 Answers1

6

Interesting. You've answered half your own question. The other half ("how do I fix it") is easy enough, just open some suitable thing (os.devnull is the obvious one) and set sys.stdin to point there. You'll need to do sys.stdout and sys.stderr as well, presumably, so something like this:

import os, sys
for _name in ('stdin', 'stdout', 'stderr'):
    if getattr(sys, _name) is None:
        setattr(sys, _name, open(os.devnull, 'r' if _name == 'stdin' else 'w'))
del _name # clean up this module's name space a little (optional)
from wsgiref.handlers ...

should do the trick.

Wayne Werner
  • 49,299
  • 29
  • 200
  • 290
torek
  • 448,244
  • 59
  • 642
  • 775
  • This ended out being half my solution - the other half was using `IISCGIHandler()`, because apparently IIS has some problems. Also, I just ended out replacing `stdin` with `os.devnull` and life was peachy. – Wayne Werner Jul 08 '13 at 18:42
  • @WayneWerner, could you please advise what is `IISCGIHandler()`? Is that function/class you created? Could you please share it? – Sergey Nudnov May 08 '20 at 15:38
  • @SergeyNudnov a quick Google search for `python iiscgihandler` turned up https://docs.python.org/3/library/wsgiref.html#wsgiref.handlers.IISCGIHandler – Wayne Werner May 11 '20 at 15:49