Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

79 lines
2.4KB

  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. def get_tool(tool_id):
  7. tool = Tool.query.filter_by(id=tool_id).first()
  8. if tool is None:
  9. abort(404)
  10. return tool
  11. tool = Blueprint('tool', __name__)
  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'))