Skip to content

Instantly share code, notes, and snippets.

@Porter97
Created April 27, 2020 20:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Porter97/a4d07e0fb6a27b86aeb3d6d2990355ae to your computer and use it in GitHub Desktop.
Save Porter97/a4d07e0fb6a27b86aeb3d6d2990355ae to your computer and use it in GitHub Desktop.
from flask import render_template, jsonify, flash, abort
from .forms import EditProfileForm, CollectionForm
from .errors import page_not_found, internal_server_error
from ..models import User, Collection, Permission'
#...
@main.route('/collections/<int:id>')
def get_collection(id):
collection = Collection.query.get_or_404(id)
return {'collection': collection.to_json()}
@main.route('/collections', methods=['POST'])
@login_required
def create_collection():
form = CollectionForm()
if current_user.can(Permission.WRITE) and form.validate_on_submit():
collection = Collection(name=form.name.data,
description=form.description.data,
author=current_user._get_current_object())
db.session.add(collection)
current_user.follow_collection(collection)
db.session.commit()
if collection.add_to_stream():
flash("You have created a new Collection!")
return {'collection': collection.to_json()}
else:
db.session.delete(collection)
db.session.commit()
return internal_server_error('An Error occurred, please try again')
return {'errors': {fieldName.title(): errorMessages for fieldName, errorMessages in form.errors.items()}}, 400
@main.route('/collections/<int:id>', methods=['PUT'])
@login_required
def update_collection(id):
collection = Collection.query.get_or_404(id)
if current_user != collection.author and \
not current_user.can(Permission.ADMIN):
abort(403)
form = CollectionForm()
if form.validate_on_submit():
# Update Database
collection.name = form.name.data
collection.description = form.description.data
db.session.commit()
# Update Stream Activity
if collection.update_stream():
return {'collection': collection.to_json()}
return {'errors': {fieldName.title(): errorMessages for fieldName, errorMessages in form.errors.items()}}, 400
@main.route('/collections/<int:id>', methods=['DELETE'])
@login_required
def delete_collection(id):
collection = Collection.query.get_or_404(id)
if current_user != collection.author and \
not current_user.can(Permission.ADMIN):
abort(403)
if collection.delete_from_stream():
db.session.delete(collection)
db.session.commit()
flash('Your Collection has been deleted')
return {'success': 200}
else:
return internal_server_error('An Error occurred, please try again')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment