您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. from flask import Blueprint, render_template, request, flash, redirect, url_for
  2. from flask_login import login_required, current_user
  3. from .models import Tool
  4. from werkzeug.exceptions import abort
  5. from . import db
  6. tool = Blueprint('tool', __name__)
  7. def get_tool(tool_id):
  8. tool = Tool.query.filter_by(id=tool_id).first()
  9. if tool is None:
  10. abort(404)
  11. return tool
  12. @tool.route('/tools')
  13. def get_tools():
  14. tools = Tool.query
  15. return render_template('tools.html', tools=tools)
  16. @tool.route('/tools/<int:tool_id>')
  17. def show_tool(tool_id):
  18. tool = get_tool(tool_id)
  19. return render_template('tool.html', tool=tool)
  20. @tool.route('/tools/<int:tool_id>/edit', methods=('GET', 'POST'))
  21. @login_required
  22. def edit_tool(tool_id):
  23. tool = get_tool(tool_id)
  24. if request.method == 'POST':
  25. name = request.form['name']
  26. description = request.form['description']
  27. if not name:
  28. flash('Name is required!')
  29. else:
  30. tool = Tool.query.get(tool_id)
  31. tool.name = name
  32. tool.description = description
  33. db.session.commit()
  34. return redirect(url_for('tool.get_tools'))
  35. return render_template('edit.html', tool=tool)
  36. @tool.route('/tools/create', methods=('GET', 'POST'))
  37. @login_required
  38. def create_tool():
  39. if request.method == 'POST':
  40. name = request.form.get('name')
  41. description = request.form.get('description')
  42. if not name:
  43. flash('Name is required!')
  44. else:
  45. tool = Tool.query.filter_by(name=name).first() # if this returns a tool, then the name already exists in database
  46. if tool: # if a tool is found, we want to redirect back to create page
  47. flash('Tool with same name already exists')
  48. return redirect(url_for('tool.create'))
  49. # create a new tool with the form data
  50. new_tool = Tool(name=name, description=description)
  51. # add the new user to the database
  52. db.session.add(new_tool)
  53. db.session.commit()
  54. return render_template('create.html')
  55. @tool.route('/tools/<int:tool_id>/delete', methods=('POST',))
  56. @login_required
  57. def delete_tool(tool_id):
  58. tool = get_tool(tool_id)
  59. deletion = Tool.query.get(tool_id)
  60. db.session.delete(deletion)
  61. db.session.commit()
  62. flash('Successfully deleted!')
  63. return redirect(url_for('tool.get_tools'))