def update_week(year=None, week=None): if not year or not week: (year, week) = this_week() text = request.json.get("text", "") tags = request.json.get("tags", []) Snippet.update(g.current_user.id, year, week, text, tags) return jsonify({"success": True})
def test_get_week_existing(self): Snippet.update(self.user.id, 2017, 9, "foo", ["blue", "red"]) resp = self.get("/api/weeks/2017/9", self.valid_api_headers()) self.assertEqual(200, resp.status_code) self.assertEqual(2017, resp.json["year"]) self.assertEqual(9, resp.json["week"]) self.assertEqual("foo", resp.json["text"]) self.assertSetEqual({"blue", "red"}, set(resp.json["tags"]))
def get_week(year=None, week=None): if not year or not week: (year, week) = this_week() snippet = Snippet.get_by_week(g.current_user.id, year, week) if snippet is None: # don't worry about actually adding to the database until user saves snippet = Snippet(user_id=g.current_user.id, year=year, week=week) return jsonify(snippet.to_json())
def test_update_no_such_user(self): user_id = self.user.id + 1 snippet = self.snippets[1] self.assertFalse("blargh" in [tag.text for tag in snippet.tags]) self.assertFalse("blue" in [tag.text for tag in snippet.tags]) Snippet.update(user_id, snippet.year, snippet.week, "blargh", ["blue"]) self.assertFalse("blargh" in [tag.text for tag in snippet.tags]) self.assertFalse("blue" in [tag.text for tag in snippet.tags])
def test_update_week(self): user_id = self.user.id snippet = self.snippets[1] self.assertNotEqual("blargh", snippet.text) self.assertFalse("blue" in {tag.text for tag in snippet.tags}) Snippet.update(user_id, snippet.year, snippet.week, "blargh", ["blue"]) after = Snippet.query.get(snippet.id) self.assertEqual("blargh", snippet.text) self.assertTrue("blue" in {tag.text for tag in after.tags})
def test_get_current_week_existing(self): (year, week) = this_week() Snippet.update(self.user.id, year, week, "foo", ["blue", "red"]) resp = self.get("/api/weeks/current", self.valid_api_headers()) self.assertEqual(200, resp.status_code) self.assertEqual(year, resp.json["year"]) self.assertEqual(week, resp.json["week"]) self.assertEqual("foo", resp.json["text"]) self.assertSetEqual({"blue", "red"}, set(resp.json["tags"]))
def test_get_weeks_tag_filter(self): Snippet.update(self.user.id, 2017, 9, "foo", ["blue", "red"]) Snippet.update(self.user.id, 2011, 18, "bar", ["green"]) resp = self.get("/api/weeks/?tag=blue", self.valid_api_headers()) self.assertEqual(1, resp.json["count"]) weeks = resp.json["weeks"] self.assertSetEqual( {(2017, 9)}, {(snippet["year"], snippet["week"]) for snippet in weeks}, )
def test_update_week_create_new(self): date = iso_week_begin(datetime.date(44, 3, 15)) (yr, wk, _) = date.isocalendar() self.assertIsNone(Snippet.query.filter_by(year=yr, week=wk).first()) Snippet.update(self.user.id, yr, wk, "beware", ["senate", "prophecy"]) found = Snippet.query.filter_by(year=yr, week=wk).first() self.assertIsNotNone(found) self.assertEqual("beware", found.text) self.assertSetEqual({"senate", "prophecy"}, {tag.text for tag in found.tags})
def edit(year=None, week=None) -> Union[Response, Text]: if not year or not week: (year, week) = this_week() return redirect(url_for(".edit", year=year, week=week)) if not is_valid_iso_week(year, week): raise ValidationError("invalid ISO week date") # if updating, always redirect to the same week form = SnippetsForm() if form.validate_on_submit(): tags = [text.strip() for text in form.tags.data.split(",")] Snippet.update(current_user.id, year, week, form.text.data, tags) return redirect(url_for(".edit", year=year, week=week)) return render_snippet_form(form, current_user, year, week)
def story(request,storyID): if request.user.is_authenticated(): story = Story.objects.get(id=storyID) print story.category new_sequence = Snippet.objects.filter(story=story).count()+1 already_taken = Snippet.objects.filter(story=story,sequence=new_sequence) if already_taken: print "finns redan" return HttpResponseRedirect('') snippets = Snippet.objects.filter(story=story) chars_left=story.length for s in snippets: chars_left-=len(s.text) snip_form=SnippetForm() chars_used=story.length-chars_left elem= { 'title':story.title, 'story':story, 'snippets':snippets, 'snip_form':snip_form, 'chars_left':chars_left, 'chars_used':chars_used, } if request.method=='POST': snip_form=SnippetForm(request.POST) elem.update({'snip_form':snip_form,}) framtida_chars_left = chars_left-len(request.POST['text']) if 0>framtida_chars_left: print "för många tecken"+str(framtida_chars_left) print story.length #okokokok elem.update({'error':(request.POST['text'])}) return render_to_response("newsnip.html",elem,context_instance=RequestContext(request)) if snip_form.is_valid(): print snip_form.cleaned_data newsnip=Snippet(created=datetime.datetime.now(),author=request.user,text=snip_form.cleaned_data['text'],story=story,sequence=new_sequence) newsnip.save() return HttpResponseRedirect('') else: elem.update({'error':"invalid snippetform"}) return render_to_response("newsnip.html",elem,context_instance=RequestContext(request)) else: snip_form=SnippetForm() elem.update({'snip_form':snip_form,}) return render_to_response("newsnip.html",elem,context_instance=RequestContext(request)) return render_to_response("newsnip.html",elem,context_instance=RequestContext(request)) else: return HttpResponseRedirect("/")
def test_get_by_week(self): year = self.snippets[0].year week = self.snippets[0].week user_id = self.snippets[0].user_id found = Snippet.get_by_week(user_id, year, week) self.assertIsNotNone(found) self.assertEqual(self.snippets[0].id, found.id)
def results(): """Results page for searches. :results: If there is a query searches ElasticSearch and returns the results. If there is no query returns the 10 most recently created Snippets. """ query = request.args.get('q') if query: # Set the form search field to match the query so that the form is # completed on the results page. g.search_form.query.data = query # Construct the query to be passed to ElasticSearch. body = { "query": { "query_string": { "query": query, } } } results = Snippet.es_search(body=body) return render_template('snippets/results.html', results=results, query=query) else: results = Snippet.query.order_by(-Snippet.id).limit(10).all() return render_template('index.html', results=results)
def test_get_weeks_empty(self): self.assertListEqual([], Snippet.get_all(self.user.id).all()) resp = self.get("/api/weeks/", self.valid_api_headers()) self.assertListEqual([], resp.json["weeks"]) self.assertIsNone(resp.json["prev_url"]) self.assertIsNone(resp.json["next_url"]) self.assertEqual(0, resp.json["count"])
def populate(self): self.tag = Tag(text="blue") self.snippets = [ Snippet(text="foo", year=2017, week=17, tags=[self.tag]), Snippet(text="bar", year=2012, week=9, tags=[]), ] self.user = User( email="*****@*****.**", name="Julius Caesar", password="******", confirmed=True, member_since=datetime.date.today(), snippets=self.snippets, ) db.session.add(self.user) db.session.commit()
def acquire_snippet_scenario(_id): try: scenario_ids = Snippet.search_group({ '_id': ObjectId(_id) }).get('scenarios') result = [] if scenario_ids: for __id in scenario_ids: snippet = Snippet.search_scenario({'_id': ObjectId(__id)}) result.append( {__id: [snippet.get('name'), snippet.get('code')]}) result = sorted(result, key=lambda item: next(iter(item.values()))[0].lower()) return json.dumps({'scenario': result}), 200 except: return json.dumps({'scenario': []}), 500
def test_get_all(self): found = Snippet.get_all(user_id=self.user.id).all() self.assertSetEqual( {snippet.text for snippet in self.snippets}, {snippet.text for snippet in found}, )
def test_get_all_tag(self): tag = self.tag.text found = Snippet.get_all(user_id=self.user.id, tag_text=tag).all() self.assertSetEqual( {self.snippets[0].text}, {snippet.text for snippet in found}, )
def test_update_week_existing(self): # write the week Snippet.update(self.user.id, 2017, 9, "foo", ["blue", "red"]) self.assertIsNotNone(Snippet.get_by_week(self.user.id, 2017, 9)) # use api to update the week json = {"text": "bar", "tags": ["green"]} resp = self.post("/api/weeks/2017/9", self.valid_api_headers(), json) self.assertEqual(200, resp.status_code) # ensure current week is updated properly updated = Snippet.get_by_week(self.user.id, 2017, 9) self.assertIsNotNone(updated) self.assertEqual("bar", updated.text) self.assertSetEqual({"green"}, {tag.text for tag in updated.tags}) self.assertEqual(2017, updated.year) self.assertEqual(9, updated.week)
def test_update_week_new(self): # verify the week hasn't been written yet self.assertIsNone(Snippet.get_by_week(self.user.id, 2017, 9)) # use api to update the week json = {"text": "foo", "tags": ["blue", "red"]} resp = self.post("/api/weeks/2017/9", self.valid_api_headers(), json) self.assertEqual(200, resp.status_code) # check that the week was updated properly snippet = Snippet.get_by_week(self.user.id, 2017, 9) self.assertIsNotNone(snippet) self.assertEqual("foo", snippet.text) self.assertSetEqual({"blue", "red"}, {tag.text for tag in snippet.tags}) self.assertEqual(2017, snippet.year) self.assertEqual(9, snippet.week)
def acquire_snippet_group(): result = [] try: groups = Snippet.get_group_cursor({}, [('name', 1)]) for group_dict in groups: result.append({str(group_dict.get('_id')): group_dict.get('name')}) return json.dumps({'group': result}), 200 except: return json.dumps({'group': []}), 500
def add_snippet(): form = EditSnippetForm() if form.validate_on_submit(): snippet = Snippet(snippetname=form.snippetname.data, snippet=form.snippet.data, use_count=0) db.session.add(snippet) db.session.commit() flash('Snippet added') return redirect(url_for('index')) return render_template('snippet.html', title='Add Snippet', form=form)
def __init__(self, current_page: int, per_page: int = 15): super().__init__(current_page, per_page=per_page) self.snippets = Snippet.get_scenario_cursor({}, [('name', 1)]) self.total_count = self.snippets.count() self.current_num = self.total_count - (self.per_page * (self.current_page - 1)) if self.current_num > self.per_page: self.current_num = self.per_page self.items = [ self.snippets[self.prev_num * self.per_page + i] for i in range(self.current_num) ]
def test_get_all_empty(self): user = User( name="bob", email="*****@*****.**", confirmed=True, member_since=datetime.date.today(), password="******", ) db.session.add(user) db.session.commit() self.assertIsNotNone(User.query.get(user.id)) self.assertListEqual([], Snippet.get_all(user_id=user.id).all())
def test_get_weeks_pagination(self): self.app.config["LASTWEEK_SNIPPETS_PER_PAGE"] = 2 Snippet.update(self.user.id, 2017, 9, "foo", ["blue", "red"]) Snippet.update(self.user.id, 2011, 18, "bar", ["green"]) Snippet.update(self.user.id, 2007, 29, "baz", []) year_week = lambda snippet: (snippet["year"], snippet["week"]) year_weeks = lambda weeks: {year_week(snippet) for snippet in weeks} # first page resp = self.get("/api/weeks/", self.valid_api_headers()) self.assertEqual(3, resp.json["count"]) self.assertIsNone(resp.json["prev_url"]) self.assertIsNotNone(resp.json["next_url"]) self.assertSetEqual({(2017, 9), (2011, 18)}, year_weeks(resp.json["weeks"])) # use link to go to the second page resp = self.get(resp.json["next_url"], self.valid_api_headers()) self.assertEqual(3, resp.json["count"]) self.assertIsNotNone(resp.json["prev_url"]) self.assertIsNone(resp.json["next_url"]) self.assertSetEqual({(2007, 29)}, year_weeks(resp.json["weeks"])) # use link to go back to the first page resp = self.get(resp.json["prev_url"], self.valid_api_headers()) self.assertEqual(3, resp.json["count"]) self.assertIsNone(resp.json["prev_url"]) self.assertIsNotNone(resp.json["next_url"]) self.assertSetEqual({(2017, 9), (2011, 18)}, year_weeks(resp.json["weeks"]))
def history() -> Union[Response, Text]: page = request.args.get("page", 1, type=int) md = markdown.Markdown() snippets = Snippet.get_all(current_user.id, request.args.get("tag")) pagination = snippets.paginate( page, per_page=current_app.config["LASTWEEK_SNIPPETS_PER_PAGE"], error_out=True, ) snippets = [render_snippet(md, s) for s in pagination.items] return render_template( "history.html.j2", snippets=snippets, pagination=pagination )
def test_from_json_existing(self): snippet = self.snippets[1] self.assertNotIn("the end", snippet.text) self.assertNotIn(self.tag.text, {tag.text for tag in snippet.tags}) json = { "year": snippet.year, "week": snippet.week, "text": snippet.text + ", the end", "tags": [self.tag.text], } deserialized = Snippet.load_from_json(self.user.id, json) self.assertIn("the end", snippet.text) self.assertIn(self.tag.text, {tag.text for tag in snippet.tags})
def fork_snippet(snippet_uuid): to_fork = get_snippet_by_uuid(snippet_uuid) if to_fork.is_private() and to_fork.user != current_user: raise Unauthorized("This snippet is private.") new_snippet = Snippet(to_fork.body) new_snippet.title = to_fork.title new_snippet.language = to_fork.language new_snippet.parent_fork = to_fork new_snippet.user = current_user db.session.add(new_snippet) db.session.commit() return redirect( url_for('snippets.show_snippet', snippet_uuid=new_snippet.get_uuid()))
def test_from_json_new(self): date = iso_week_begin(datetime.date(44, 3, 15)) (yr, wk, _) = date.isocalendar() json = { "year": yr, "week": wk, "text": "beware", "tags": ["senate", "prophecy"], } deserialized = Snippet.load_from_json(self.user.id, json) self.assertEqual("beware", deserialized.text) self.assertEqual(yr, deserialized.year) self.assertEqual(wk, deserialized.week) self.assertSetEqual( {"senate", "prophecy"}, {tag.text for tag in deserialized.tags}, )
def render_snippet_form( form: SnippetsForm, user: User, year: int, week: int ) -> Text: snippet = Snippet.get_by_week(user.id, year, week) text = snippet and snippet.text form.text.data = text form.year.data = year form.week.data = week tags = snippet and sorted(tag.text for tag in snippet.tags) or [] form.tags.data = ", ".join(tags) return render_template( "edit.html.j2", name=user.name, user_id=user.id, week_begin=date.fromisocalendar(year, week, 1), content=text and markdown.markdown(text), form=form, tags=tags, )
def create_snippet(): if request.form: snippet_code = request.form.get('code') snippet_group = request.form.get('group') snippet_scenario = request.form.get('scenario') group_id, scenario_id = Snippet(snippet_group, snippet_scenario, snippet_code).new() if group_id and scenario_id: flash('New code snippet has been created successfully.', category='success') return redirect( url_for('main.edit_snippet', group=snippet_group, scenario=snippet_scenario)) else: flash( 'Naming conflict, please change Group name or Scenario name.', category='danger') return render_template('main/create_snippet.html', snippet_code=snippet_code) return render_template('main/create_snippet.html', snippet_code='')
def delete_snippet(): snippet_group = request.form.get('group') snippet_scenario = request.form.get('scenario') if not snippet_group or not snippet_scenario: abort(404) scenario_id_list = Snippet.search_group({ 'name': snippet_group }).get('scenarios') for _id in scenario_id_list: if Snippet.search_scenario({ '_id': ObjectId(_id) }).get('name') == snippet_scenario: Snippet.delete_doc_scenario({'_id': ObjectId(_id)}) if len(scenario_id_list) == 1: Snippet.delete_doc_group({'name': snippet_group}) else: scenario_id_list.remove(_id) Snippet.update_doc_group({'name': snippet_group}, {'scenarios': scenario_id_list}) break flash('Code Snippet has been deleted successfully.', category='info') return redirect(url_for('main.index'))
def index(): """Route allows users to create a new snippet""" snippet_form = SnippetForm() populate_choice_field(snippet_form) if snippet_form.validate_on_submit(): s = Snippet(snippet_form.snippet.data) if snippet_form.title.data: s.title = snippet_form.title.data s.language = Language.query.get(snippet_form.language.data) if not current_user.is_anonymous(): s.user = current_user s.private = snippet_form.private.data db.session.add(s) db.session.commit() return redirect( url_for('snippets.show_snippet', snippet_uuid=s.get_uuid())) if current_user.is_authenticated() and current_user.default_language: snippet_form.language.default = current_user.default_language_id snippet_form.process() return render_template('snippets/compose.html', form=snippet_form)
def get(self, request): s = Snippet(text='', user=request.user) s.save() return redirect('/snippet/' + str(s.pk))