Last active
December 4, 2022 19:29
-
-
Save acg/5905629 to your computer and use it in GitHub Desktop.
Exercise a flask app on stdio instead of a socket.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
wsgiref.handlers.CGIHandler