A copyright violation detector running on Wikimedia Cloud Services https://tools.wmflabs.org/copyvios/
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

app.py 3.8 KiB

10年前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. #! /usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from functools import wraps
  4. from json import dumps
  5. from logging import DEBUG, INFO, getLogger
  6. from logging.handlers import TimedRotatingFileHandler
  7. from time import asctime
  8. from traceback import format_exc
  9. from earwigbot.bot import Bot
  10. from earwigbot.wiki.copyvios import globalize
  11. from flask import Flask, g, make_response, request
  12. from flask.ext.mako import MakoTemplates, render_template, TemplateError
  13. from copyvios.api import format_api_error, handle_api_request
  14. from copyvios.checker import do_check
  15. from copyvios.cookies import parse_cookies
  16. from copyvios.misc import cache, get_notice
  17. from copyvios.settings import process_settings
  18. from copyvios.sites import update_sites
  19. app = Flask(__name__)
  20. MakoTemplates(app)
  21. hand = TimedRotatingFileHandler("logs/app.log", when="midnight", backupCount=7)
  22. hand.setLevel(DEBUG)
  23. app.logger.addHandler(hand)
  24. app.logger.info(u"Flask server started " + asctime())
  25. def catch_errors(func):
  26. @wraps(func)
  27. def inner(*args, **kwargs):
  28. try:
  29. return func(*args, **kwargs)
  30. except TemplateError as exc:
  31. app.logger.error(u"Caught exception:\n{0}".format(exc.text))
  32. return render_template("error.mako", traceback=exc.text)
  33. except Exception:
  34. app.logger.exception(u"Caught exception:")
  35. return render_template("error.mako", traceback=format_exc())
  36. return inner
  37. @app.before_first_request
  38. def setup_app():
  39. cache.bot = Bot(".earwigbot", 100)
  40. cache.langs, cache.projects = [], []
  41. cache.last_sites_update = 0
  42. cache.background_data = {}
  43. cache.last_background_updates = {}
  44. getLogger("earwigbot.wiki.cvworker").setLevel(INFO)
  45. globalize()
  46. @app.before_request
  47. def prepare_request():
  48. g._db = None
  49. g.cookies = parse_cookies(
  50. request.script_root, request.environ.get("HTTP_COOKIE"))
  51. g.new_cookies = []
  52. @app.after_request
  53. def add_new_cookies(response):
  54. for cookie in g.new_cookies:
  55. response.headers.add("Set-Cookie", cookie)
  56. return response
  57. @app.after_request
  58. def write_access_log(response):
  59. msg = u"%s %s %s %s -> %s"
  60. app.logger.debug(msg, asctime(), request.method, request.path,
  61. request.values.to_dict(), response.status_code)
  62. return response
  63. @app.teardown_appcontext
  64. def close_databases(error):
  65. if g._db:
  66. g._db.close()
  67. @app.route("/")
  68. @catch_errors
  69. def index():
  70. notice = get_notice()
  71. update_sites()
  72. query = do_check()
  73. return render_template(
  74. "index.mako", notice=notice, query=query, result=query.result)
  75. @app.route("/settings", methods=["GET", "POST"])
  76. @catch_errors
  77. def settings():
  78. status = process_settings() if request.method == "POST" else None
  79. update_sites()
  80. default = cache.bot.wiki.get_site()
  81. kwargs = {"status": status, "default_lang": default.lang,
  82. "default_project": default.project}
  83. return render_template("settings.mako", **kwargs)
  84. @app.route("/api")
  85. @catch_errors
  86. def api():
  87. return render_template("api.mako", help=True)
  88. @app.route("/api.json")
  89. @catch_errors
  90. def api_json():
  91. if not request.args:
  92. return render_template("api.mako", help=True)
  93. format = request.args.get("format", "json")
  94. if format in ["json", "jsonfm"]:
  95. update_sites()
  96. try:
  97. result = handle_api_request()
  98. except Exception as exc:
  99. result = format_api_error("unhandled_exception", exc)
  100. else:
  101. errmsg = u"Unknown format: '{0}'".format(format)
  102. result = format_api_error("unknown_format", errmsg)
  103. if format == "jsonfm":
  104. return render_template("api.mako", help=False, result=result)
  105. resp = make_response(dumps(result))
  106. resp.mimetype = "application/json"
  107. resp.headers["Access-Control-Allow-Origin"] = "*"
  108. return resp
  109. if __name__ == '__main__':
  110. app.run()