From 64d270dc4d3cdd2f5c742793aaf4ddcd95ba2734 Mon Sep 17 00:00:00 2001 From: Piero Toffanin Date: Tue, 6 Jul 2021 20:26:06 -0400 Subject: [PATCH] wsgi support --- README.md | 15 +++++++++++++++ app/main.py | 22 +++++++++++++--------- wsgi.py | 19 +++++++++++++++++++ 3 files changed, 47 insertions(+), 9 deletions(-) create mode 100644 wsgi.py diff --git a/README.md b/README.md index e0a8598..efb9ec9 100644 --- a/README.md +++ b/README.md @@ -118,6 +118,21 @@ docker-compose up -d --build | --require-api-key-origin | Require use of an API key for programmatic access to the API, unless the request origin matches this domain | `No restrictions on domain origin` | | --load-only | Set available languages | `all from argostranslate` | +## Run with Gunicorn + +``` +pip install gunicorn +gunicorn --bind 0.0.0.0:5000 'wsgi:app' +``` + +You can pass application arguments directly to Gunicorn via: + + +``` +gunicorn --bind 0.0.0.0:5000 'wsgi:app(api_keys=True)' +``` + + ## Manage API Keys LibreTranslate supports per-user limit quotas, e.g. you can issue API keys to users so that they can enjoy higher requests limits per minute (if you also set `--req-limit`). By default all users are rate-limited based on `--req-limit`, but passing an optional `api_key` parameter to the REST endpoints allows a user to enjoy higher request limits. diff --git a/app/main.py b/app/main.py index a4ac6f9..9057946 100644 --- a/app/main.py +++ b/app/main.py @@ -1,4 +1,5 @@ import argparse +import sys import operator from app.app import create_app @@ -103,17 +104,20 @@ def main(): args = parser.parse_args() app = create_app(args) - if args.debug: - app.run(host=args.host, port=args.port) + if sys.argv[0] == '--wsgi': + return app else: - from waitress import serve + if args.debug: + app.run(host=args.host, port=args.port) + else: + from waitress import serve - serve( - app, - host=args.host, - port=args.port, - url_scheme="https" if args.ssl else "http", - ) + serve( + app, + host=args.host, + port=args.port, + url_scheme="https" if args.ssl else "http", + ) if __name__ == "__main__": diff --git a/wsgi.py b/wsgi.py new file mode 100644 index 0000000..aaf531e --- /dev/null +++ b/wsgi.py @@ -0,0 +1,19 @@ +from app import main + +def app(*args, **kwargs): + import sys + sys.argv = ['--wsgi'] + for k in kwargs: + ck = k.replace("_", "-") + if isinstance(kwargs[k], bool) and kwargs[k]: + sys.argv.append("--" + ck) + else: + sys.argv.append("--" + ck) + sys.argv.append(kwargs[k]) + + instance = main() + + if len(kwargs) == 0: + return instance(*args, **kwargs) + else: + return instance