Last active
May 21, 2020 18:12
-
-
Save Tythos/2916b0fb12809c763d0ed593aa762cb7 to your computer and use it in GitHub Desktop.
Basic reusable server base, using Flask-based WSGI application served asynchronously w/ gevent.pywsgi
This file contains 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
"""Basic reusable server base, using Flask-based WSGI application served | |
asynchronously with gevent.pywsgi; provides a nice template / starting point | |
that I've reused several dozen times. | |
""" | |
import os | |
import flask | |
from gevent import pywsgi | |
MOD_PATH, _ = os.path.split(os.path.abspath(__file__)) | |
_, MOD_NAME = os.path.split(MOD_PATH) | |
APP = flask.Flask(MOD_NAME) | |
@APP.route("/", methods=["GET"]) | |
def index(): | |
"""Flask-like endpoints are easily identifiable and access request | |
information via flask.request ; might be useful in the near-future to | |
provide more examples of things like reading request body data, | |
websockets, query arguments, path-matching, request headers, etc. I do | |
use the three-element tuple return format here, partly as an example but | |
also because I've found it very helpful to explicitly declare response | |
codes and header fields in many different situations. | |
""" | |
return "Hey.", 200, {"Content-Type": "text/plain"} | |
def main(): | |
"""Launching via command line, by default entry point, will start pywsgi | |
with the module-defined Flask app. Environmental variables can be used | |
to override port and host used (useful for container-based services). | |
The APP module-level symbol can be customized to programmatically extend | |
the service from outside the module, if desired, but most use cases will | |
copy-and-paste this file to extend/define their own service. | |
""" | |
host = os.getenv("SERVICE_HOST", "0.0.0.0") | |
port = int(os.getenv("SERVICE_PORT", 5000)) | |
print("Starting %s client hosting at %s:%u..." % (MOD_NAME, host, port)) | |
pywsgi.WSGIServer((host, port), APP).serve_forever() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment