def test_home_page_with_friends(self): """ Creates ten users, user 1 follows five of them, each user uploads a file, result from hitting /friends will return five files. When we go to friends for first time, bookmark will be set. If done multiple times, still will only have one bookmark if no files have been uploaded between visits. """ for x in range(10): user = User(name='test%s' % (x), email='*****@*****.**' % (x), email_confirmed=1) user.save() sf = test.factories.sharedfile(user) sf.add_to_shake(user.shake()) if (x % 2) == 0: self.admin.subscribe(user.shake()) ssf = Shakesharedfile.all() self.assertEqual(len(ssf), 10) self.assertEqual(len(self.admin.sharedfiles_from_subscriptions()), 5) response = self.fetch_url('/friends') self.assertEqual(response.code, 200) self.assertEqual(1, len(Bookmark.all())) response = self.fetch_url('/friends') self.assertEqual(response.code, 200) self.assertEqual(1, len(Bookmark.all()))
def delete_bookmark_handler(book_info, bookmark_info, session_storage, res): try: # If all data is correct if book_info['book_name'] and book_info[ 'book_author'] and bookmark_info['bookmark_page']: book = Book.query.filter_by( title=book_info['book_name'], author=book_info['book_author']).first() # If book in any list if book: # If book in now reading list if book.status == 1: bookmark = Bookmark.query.filter_by( book_id=book.id, page=bookmark_info['bookmark_page']).first() Bookmark.delete(bookmark) res['response'][ 'text'] = 'Bookmark has been deleted!' + '\n\n\nWhat else I can do for you, {}?'.format( session_storage['username']) # If book not in now reading list else: res['response'][ 'text'] = 'Chosen book should be in \"Reading now\" list!' # If book not found in any of lists else: res['response']['text'] = 'No such book found!' except Exception as e: print(e)
def bookmark_add(): error = {} bookmark = {} user = auth.get_logged_in_user() if request.method == 'POST': if not request.form['url']: error['url'] = u'书签的网址不能为空' if not request.form['url'].startswith('http://') and not request.form['url'].startswith('https://'): request.form['url'] = ''.join(['http://', request.form['url']]) if not error: try: bookmark = Bookmark.select().where(Bookmark.user == user, Bookmark.url == request.form['url'] ).get() except Bookmark.DoesNotExist: try: db.database.set_autocommit(False) bookmark = Bookmark.create( user=user, url=request.form['url'], title=request.form['title'] ) bookmark.fetch_image() bookmark.save() tagnames = re.split('\s+', request.form['tags'].strip()) # marksure request.form['tags'] not a empty string if tagnames[0]: for tagname in tagnames: if not Tag.select().where(Tag.user == user, Tag.name == tagname ).exists(): tag = Tag.create(user=user, name=tagname) tag.save() relationship = Relationship.create( user=user, tag=tag, bookmark=bookmark) relationship.save() except Exception as e: db.database.rollback() flash(u'对不起,服务器太累了,刚罢工了一会儿', 'error') else: try: db.database.commit() except Exception as e: db.database.rollback() flash(u'对不起,服务器太累了,刚罢工了一会儿', 'error') finally: db.database.set_autocommit(True) if not get_flashed_messages(): flash(u'你已经成功添加一个书签', 'success') return redirect(url_for('bookmark')) else: flash(Markup(u'书签已经存在,也许你想要<a href="' + url_for('bookmark_edit', id=bookmark.id) + u'">编辑</a>此书签'), 'info') return render_template('bookmark_add.html', error=error, form=request.form, user=user, bookmark=bookmark)
def test_home_page_non_user_request(self): """ Safari, Firefox and other browsers like to fetch pages to create preview images (i.e. Safari's Top Sites) feature. Or prefetch for speeding up future render times. When we can detect that the request is not user-intiated, we want to make sure we don't set any bookmarks for the user. When a browser bot accesses the home page, no bookmarks should be set. """ user = User(name='user2', email='*****@*****.**', email_confirmed=1) user.save() self.admin.subscribe(user.shake()) saved_files = [] for x in range(5): sf = test.factories.sharedfile(user) sf.add_to_shake(user.shake()) saved_files.append(sf) response = self.fetch_url('/friends', headers={"X-Purpose": "preview"}) self.assertEqual(response.code, 200) self.assertEqual(0, len(Bookmark.all())) response = self.fetch_url('/friends', headers={"X-Moz": "prefetch"}) self.assertEqual(response.code, 200) self.assertEqual(0, len(Bookmark.all())) response = self.fetch_url('/friends', ) self.assertEqual(response.code, 200) self.assertEqual(1, len(Bookmark.all()))
def bookmark(request,id): try: bookmark = Bookmark.objects.get(user=request.user,event_id=id) except Bookmark.DoesNotExist: bookmark = Bookmark(user=request.user,event_id=id) bookmark.save() return redirect(bookmark)
def bookmark(request, id): try: bookmark = Bookmark.objects.get(user=request.user, event_id=id) except Bookmark.DoesNotExist: bookmark = Bookmark(user=request.user, event_id=id) bookmark.save() return redirect(bookmark)
def save_bookmark(request, bookmark_id=False): if request.is_ajax: return ajax_save_bookmark(request, bookmark_id) form = BookmarkForm() bookmark = get_object_or_None(Bookmark, pk=bookmark_id) if bookmark: form = BookmarkForm(instance=bookmark) if not request.user.is_authenticated() or ( not request.user.is_staff and (bookmark.note.author == request.user)): return HttpResponseRedirect(reverse(list, args=(note.id, ))) if request.method == "POST": if bookmark: form = BookmarkForm(request.POST, instance=bookmark) else: form = BookmarkForm(request.POST) if form.is_valid(): if not bookmark: bookmark = Bookmark() bookmark.save() if 'text' in form.cleaned_data: bookmark.text = form.cleaned_data['text'] if 'chart' in form.cleaned_data: bookmark.chart = form.cleaned_data['chart'] if 'tags' in form.cleaned_data: bookmark.tags = form.cleaned_data['tags'] if 'note' in form.cleaned_data: bookmark.note = form.cleaned_data['note'] bookmark.save() return HttpResponseRedirect( reverse(save_bookmark, kwargs={ "bookmark_id": bookmark.id, })) return render_to_response('notes/form_page.html', {'form': form}, context_instance=RequestContext(request))
def add(user=None): if 'url' not in request.form: return jsonify(errors=['Dude, what\'s wrong with you ?', 'You are missing Bookmark Url']), 400 if not is_url_valid(request.form['url']): return jsonify(errors=['Dude, what\'s wrong with you ?', 'Invalid Bookmark Url']), 400 bookmark = Bookmark(url=request.form['url'], user=user) if bookmark.save(): return jsonify(bookmark=bookmark.to_dict()), 200 return jsonify(errors=[bookmark.to_dict()]), 400
def test_addition_of_results_to_folder(self): f1 = create_folder(self.ie,'test') r1 = Result(title='r1',url='www.love.com',summary="Gambo Gambo") b1 = Bookmark(folder=f1,title=r1.title, url=r1.url, summary=r1.summary) b1.save() b2 = add_result_to_folder(f1.id, r1) self.assertEquals(b1,b2)
def upload(request, usrid): if request.method == "POST": this = AudioMeta() try: this.name = request.POST['title'] except: this.name = "NONE" try: this.user_id = User.objects.get(id=usrid) except: try: this.user_id = User.objects.get(id=1) except: pass this.annotations = 0 this.transcriptions = 0 this.plays = 0 this.likes = 0 if request.FILES: this.bytes = request.FILES['file'].size a = open("/home/leegao/webapps/notetag/notetag/audio/a.txt", "w") a.write(str(request.FILES)) a.close() try: this.type = extension_re.search( request.FILES['file'].name).group(1).lower() except: this.type = "wav" this.save() try: marks = request.POST['marks'] for secs in [int(i.strip()) for i in marks.split(",") if i]: m = Bookmark(aud_id=this, time=secs) m.save() except: pass handle_uploaded_file(request.FILES['file'], this.id, this.type) else: return HttpResponseForbidden() return HttpResponse(content="1") else: form = UploadFileForm() return render_to_response('upload.html', { 'form': form, 'usrid': usrid })
def post(self): g = self.request.get l = self.get_link(g('link')) b = Bookmark( user = users.get_current_user(), title = g('title'), link = l, tags = [db.Category(t) for t in g('tags').split()], #tags whitespace separated access = g('access')) b.put() logging.info("new bookmark created - %s" % b)
def add(user=None): if 'url' not in request.form: return jsonify(errors=[ 'Dude, what\'s wrong with you ?', 'You are missing Bookmark Url' ]), 400 if not is_url_valid(request.form['url']): return jsonify( errors=['Dude, what\'s wrong with you ?', 'Invalid Bookmark Url' ]), 400 bookmark = Bookmark(url=request.form['url'], user=user) if bookmark.save(): return jsonify(bookmark=bookmark.to_dict()), 200 return jsonify(errors=[bookmark.to_dict()]), 400
def upload(request, usrid): if request.method == "POST": this = AudioMeta() try: this.name = request.POST["title"] except: this.name = "NONE" try: this.user_id = User.objects.get(id=usrid) except: try: this.user_id = User.objects.get(id=1) except: pass this.annotations = 0 this.transcriptions = 0 this.plays = 0 this.likes = 0 if request.FILES: this.bytes = request.FILES["file"].size a = open("/home/leegao/webapps/notetag/notetag/audio/a.txt", "w") a.write(str(request.FILES)) a.close() try: this.type = extension_re.search(request.FILES["file"].name).group(1).lower() except: this.type = "wav" this.save() try: marks = request.POST["marks"] for secs in [int(i.strip()) for i in marks.split(",") if i]: m = Bookmark(aud_id=this, time=secs) m.save() except: pass handle_uploaded_file(request.FILES["file"], this.id, this.type) else: return HttpResponseForbidden() return HttpResponse(content="1") else: form = UploadFileForm() return render_to_response("upload.html", {"form": form, "usrid": usrid})
def senator(request, representative_id=None): """senator page""" to_response = {} to_response['senator'] = get_object_or_404(Representative.objects.select_related(), pk=representative_id) try: bookmark = Bookmark.objects.get( user=request.user, content_type=ContentType.objects.get_for_model(Representative), object_id=to_response['senator'].id, ) to_response['bookmark'] = bookmark except Exception, e: bookmark = Bookmark() bookmark.content_object = to_response['senator']
def bill(request, bill_id=None): """bill page""" to_response = {} to_response['bill'] = get_object_or_404(Bill.objects.select_related(), pk=bill_id) try: bookmark = Bookmark.objects.get( user=request.user, content_type=ContentType.objects.get_for_model(Bill), object_id=to_response['bill'].id, ) to_response['bookmark'] = bookmark except Exception, e: bookmark = Bookmark() bookmark.content_object = to_response['bill']
def POST(self): form = bookmark_form() if not form.validates(): content = 'Validation error' return render.add_bookmark(content, form) else: i = web.input() #db = web.database(dbn='sqlite', db='bookmarks_webpy.sqlite') bookmark = Bookmark(db) bookmark.url = i.url bookmark.description = i.description bookmark.author = session.user_id result = bookmark.save() content = 'bookmark added' return render.add_bookmark_success(content, result)
def ajax_save_bookmark(request, bookmark_id=False): bookmark = get_object_or_None(Bookmark, pk=bookmark_id) if request.method == "POST": if 'chart_id' not in request.POST or 'tags' not in request.POST: return HttpResponse( json.dumps({ "message": { 'type': 'error', 'text': "Can't save bookmark", }, }), 'application/json') if not bookmark: bookmark = Bookmark() bookmark.save() if 'chart_id' in request.POST: chart = get_object_or_None(Chart, pk=request.POST['chart_id']) if chart: bookmark.chart = chart if 'tags' in request.POST: for short in request.POST['tags'].split(','): tag = get_object_or_None(Tag, short=short) if tag: bookmark.tags.add(tag) if 'note_id' in request.POST: note = get_object_or_None(Note, pk=request.POST['note_id']) if note: bookmark.note = note else: bookmark.note = False bookmark.save() _bookmark = bookmark.as_json() _bookmark['url'] = 'http://' + request.get_host() + reverse( save_bookmark, args=(bookmark.id, )) return HttpResponse( json.dumps({ "message": { 'type': 'success', 'text': "Bookmark saved", }, "bookmarks": [_bookmark], }), 'application/json') return HttpResponse( json.dumps({ "message": { 'type': 'error', 'text': "Use post", }, }), 'application/json')
def bookmark(user=None): bookmark = Bookmark.objects(id=bookmark_id, user=user).first() if bookmark: if bookmark.updated_at is None: bookmark.fetch() return jsonify(bookmark=bookmark.to_dict()), 200 return jsonify(errors=['Not Found']), 404
def update(user=None, bookmark_id=None): bookmark = Bookmark.objects(id=bookmark_id, user=user).first() if bookmark and bookmark.fetch(): if bookmark.save(): return jsonify(bookmark=bookmark.to_dict()) return jsonify(bookmark=bookmark.to_dict()), 304 return jsonify(errors=['Not Found']), 404
def add(): form = BookmarkForm() if form.validate_on_submit(): url = form.url.data description = form.description.data destination = form.destination.data outbound_date = form.outbound_date.data outbound_time = form.outbound_time.data inbound_date = form.inbound_date.data inbound_time = form.inbound_time.data tags = form.tags.data bm = Bookmark(user=current_user, url=url, description=description, destination=destination, tags=tags, outbound_date=outbound_date, outbound_time=outbound_time, inbound_date=inbound_date, inbound_time=inbound_time) db.session.add(bm) db.session.commit() flash("Stored trip '{}'".format(description)) return redirect(url_for('index')) return render_template('bookmark_form.html', form=form, title="Add a Trip")
def bookmarks(): form_add = AddBookmarkForm() form_remove = RemoveBookmarkForm() action = request.form.get('submit', '').lower() if action == 'add': if form_add.validate_on_submit(): bookmark = Bookmark(current_user, form_add.bookmark.data) db.session.add(bookmark) db.session.commit() flash('Saved.', 'success') return redirect(url_for('bookmarks')) elif action == 'remove': if form_remove.validate_on_submit(): for email in form_remove.bookmarks.data: bookmark = current_user.bookmarks.filter_by( email=email).first() db.session.delete(bookmark) db.session.commit() flash('Removed.', 'success') return redirect(url_for('bookmarks')) return render_template('bookmarks.html', form_add=form_add, form_remove=form_remove)
def get_bookmarks_from_api_response_items(items: List[Dict]) -> List[Bookmark]: ''' Get bookmark model from API response dict ''' bookmarks: List[Bookmark] = [] for item in items: items_tags: List[Tag] = [] bookmark_tag_mappings: List[BookmarkTagMapping] = [] for item_tag_str in item['tags']: bookmark_tag_mappings.append( BookmarkTagMapping(item['_id'], item_tag_str)) items_tags.append(Tag(item_tag_str)) bookmarks.append( Bookmark( _id=item['_id'], created_at=item['created'], updated_at=item['lastUpdate'], link=item['link'], title=item['title'], tags=items_tags, mappings=bookmark_tag_mappings) ) return bookmarks
def get_bookmarks(self): def add_childs(bkmkt): for bookmark, childs in bkmkt: if bookmark.key() in bookmark_dict: for bkm in sorted(bookmark_dict[bookmark.key()], key=lambda b: b.date): childs.append((bkm, [])) add_childs(childs) bookmark_list = [] if users.get_current_user(): bookmark_list += Bookmark.gql("WHERE author = :1", users.get_current_user()) bookmark_dict = {} bookmark_tree = [] for bookmark in bookmark_list: key = None if bookmark.reference: key = bookmark.reference.key() if key in bookmark_dict: bmks = bookmark_dict[key] else: bmks = [] bookmark_dict[key] = bmks bmks.append(bookmark) if bookmark_dict.get(None): for bkm in sorted(bookmark_dict[None], key=lambda b: b.date): bookmark_tree.append((bkm, [])) add_childs(bookmark_tree) return bookmark_tree
def create(self, parent_id=None): if not users.get_current_user(): webapp2.abort(401) form = BookmarkForm(self.get_locale(), self.request.POST, None) if self.request.POST and form.validate(): parent = None if form.reference_id.data: parent = db.get(db.Key.from_path('Bookmark', int(form.reference_id.data))) bookmark = Bookmark(author=users.get_current_user(), reference=parent, title=form.title.data, url=form.url.data) bookmark.date = datetime.now() bookmark.put() return self.redirect('/bookmark/list') else: if parent_id: form.reference_id.data = parent_id self.render_template('form.html', {'title': _('Bookmark'), 'form': form, 'name': 'bookmark'})
def extra_context(self, *args, **kwargs): """return the context for the search view""" context = super(TWFASearchView, self).extra_context(*args, **kwargs) saved_search, created = SavedSearch.objects.get_or_create( hashed_search=SavedSearch.create_hash(self.query), search=self.query, ) try: bookmark = Bookmark.objects.get( user=self.request.user, content_type=ContentType.objects.get_for_model(SavedSearch), object_id=saved_search.id, ) context['bookmark'] = bookmark except Exception, e: bookmark = Bookmark() bookmark.content_object = saved_search
def save_bookmark_to_note(request, note): saved_bookmarks = 0 if request.method == 'POST': if 'bookmarks' in request.POST: for bookmark_id in request.POST['bookmarks'].split(","): if bookmark_id != '': bookmark = get_object_or_None(Bookmark, pk=bookmark_id) if bookmark: bookmark.note = note bookmark.save() chart = False tags = [] if 'chart_id' in request.POST: chart = get_object_or_None(Chart, pk=request.POST['chart_id']) if 'tags' in request.POST: for short in request.POST['tags'].split(','): if short != '': tag = get_object_or_None(Tag, short=short) if tag: tags.append(tag) if chart: bookmark = Bookmark() bookmark.chart = chart bookmark.note = note bookmark.save() bookmark.tags = tags return saved_bookmarks
def test_home_page_no_sharedfiles(self): """ Accessing friend page with no files - Should not error. - No bookmarks should be created. - Introduction to mltshp should show. """ response = self.fetch_url('/friends') self.assertEqual(200, response.code) self.assertEqual(0, len(Bookmark.all()))
def add(): form = BookmarkForm() if form.validate_on_submit(): url = request.form['url'] bm = Bookmark(user=current_user, url=url) db.session.add(bm) db.session.commit() application.logger.debug('URL:' + url) flash("Stored url: {}".format(url)) return redirect(url_for('return_200')) return render_template('add.html', form=form)
def add(): form = BookmarkForm() if form.validate_on_submit(): url = form.url.data description = form.description.data b = Bookmark(url=url, description=description) db.session.add(b) db.session.commit() flash("Stored '{}'".format(description)) return redirect(url_for('index')) return render_template('add.html', form=form)
def add(): form = BookmarkForm() if form.validate_on_submit(): db.session.add( Bookmark(user=logged_in_user(), url=form.obj.data, description=form.description.data)) db.session.commit() flash("Stored description {}".format(form.description.data)) return redirect(url_for('index')) return render_template('add.html', form=form)
def add(): form = BookmarkForm() if form.validate_on_submit(): url = form.url.data description = form.description.data bm = Bookmark(user=logged_in_user(), url=url, description=description) db.session.add(bm) db.session.commit() flash("Stored bookmak '{}'.".format(description)) return redirect(url_for("index")) return render_template("add.html", form=form)
def index(): user = auth.get_logged_in_user() if user: return redirect(url_for('bookmark')) else: # random pick 30 bookmarks, If Database is MySQL, please use fn.Rand() # fn come from, from peewee import * bookmarks = Bookmark.select().order_by(fn.Random()).limit(PERPAGE) return object_list('bookmark_list.html', bookmarks, 'bookmarks', paginate_by=PERPAGE)
def add_bookmark(): form = BookmarkForm() # checks http request and form if form.validate_on_submit(): url = form.url.data description = form.description.data bm = Bookmark(url=url, description=description) db.session.add(bm) db.session.commit() flash(f"stored bookmark: {url}") return redirect(url_for('index')) return render_template('add.html', form=form)
def upload(request, usrid): if request.method == "POST": this = AudioMeta() this.name = request.POST['title'] #try: this.user_id = User.objects.get(id=usrid) #except: #return HttpResponseForbidden() this.annotations = 0 this.transcriptions = 0 this.plays = 0 this.likes = 0 if request.FILES: this.bytes = request.FILES['file'].size try: this.type = extension_re.search( request.FILES['file'].name).group(1).lower() except: this.type = "wav" this.save() try: marks = request.POST['marks'] for secs in [int(i.strip()) for i in marks.split(",")]: m = Bookmark(aud_id=this, time=secs) m.save() except: pass handle_uploaded_file(request.FILES['file'], this.id, this.type) else: return HttpResponseForbidden() return HttpResponseRedirect('/') else: form = UploadFileForm() return render_to_response('upload.html', { 'form': form, 'usrid': usrid })
def get(self): g = self.request.get q = Bookmark.all() if g('key'): b = Bookmark.get(g('key')) if b: if self.has_permission_for(b): self.json_output([b,]) return else: self.do_error('forbidden') else: self.do_error('not-found') if g('tag'): q = q.filter('tags=', g('tag')) if g('tags'): #union comma sep q = q.filter('tags IN', g('tags').split(',')) if g('all_tags'): for t in g('all_tags').split(','): q = q.filter('tags=', t) if g('link'): l = Link.all().filter('url=', g('link')).get() if l: q = q.filter('link=', l) if g('title'): q = q.filter('title=', g('title')) if g('access'): q = q.filter('access=', g('access')) if g('user'): q = q.filter('user='******'-created') try: limit = int(g('limit')) except: limit = 10 results = [r for r in q.fetch(limit) if self.can_view(r)] self.json_output(results)
def post(self): user = users.get_current_user() url = self.request.get('url_text') tags = self.request.get('url_tag').split(",") usable_tags = [] for tag_name in tags: if len(tag_name) is 0: continue tag = Tag(name = tag_name) tags_query = Tag.all() tags_query.filter('name =', tag_name) if len(tags_query.fetch(1)) is not 0: continue tag.put() usable_tags.append(tag.key()) book_mark = Bookmark(user = user, url = url, tags = usable_tags) book_mark.put() json_data = simplejson.dumps({'result':True, 'link': url, 'tags': tags}) self.response.out.write(json_data)
def add(): form = BookmarkForm() if form.validate_on_submit(): url = form.url.data description = form.description.data bm = Bookmark(url=url, description=description, user=current_user) db.session.add(bm) db.session.commit() flash('Stored bookmark: {}'.format(url)) return redirect(url_for('index')) return render_template('bookmark_form.html', form=form, title='Add Bookmark')
def add(): form = BookmarkForm() if form.validate_on_submit(): url = form.url.data description = form.description.data bm = Bookmark(url=url, description=description, user=current_user) db.session.add(bm) db.session.commit() app.logger.debug('stored url ' + url) flash("Stored '{0}'".format(description)) return redirect(url_for('index')) return render_template('bookmark_form.html', form=form, title='Add new bookmark')
def parse_bookmarks(dl, parent): if not dl: return dts = dl.find_all('dt', recursive=False) for dt in dts: title = None url = None description = None if dt.h3: if dt.h3.string: title = dt.h3.string.strip() else: if dt.a: if dt.a.string: title = dt.a.string.strip() url = dt.a['href'] #dd = dt.findNextSibling() #if dd and dd.name == 'dd' and dd.string: # description = dd.string.strip() bookmark = Bookmark(author=users.get_current_user(), date=datetime.now(), reference=parent, title=title, url=url, description=description) bookmark.put() if dt.dl: parse_bookmarks(dt.dl, bookmark)
def add(): form = BookmarkForm() if form.validate_on_submit(): url = form.url.data description = form.description.data tags = form.tags.data bm = Bookmark(user=current_user, url=url, description=description, tags=tags) db.session.add(bm) db.session.commit() #store_bookmark(url, description) #app.logger.debug('stored url: ' + url) flash("Stored '{}'".format(description)) return redirect(url_for('index')) return render_template('add.html', form=form)
def add(): form = BookmarkForm() if form.validate_on_submit(): url = form.url.data description = form.description.data bm = Bookmark(user=current_user, url=url, description=description) db.session.add(bm) db.session.commit() # app.logger.debug("Stored url: " + url) flash("Stored bookmark '{}'".format(description)) return redirect(url_for("index")) return render_template("add.html", form=form)
def put(self): g = self.request.get b = Bookmark.get(g('key')) if b is None: self.post() else: if b.user == users.get_current_user(): if g('title'): b.title = g('title') if g('link'): b.link = self.get_link(g('link')) if g('tags'): b.tags = [db.Category(t) for t in g('tags').split()] if g('access'): b.access = g('access') b.put() else: self.do_error('forbidden')
def upload(request, usrid): if request.method == "POST": this = AudioMeta() this.name = request.POST['title'] #try: this.user_id = User.objects.get(id=usrid) #except: #return HttpResponseForbidden() this.annotations = 0 this.transcriptions = 0 this.plays = 0 this.likes = 0 if request.FILES: this.bytes = request.FILES['file'].size try: this.type = extension_re.search(request.FILES['file'].name).group(1).lower() except: this.type = "wav" this.save() try: marks = request.POST['marks'] for secs in [int(i.strip()) for i in marks.split(",")]: m = Bookmark(aud_id = this, time = secs) m.save() except: pass handle_uploaded_file(request.FILES['file'], this.id, this.type) else: return HttpResponseForbidden() return HttpResponseRedirect('/') else: form = UploadFileForm() return render_to_response('upload.html', {'form': form, 'usrid':usrid})
def add(): form = BookmarkForm( ) # On a GET request, the fields are empty and the form variables are also empty. On a POST request, the variables are full. This will likely only work because the action was "", as that means it referring to a still available form to read the values of if form.validate_on_submit( ): # This line also checks to make sure the method is not GET url = form.url.data description = form.description.data bm = Bookmark(user=current_user, url=url, description=description) db.session.add(bm) db.session.commit() flash("Stored '{}'".format(bm.description)) return redirect(url_for('index')) return render_template( 'bookmark_form.html', form=form, title="Add a bookmark" ) # form=form is sent because the template is actually using the form to populate the DOM with form fields
def add(): form = BookmarkForm() if form.validate_on_submit(): url = form.url.data description = form.description.data with open('test.txt', 'w') as f: f.write(url) f.write(description) bm = Bookmark(user=current_user, url=url, description=description) db.session.add(bm) db.session.commit() app.logger.debug('stored url: {} {}'.format(url, description)) flash("Stored '{}'".format(description)) return redirect(url_for('index')) return render_template('add.html', form=form)
def add(): form = BookmarkForm() if form.validate_on_submit(): url = form.url.data description = form.description.data tags = form.tags.data bm = Bookmark(user=current_user, url=url, description=description, tags=tags) db.session.add(bm) db.session.commit() flash("Bookmark Successfully Added") return redirect(url_for('index')) return render_template('add.html', form=form)
def savebookmark(TitleF,UrlF,DescriptionF,TagF,PrivateF,UserF): TitleF = unicode(TitleF) UrlF = unicode(UrlF) DescriptionF = unicode(DescriptionF) Tagf = unicode(TagF) try : UrlB = Url.objects.get(url=UrlF) except : UrlB = Url(url=UrlF) UrlB.save() try : TitleB = Title.objects.get(title=TitleF) except : TitleB = Title(title=TitleF) TitleB.save(); try : DescriptionB = Description.objects.get(description=DescriptionF) except : DescriptionB = Description(description=DescriptionF) DescriptionB.save() try : PrivateB = Private.objects.get(private= (PrivateF == 'True')) except : PrivateB = Private(private= (PrivateF == 'True')) PrivateB.save() try : b2 = Bookmark.objects.get(url=UrlB) b2.title=TitleB b2.description=DescriptionB b2.private=PrivateB except : b2 = Bookmark(title=TitleB,url=UrlB,description=DescriptionB,private=PrivateB) b2.save() b2.user.add(UserF) b2.save() tags = TagF.split(" ") tags.sort() for t in tags : try : TagB = Tag.objects.get(tag=t) except : TagB= Tag(tag=t) TagB.save() TagB.user.add(UserF) TagB.save() b2.tag.add(TagB) b2.save()
def bookmark_remove(id): user = auth.get_logged_in_user() bookmark = {} try: bookmark = Bookmark.get(Bookmark.id == id) except Bookmark.DoesNotExist: flash(u'你要删除的书签不存在', 'error') return redirect(url_for('page_404')) if request.method == 'POST': with db.database.transaction(): bookmark.destory_image() bookmark.delete_instance(recursive=True) flash(u'你刚刚删除了一个书签', 'success') return redirect(url_for('bookmark')) return render_template('bookmark_remove.html', bookmark=bookmark, user=user)
def add(): form = BookmarkForm() if form.validate_on_submit(): url = form.url.data description = form.description.data tags = form.tags.data bm = Bookmark(user=current_user, url=url, description=description, tags=tags) db.session.add(bm) db.session.commit() flash("Stored '{}'".format(bm.description)) return redirect(url_for('index')) return render_template('bookmark_form.html', form=form, title="Add a bookmark")
def get(self): user = users.get_current_user() if user is None: self.redirect(users.create_login_url(self.request.uri)) logout_url = users.create_logout_url(self.request.uri) username = user.nickname() if user is not None else "" urls_query = Bookmark.all() last_cursor = memcache.get('bookmark_cursor') if last_cursor: urls_query.with_cursor(last_cursor) urls_query.filter('user ='******'bookmark_cursor', urls_query.cursor()) logging.error(urls) template_values = {'user_name': username, 'logout_url': logout_url, 'urls': urls} path = os.path.join(os.path.dirname(__file__), 'templates/index.html') self.response.out.write(template.render(path, template_values))
def create_bookmark(request): form = BookmarkForm() if request.method == 'GET' and request.GET: form = BookmarkForm(initial=request.GET) elif request.method == 'POST': form = BookmarkForm(request.POST) if form.is_valid(): data = form.cleaned_data labels = str_to_labels(data.pop('labels')) bookmark = Bookmark(**data) bookmark.author = request.user bookmark.save() bookmark.labels = labels bookmark.save() return HttpResponseRedirect(reverse("bookmarks.views.bookmark_list", args=[])) return render_to_response('bookmarks/bookmark_form.html', {'form': form, 'labels': Label.objects.all()}, context_instance=RequestContext(request))
def new_bookmark(): form = BookmarkForm() if form.validate_on_submit(): b = Bookmark() form.populate_obj(b) b.owner_id = g.user.id b.created = datetime.utcnow() b.tags = ' '.join( [t.strip() for t in form.tags.data.strip().split(',')])\ .lower() b.clicks = 0 if not form.title.data: soup = BSoup(urlopen(form.url.data)) b.title = soup.title.string db.session.add(b) db.session.commit() flash('New bookmark %s added' % (b.title), category='info') return redirect(url_for('index')) return render_template('new.html', title='New', form=form)
def new_bookmark(): form = BookmarkForm() if form.validate_on_submit(): b = Bookmark() form.populate_obj(b) b.owner_id = g.user.id b.created = datetime.utcnow() b.tags = " ".join([t.strip() for t in form.tags.data.strip().split(",")]).lower() b.clicks = 0 if not form.title.data: soup = BSoup(urlopen(form.url.data)) b.title = soup.title.string db.session.add(b) db.session.commit() flash("New bookmark %s added" % (b.title), category="info") return redirect(url_for("index")) return render_template("new.html", title="New", form=form)
def index(): return render_template('index.html', title="Title passed from view to template", new_bookmarks=Bookmark.newest(5))
def index(): return render_template("index.html", new_bookmarks=Bookmark.newest(5))
def test_read_bookmarks_from_file(self): with codecs.open(os.path.join(os.path.dirname(__file__), 'bookmarks.html'), 'r', 'utf-8') as f: html = f.read() soup = BeautifulSoup(html, "html5lib") parse_bookmarks(soup.dl, None) self.assertEqual(106, Bookmark.all().count(1000))
def testBookmark(self): Bookmark(author=self.current_user, title='Test 1').put() self.assertEqual(1, Bookmark.all().count(10)) Bookmark(author=self.current_user, title='Test 2').put() self.assertEqual(2, Bookmark.all().count(10)) bookmark = Bookmark(author=self.current_user, title='Test 3', description=u'Treść', url='jkpluta.appspot.com') bookmark.put() self.assertEqual(3, Bookmark.all().count(10)) Bookmark(author=self.current_user, reference=bookmark, title='Test 3A').put() self.assertEqual(4, Bookmark.all().count(10)) Bookmark(author=self.current_user, reference=bookmark, title='Test 3B').put() self.assertEqual(5, Bookmark.all().count(10)) Bookmark(author=self.current_user, reference=bookmark, title='Test 3C').put() self.assertEqual(6, Bookmark.all().count(10)) with self.assertRaises(datastore_errors.BadValueError): Bookmark().put() self.assertEqual(6, Bookmark.all().count(10)) db.delete(bookmark) self.assertEqual(5, Bookmark.all().count(10)) child_bookmark = Bookmark(author=self.current_user, reference=bookmark, title='Test X') child_bookmark.put() self.assertEqual(6, Bookmark.all().count(10)) test_bookmark = db.get(db.Key.from_path('Bookmark', int(child_bookmark.key().id()))) with self.assertRaises(datastore_errors.ReferencePropertyResolveError): test_bookmark.reference != None
def add_bookmark( user, obj ): bookmark = Bookmark( user=user, content_object=obj, public = get_setting(user, 'profile_public')) bookmark.save() return bookmark