def delete_idea(request, idea_id): idea = Idea.objects.get(id = idea_id) if not request.user == idea.user: messages.error(request, "You're not the author of this idea") else: Idea.delete(idea) return HttpResponseRedirect("/")
def test_get_all_ideas(self): self.addTestModels() idea = Idea() idea.title = 'Testy Title' idea.description = 'Testy Description' idea.user_id = self.testUser.id self.addModel(idea) self.assertCountEqual([idea, self.testIdea], get_all_ideas())
def addIdeas(self): ideas = [] for i in range(15): idea = Idea() idea.title = str(i) self.addModel(idea) ideas.append(idea) return ideas
def test_get_random_unvoted_idea_for_user(self): self.addModel(self.testUser) self.addModel(self.testIdea) idea = Idea() idea.title = 'Unique Title' idea.category = 'Unique Category' idea.tags = 'Unique Tag' self.addModel(idea) self.assertEqual(self.testIdea, get_random_unvoted_idea_for_user(self.testUser.id))
def mutate(cls, _, info, title, body, category): author = User.objects(email=get_jwt_identity()).first() new_idea = Idea(author=author, title=title, body=body, category=category) new_idea.save() author.update(inc__point=50) author.update(push__ideas=new_idea) idea_activity_logger(user=author, type="new") return NewIdeaMutation(result=ResponseMessageField( is_success=True, message="Idea upload success"))
def save_idea_by_form(form, user_id): idea = Idea(title=form.title.data, description=form.description.data, category=form.category.data, tags=form.tags.data, user_id=user_id) return save_idea(idea)
def mutate(cls, _, info, id): user = User.objects(email=get_jwt_identity()).first() idea = Idea.objects(id=id).first() if idea is None: return VoteIdeaMutation(result=ResponseMessageField( is_success=False, message="Not found")) if user not in idea.upvoter: try: idea.update(push__upvoter=user) except Exception as e: return VoteIdeaMutation(result=ResponseMessageField( is_success=False, message=str(e))) idea_activity_logger(user=user, type="vote") return VoteIdeaMutation(result=ResponseMessageField( is_success=True, message="Vote success")) elif user in idea.upvoter: try: idea.update(pull__upvoter=user) except Exception as e: return VoteIdeaMutation(result=ResponseMessageField( is_success=False, message=str(e))) return VoteIdeaMutation(result=ResponseMessageField( is_success=True, message="Vote cancel success"))
def try_new(): form = AddIdeaForm() if form.validate_on_submit(): idea = Idea(user_id=current_user.id, title=form.title.data, description=form.description.data) db.session.add(idea) db.session.commit() flash('New idea has been saved!') return redirect(url_for('main.try_new')) if request.method == 'DELETE': idea_id = int(request.data) Idea.query.filter_by(id=idea_id).delete() db.session.commit() flash('Idea has been deleted') return '' ideas = current_user.ideas return render_template('try_new.html', title='Try new', form=form, ideas=ideas)
def bookmarklet(request): posted = False if request.method == 'POST': #If something has been submitted if 'submit_idea' in request.POST: ideaForm = IdeaForm(request.POST) # A form bound to the POST data if ideaForm.is_valid(): # All validation rules pass # Process the data in form.cleaned_data # ... clean = ideaForm.cleaned_data idea = Idea(idea=clean['idea_content'], user = request.user, private=clean['private']) idea.save() helpers.filter_tags(clean['tags'], idea) posted = True ideaForm = IdeaForm() return render_to_response("main/bookmarklet.html", locals(), context_instance=RequestContext(request))
def save_idea_by_json(json_data, user): idea = Idea() idea.title = json_data['title'] idea.description = json_data['description'] idea.category = json_data['category'] idea.tags = json_data['tags'] idea.author = user return save_idea(idea)
def add_idea(user): idea = Idea() idea.title = '{} Awesome Idea'.format(user.username) idea.description = 'Description of an awesome Idea of {} with the title {}'.format(user.username, idea.title) idea.category = 'Engineering' idea.tags = '{},tag-{},#{},{}'.format(user.name.lower(), user.name.lower(), user.name.lower(), idea.title) idea.user_id = user.id db.session.add(idea) db.session.commit()
def create(self, request, apikey, apisignature): """ Creates an Idea """ if not key_check( apikey, apisignature, '/idea/post/'): return {'error':'authentication failed'} else: tags = False try: ideaForm = IdeaForm({"idea_content":request.POST['idea_text'],"tags":request.POST['idea_tags']}) except: ideaForm = IdeaForm({"idea_content":request.POST['idea_text'],}) else: if request.POST['idea_tags'] != '': tags = True #set tags if the user submitted them if ideaForm.is_valid(): private = False try: if request.POST['private'] == '1': private = True except: pass clean = ideaForm.cleaned_data idea = Idea(idea=clean['idea_content'], user = User.objects.get(id = request.POST['user_id']), private = private ) idea.save() # if tags: helpers.filter_tags(clean['tags'], idea) # try: # if request.POST['slate'] != "": # print "slate problem" # slate = Slate.objects.get(id=request.POST['slate']) # slate.ideas.add(idea) # slate.save() # except Error as e: # print e return idea else: return {'error':'no idea'}
def idea_base(session) -> Idea: new_tag: Tag = Tag(title="raincoat") session.add(new_tag) new_idea: Idea = Idea(email="*****@*****.**", code=str(uuid.uuid4()).upper().replace("-", "")[:10]) session.add(new_idea) session.commit() return new_idea
def add_idea(request, slate_id=None): print slate_id ideaForm = IdeaForm(request.POST) if ideaForm.is_valid(): # All validation rules pass # Process the data in form.cleaned_data # ... clean = ideaForm.cleaned_data idea = Idea( idea=clean['idea_content'], user = request.user, private = clean['private'], ) idea.save() if slate_id: print "add to slate" slate = Slate.objects.get(id=slate_id) slate.ideas.add(idea) slate.save() filter_tags(clean['tags'], idea) print "returning idea" return idea
def test_idea_title_constraint(self): first_idea = Idea() first_idea.title = 'MyTitle' second_idea = Idea() second_idea.title = 'MyTitle' self.addModel(first_idea) with self.assertRaises(IntegrityError): self.addModel(second_idea)
def idea_add(): form = IdeaForm() if form.validate_on_submit(): data = form.data idea = Idea( content=data['content'], logo = data['logo'] ) db.session.add(idea) db.session.commit() flash("添加说说成功", "ok") operate_log("添加说说:%s" % data['content']) return redirect(url_for('admin.idea_add')) return render_template('admin/idea_add.html', form=form)
def idea(session) -> Idea: new_tag: Tag = Tag(title="raincoat") session.add(new_tag) new_idea: Idea = Idea(email="*****@*****.**", code=str(uuid.uuid4()).upper().replace("-", "")[:10], title="raincoat", tag=[new_tag], body="I have an idea about raincoat") session.add(new_idea) session.commit() return new_idea
def mutate(cls, _, info, id, update): user = User.objects(email=get_jwt_identity()).first() idea = Idea.objects(id=id, author=user).first() if idea is None: return UpdateIdeaMutation(result=ResponseMessageField( is_success=False, message="Not found")) try: idea.update(set__body=update) except Exception as e: return UpdateIdeaMutation( result=ResponseMessageField(is_success=False, message=str(e))) # TODO: User Log 남기는 기능은 함수로 따로 빼자 return UpdateIdeaMutation(result=ResponseMessageField( is_success=True, message="Idea update success"))
def resolve_ideas(root, info, **kwargs): search = kwargs.get('search_string', None) filter_by = kwargs.get('filter_by', None) view_id = kwargs.get('view', None) start_rank = kwargs.get('start_rank', 1) - 1 if (view_id is not None) and (view_id != ""): idea = Idea.objects(id=view_id).first() if idea is None: return [ResponseMessageField(is_success=False, message="Not found")] return [IdeasField(id=view_id, author=idea.author.username, title=idea.title, body=idea.body, created_at=idea.created_at, upvoter=len([v.username for v in idea.upvoter]), vote_checked=True if True in [True for v in idea.upvoter if v.email == get_jwt_identity()] else False, comments=CommentResultField(comment_count=len(idea.comments), comments=[CommentField(author=c.author.username, body=c.body) for c in idea.comments]), category=idea.category)] ideas = Idea.objects[start_rank: start_rank + 30].order_by('point') if (filter_by is not None) and (filter_by != ""): ideas = [idea for idea in ideas if idea.category == filter_by] if (search is not None) and (search != ""): ideas = [idea for idea in ideas if (search in idea.body) or (search in idea.title)] return [IdeasField(id=str(idea.id), author=idea.author.username, title=idea.title, body=idea.body, created_at=idea.created_at, upvoter=len([v.username for v in idea.upvoter]), vote_checked=True if True in [True for v in idea.upvoter if v.email == get_jwt_identity()] else False, comments=CommentResultField(comment_count=len(idea.comments), comments=[CommentField(author=c.author.username, body=c.body) for c in idea.comments]), category=idea.category) for idea in ideas]
def mutate(cls, _, info, id, comment): user = User.objects(email=get_jwt_identity()).first() idea = Idea.objects(id=id).first() if idea is None: return NewCommentMutation(result=ResponseMessageField( is_success=False, message="Not found")) try: idea.update(push__comments=Comment(author=user, body=comment)) except Exception as e: return NewCommentMutation( result=ResponseMessageField(is_success=False, message=str(e))) user.update(inc__point=10) idea_activity_logger(user=user, type="comment") return NewCommentMutation( ResponseMessageField(is_success=True, message="Comment upload success"))
def test_get_ideas_by_search(self): self.addTestModels() idea = Idea() idea.title = 'Unique Title' idea.category = 'Unique Category' idea.tags = 'Unique Tag' idea.user_id = self.testUser.id self.addModel(idea) search = Search() self.assertCountEqual([self.testIdea, idea], get_ideas_by_search(search)) search.title = 'Unique' self.assertEqual([idea], get_ideas_by_search(search)) search.category = 'Unique Category' self.assertEqual([idea], get_ideas_by_search(search)) search.tags = 'Unique' self.assertEqual([idea], get_ideas_by_search(search))
def setTestIdea(self): self.testIdea = Idea() self.testIdea.title = 'My Awesome Test Idea' self.testIdea.description = 'Description of an Awesome Test Idea' self.testIdea.category = 'Engineering' self.testIdea.tags = self.testUser.tags
def pre_fill_db(): try: moods = [] moods.append( Mood(mood_name='Positive') ) #, is_active=1, created_by=1, created_date=datetime.now())) moods.append( Mood(mood_name='Neutral') ) #, is_active=1, created_by=1, created_date=datetime.now())) moods.append( Mood(mood_name='Negative') ) #, is_active=1, created_by=1, created_date=datetime.now())) # db.session.add(moods[0]) # db.session.add(moods[1]) # db.session.add(moods[2]) m = len(moods) for y in moods: db.session.add(moods[m]) m += 1 tags = [] tags.append( Tags(tag_name='Unknown') ) #, is_active=1, created_by=1, created_date=datetime.now())) tags.append( Tags(tag_name='Work') ) #, is_active=1, created_by=1, created_date=datetime.now())) tags.append( Tags(tag_name='Family') ) #, is_active=1, created_by=1, created_date=datetime.now())) tags.append( Tags(tag_name='Friends') ) #, is_active=1, created_by=1, created_date=datetime.now())) tags.append( Tags(tag_name='Development') ) #, is_active=1, created_by=1, created_date=datetime.now())) db.session.add(tags[0]) db.session.add(tags[1]) db.session.add(tags[2]) db.session.add(tags[3]) notes = [] notes.append( Note(mood_id=random.randrange(1, 3), my_note=lorem.paragraph(), created_by=1, create_date=random_date())) notes.append( Note(mood_id=random.randrange(1, 3), my_note=lorem.paragraph(), created_by=1, create_date=random_date())) notes.append( Note(mood_id=random.randrange(1, 3), my_note=lorem.paragraph(), created_by=1, create_date=random_date())) notes.append( Note(mood_id=random.randrange(1, 3), my_note=lorem.paragraph(), created_by=1, create_date=random_date())) notes.append( Note(mood_id=random.randrange(1, 3), my_note=lorem.paragraph(), created_by=1, create_date=random_date())) notes.append( Note(mood_id=random.randrange(1, 3), my_note=lorem.paragraph(), created_by=1, create_date=random_date())) notes.append( Note(mood_id=random.randrange(1, 3), my_note=lorem.paragraph(), created_by=1, create_date=random_date())) notes.append( Note(mood_id=random.randrange(1, 3), my_note=lorem.paragraph(), created_by=1, create_date=random_date())) notes.append( Note(mood_id=random.randrange(1, 3), my_note=lorem.paragraph(), created_by=1, create_date=random_date())) notes.append( Note(mood_id=random.randrange(1, 3), my_note=lorem.paragraph(), created_by=1, create_date=random_date())) db.session.add(notes[0]) db.session.add(notes[1]) db.session.add(notes[2]) db.session.add(notes[3]) db.session.add(notes[4]) db.session.add(notes[5]) db.session.add(notes[6]) db.session.add(notes[7]) db.session.add(notes[8]) db.session.add(notes[9]) # tagnote = [] # tagnote.append(tags_notes(tags_id=1,notes_id=1)) # tagnote.append(tags_notes(tags_id=2,notes_id=1)) # tagnote.append(tags_notes(tags_id=3,notes_id=1)) # tagnote.append(tags_notes(tags_id=4,notes_id=1)) # tagnote.append(tags_notes(tags_id=2,notes_id=2)) # tagnote.append(tags_notes(tags_id=3,notes_id=2)) # tagnote.append(tags_notes(tags_id=4,notes_id=2)) # tagnote.append(tags_notes(tags_id=3,notes_id=3)) # tagnote.append(tags_notes(tags_id=4,notes_id=3)) # tagnote.append(tags_notes(tags_id=4,notes_id=4)) # db.session.add(tagnote[0]) # db.session.add(tagnote[1]) # db.session.add(tagnote[2]) # db.session.add(tagnote[3]) # db.session.add(tagnote[4]) # db.session.add(tagnote[5]) # db.session.add(tagnote[6]) # db.session.add(tagnote[7]) # db.session.add(tagnote[8]) # db.session.add(tagnote[9]) ideas = [] ideas.append( Idea(name=lorem.sentence(), description=lorem.paragraph(), is_active=random.choice([True, False]), created_by=1, create_date=random_date())) ideas.append( Idea(name=lorem.sentence(), description=lorem.paragraph(), is_active=random.choice([True, False]), created_by=1, create_date=random_date())) db.session.add(ideas[0]) db.session.add(ideas[1]) ideanotes = [] ideanotes.append( IdeaNotes(title=lorem.sentence(), description=lorem.paragraph(), is_active=random.choice([True, False]), idea_id=1, created_by=1, create_date=random_date(), follow_up_date=datetime.now() + timedelta(days=random.random()))) ideanotes.append( IdeaNotes(title=lorem.sentence(), description=lorem.paragraph(), is_active=random.choice([True, False]), idea_id=1, created_by=1, create_date=random_date(), follow_up_date=datetime.now() + timedelta(days=random.random()))) ideanotes.append( IdeaNotes(title=lorem.sentence(), description=lorem.paragraph(), is_active=random.choice([True, False]), idea_id=1, created_by=1, create_date=random_date(), follow_up_date=datetime.now() + timedelta(days=random.random()))) ideanotes.append( IdeaNotes(title=lorem.sentence(), description=lorem.paragraph(), is_active=random.choice([True, False]), idea_id=1, created_by=1, create_date=random_date(), follow_up_date=datetime.now() + timedelta(days=random.random()))) ideanotes.append( IdeaNotes(title=lorem.sentence(), description=lorem.paragraph(), is_active=random.choice([True, False]), idea_id=1, created_by=1, create_date=random_date(), follow_up_date=datetime.now() + timedelta(days=random.random()))) ideanotes.append( IdeaNotes(title=lorem.sentence(), description=lorem.paragraph(), is_active=random.choice([True, False]), idea_id=2, created_by=1, create_date=random_date(), follow_up_date=datetime.now() + timedelta(days=random.random()))) ideanotes.append( IdeaNotes(title=lorem.sentence(), description=lorem.paragraph(), is_active=random.choice([True, False]), idea_id=2, created_by=1, create_date=random_date(), follow_up_date=datetime.now() + timedelta(days=random.random()))) ideanotes.append( IdeaNotes(title=lorem.sentence(), description=lorem.paragraph(), is_active=random.choice([True, False]), idea_id=2, created_by=1, create_date=random_date(), follow_up_date=datetime.now() + timedelta(days=random.random()))) ideanotes.append( IdeaNotes(title=lorem.sentence(), description=lorem.paragraph(), is_active=random.choice([True, False]), idea_id=2, created_by=1, create_date=random_date(), follow_up_date=datetime.now() + timedelta(days=random.random()))) ideanotes.append( IdeaNotes(title=lorem.sentence(), description=lorem.paragraph(), is_active=random.choice([True, False]), idea_id=2, created_by=1, create_date=random_date(), follow_up_date=datetime.now() + timedelta(days=random.random()))) db.session.add(ideanotes[0]) db.session.add(ideanotes[0]) db.session.add(ideanotes[1]) db.session.add(ideanotes[2]) db.session.add(ideanotes[3]) db.session.add(ideanotes[4]) db.session.add(ideanotes[5]) db.session.add(ideanotes[6]) db.session.add(ideanotes[7]) db.session.add(ideanotes[8]) db.session.add(ideanotes[9]) db.session.commit() # except ValueError: except ValueError as e: # log.error("Creating mood: %s", ValueError) # print(db.error) print(e) db.session.rollback()
def ideas(): if not request.data: return make_response(jsonify(error="Missing parameters."), 400) if request.method == "POST": token = str(request.json.get('id', '')) user = User.query.filter_by(token=token) action = Action.query.filter_by( action=str(request.json.get('action', ''))) idea = Idea.query.filter_by( response=str(request.json.get('idea', ''))) categories = request.json.get('categories', '') if str(request.json.get('isGenius', '')) == 'True': is_genius = True if str(request.json.get('isGenius', '')) == 'False': is_genius = False if user.count() <= 0: return make_response(jsonify(error="User not found."), 404) elif idea.count() > 0: return make_response( jsonify( error= "{0} idea already exists in the database for {1} {2}.". format(action[0].action, user[0].first_name, user[0].last_name)), 400) else: idea = Idea(response=str(request.json.get('idea', '')), random_word=str(request.json.get( 'random_word', '')), user_id=user[0].id, action_id=action[0].id, is_genius=is_genius, question=str(request.json.get('question', ''))) idea.save() for category in categories: found_cat = Category.query.filter_by(name=category['name']) new_idea_categories = idea_categories.insert().values( idea_id=idea.id, category_id=found_cat[0].id) db.session.execute(new_idea_categories) db.session.commit() return make_response( jsonify( success= "{0} idea for {1} {2} has been successfully created!". format(action[0].action, user[0].first_name, user[0].last_name)), 200) if request.method == "DELETE": token = str(request.json.get('token', '')) user = User.query.filter_by(token=token) idea_id = str(request.json.get('idea_id', '')) if user.count() <= 0: return make_response(jsonify(error="User not found."), 404) else: idea = Idea.query.filter_by(id=idea_id, user_id=user[0].id) if idea.count() <= 0: return make_response(jsonify(error="Idea not found."), 404) else: idea_name = idea[0].question Idea.delete(idea[0]) return make_response('', 204)
def setUp(self): self.app = create_app(config_name="testing") self.client = self.app.test_client from app.models import User, Category, Action, Idea with self.app.app_context(): db.create_all() user = User(first_name="Ryan", last_name="Hantak", email="*****@*****.**", password="******") user.save() cat1 = Category(name="Finance") cat1.save() cat2 = Category(name="Education") cat2.save() cat3 = Category(name="Tech") cat3.save() action1 = Action(action="Create an app") action1.save() action2 = Action(action="Draft an ad campaign") action2.save() idea1 = Idea( user_id=user.id, random_word="Skate", action_id=action2.id, is_genius=True, question= "Create an ad campaign to sell a book about financial literacy.", response= "Two friends in a roller derby match are having a conversation about how they're investing their money, one tells the other about what they learned from the book and the second person is so impressed they want to buy it." ) idea1.save() idea2 = Idea( user_id=user.id, random_word="Bird", action_id=action1.id, is_genius=False, question="Create an app people use to trade stocks", response= "Make it easy to trade stocks mobile, charge a monthly fee so people don't feel like each trade costs them extra money and offer daily articles to encourage them to keep checking." ) idea2.save() user.categories.append(cat1) user.categories.append(cat2) user.categories.append(cat3) user.actions.append(action1) user.actions.append(action2) idea1.categories.append(cat1) idea1.categories.append(cat2) idea2.categories.append(cat1) idea2.categories.append(cat3) db.session.add_all([idea1, idea2]) db.session.commit() global user_token user_token = User.query.filter_by( email='*****@*****.**').first().token