def create_project(): """ This route adds a new project to the database and returns a success message as a json object. Returns {Object<json>} 200 success: {string} project: {Object<json>} Throws {Exception{Object<json>}} error: NotAuthorized 401 NoResultFound 404 SQLAlchemyError 400 """ # Get the user's id from access token uid = get_jwt_identity() # If no user id, return error if not uid: return make_response( jsonify({'error': 'Could not verify!'}), 401, {'WWW-Authentication': 'Basic realm="Login required!"'}) # Try to get user from database query = User.query.filter_by(public_id=uid) try: user = query.one() # If no result found, return error except NoResultFound: return jsonify({'error': 'No result found!'}), 401 # If some other sqlalchemy error is thrown, return error except SQLAlchemyError: return jsonify({'error': 'Some problem occurred!'}), 400 # Get project data from request data = request.get_json() # Verify that all required project data was sent # TODO: Add topics as required. Do I have to post directly to # topics table or can I post to relationship table??? if not data['title'] or not data['description']: return make_response(jsonify({'error': 'Missing data!'}), 400) # Create project object project = Project(title=data['title'], description=data['description'], created_at=datetime.utcnow()) # Add additional non-required project data if it was sent if 'img_url' in data: project.img_url = data['img_url'] if 'alt' in data: project.alt = data['alt'] if 'site_url' in data: project.site_url = data['site_url'] if 'github_url' in data: project.github_url = data['github_url'] if 'read_me' in data: project.read_me = data['read_me'].encode() if 'topic_main' in data: project.topic_main = data['topic_main'] # Try to add project to database try: db.session.add(project) db.session.commit() # If project name already in database, return error except IntegrityError: return jsonify({'error': 'User with name or email already exists'}), 400 # If some other sqlalchemy error is thrown, return error except SQLAlchemyError: return jsonify({'error': 'Some problem occurred!'}), 400 if 'topics' in data: for id in data['topics']: # Create project topics object project_topics = ProjectTopics(project_id=project.id, topic_id=id) # Try to add project_topics to database try: db.session.add(project_topics) db.session.commit() # If project name already in database, return error except IntegrityError: return jsonify( {'error': 'User with name or email already exists'}), 400 # If some other sqlalchemy error is thrown, return error except SQLAlchemyError: return jsonify({'error': 'Some problem occurred!'}), 400 # Serialze the project object and return json response project_schema = ProjectSchema() output = project_schema.dump(project).data return jsonify({ 'success': 'Successfully retrieved project.', 'project': output }), 200