rest_api.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. from os import environ
  2. from flask import Flask, Response, jsonify, render_template, request
  3. from transliterator.tables import list_tables, load_table
  4. from transliterator.trans import transliterate
  5. def create_app():
  6. app = Flask(__name__)
  7. app.config.update({
  8. "ENV": environ.get("TXL_APP_MODE", "production"),
  9. "SECRET_KEY": environ["TXL_FLASK_SECRET"],
  10. "USE_X_SENDFILE": True,
  11. "JSON_AS_ASCII": False,
  12. "JSONIFY_PRETTYPRINT_REGULAR": True,
  13. })
  14. return app
  15. app = create_app()
  16. @app.route("/", methods=["GET"])
  17. def index():
  18. return render_template("index.html", languages=list_tables())
  19. @app.route("/health", methods=["GET"])
  20. def health_check():
  21. return "I'm alive!\n"
  22. @app.route("/languages", methods=["GET"])
  23. def list_languages():
  24. return jsonify(list_tables())
  25. @app.route("/table/<lang>")
  26. def dump_table(lang):
  27. """
  28. Dump parsed transliteration table for a language.
  29. """
  30. return jsonify(load_table(lang))
  31. @app.route("/transliterate", methods=["POST"])
  32. def transliterate_form():
  33. """ UI version of the `trans` endpoint. Passes everything via form. """
  34. return transliterate_req(
  35. request.form["lang"], request.form.get("r2s", False))
  36. @app.route("/trans/<lang>/r2s", methods=["POST"], defaults={"r2s": True})
  37. @app.route("/trans/<lang>", methods=["POST"])
  38. def transliterate_req(lang, r2s=False):
  39. in_txt = request.form["text"]
  40. if not len(in_txt):
  41. return ("No input text provided! ", 400)
  42. return Response(
  43. transliterate(in_txt, lang, r2s),
  44. content_type="text/plain")