test.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. from flask import blueprints, render_template, current_app, abort, redirect, url_for, flash, make_response
  2. from flask_login import current_user, login_required
  3. from .user import UserWordDataBase
  4. from itsdangerous import URLSafeTimedSerializer
  5. from itsdangerous.exc import BadData
  6. test = blueprints.Blueprint("test", __name__)
  7. @test.route("/")
  8. @login_required
  9. def question():
  10. user: UserWordDataBase = current_user
  11. word = user.rand_word()
  12. if word is None:
  13. return render_template("not_word.html")
  14. serializer = URLSafeTimedSerializer(current_app.config["SECRET_KEY"])
  15. word_id = serializer.dumps({"word": word.name})
  16. return render_template("test.html", word=word, len=len, word_id=word_id) # 需要使用len函数
  17. @test.route("/right/<string:word_id>")
  18. @login_required
  19. def right(word_id: str):
  20. serializer = URLSafeTimedSerializer(current_app.config["SECRET_KEY"])
  21. try:
  22. word: dict = serializer.loads(word_id, max_age=120) # 120s内生效
  23. user: UserWordDataBase = current_user
  24. user.right_word(word["word"])
  25. except (BadData, KeyError):
  26. abort(404)
  27. return redirect(url_for("test.question"))
  28. @test.route("/wrong/<string:word_id>")
  29. @login_required
  30. def wrong(word_id: str):
  31. serializer = URLSafeTimedSerializer(current_app.config["SECRET_KEY"])
  32. try:
  33. word: dict = serializer.loads(word_id, max_age=120) # 120s内生效
  34. user: UserWordDataBase = current_user
  35. user.wrong_word(word["word"])
  36. except (BadData, KeyError):
  37. abort(404)
  38. return redirect(url_for("test.question"))
  39. @test.route("/delete/<string:word>")
  40. @login_required
  41. def delete(word: str):
  42. user: UserWordDataBase = current_user
  43. user.delete_txt(word)
  44. flash(f"Word '{word}' is deleted.")
  45. return redirect(url_for("test.question"))
  46. @test.route("/download/<string:word>")
  47. @login_required
  48. def download(word: str):
  49. user: UserWordDataBase = current_user
  50. w = user.find_word(word, False)
  51. if w is None:
  52. abort(404)
  53. w_str = f"{w.name}\n"
  54. for i in w.comment:
  55. comment = w.comment[i]
  56. w_str += f" {comment.part}\n {comment.english}\n {comment.chinese}\n"
  57. for a in comment.eg:
  58. e, c = a.split("##")
  59. w_str += f" {e}\n {c}\n"
  60. response = make_response(w_str)
  61. response.headers["Content-Disposition"] = f"attachment;filename={word}.henglish.txt"
  62. return response