Skip to content

Instantly share code, notes, and snippets.

@acg
Last active December 4, 2022 19:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acg/5905629 to your computer and use it in GitHub Desktop.
Save acg/5905629 to your computer and use it in GitHub Desktop.
Exercise a flask app on stdio instead of a socket.
#!/usr/bin/env python
'''
Most flask examples use a socket.
This flask example reads HTTP from stdin and writes HTTP to stdout.
A single HTTP request is processed.
Usage:
printf "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n" | ./flask-stdio
Note: not working yet under tcpserver, wants to read until EOF.
'''
from flask import Flask
from http_parser.http import HttpStream
from http_parser.reader import IterReader
import wsgiref.handlers
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello world."
class WSGIStdioHandler( wsgiref.handlers.SimpleHandler ):
def setup_environ( self ):
httpin = HttpStream(IterReader(self.get_stdin()), kind=0)
headers = httpin.headers()
environ = httpin.wsgi_environ()
environ['wsgi.input'] = httpin.body_file()
environ['wsgi.errors'] = self.get_stderr()
environ['wsgi.version'] = (1, 0)
environ['wsgi.multithread'] = False
environ['wsgi.multiprocess'] = False
environ['wsgi.run_once'] = True
self.environ = environ
if __name__ == '__main__':
import sys
handler = WSGIStdioHandler( sys.stdin, sys.stdout, sys.stderr, {}, multithread=False, multiprocess=False )
handler.run(app)
@Lucyfurnice
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment