def tag_handler(tag_id): if request.method == 'GET': tag = Tag.get(tag_id) if tag is not None: return jsonify(tag=[tag.serialize]) else: raise InvalidUsage('Not Found', status_code=404) if request.method == 'PUT': tag = Tag.get(tag_id) if tag is not None: name = request.args.get('name') description = request.args.get('description') updated_tag = tag.update(name, description) return jsonify(tag=[updated_tag.serialize]) else: raise InvalidUsage('Not Found', status_code=404) if request.method == 'DELETE': tag = Tag.get(tag_id) if tag is not None: deleted = tag.delete() if deleted: return jsonify(status='OK') else: raise InvalidUsage('Unknown Error', status_code=520) else: raise InvalidUsage('Not Found', status_code=404)
def post_update_post(id): postid = request.forms.get('postid') title = request.forms.get('title').decode('utf-8') slug = request.forms.get('slug').decode('utf-8') post = request.forms.get('post') tags = request.forms.get('tags').decode('utf-8') category = request.forms.get('category').decode('utf-8') post_type = request.forms.get('postype') if post_type == 'HTML': is_html = 1 content = post.decode('utf-8') markdown = u'html' else: is_html = 0 markdown = post.decode('utf-8') content = to_markdown(markdown) category = Category.get(name=category) Post.update(title=title, slug=slug, content=content, markdown=markdown, tags=tags, category=category, is_html=is_html).where(id=postid).execute() tag_list = set(tags.split(",")) for tag in tag_list: try: Tag.get(name=tag.strip(), post_id=postid) except Post.DoesNotExist: Tag.create(name=tag.strip(), post_id=postid) redirect("/%s" % slug)
def __init__(self, dorms=TWO_DORMS): self.scrape_uri = f'http://clasificados.eldia.com/clasificados-alquiler-departamentos-{dorms}-la-plata' tags = [{ ONE_DORM: Tag.get(tag=ONE_DORM), TWO_DORMS: Tag.get(tag=TWO_DORMS), THREE_DORMS: Tag.get(tag=THREE_DORMS), }[dorms]] self.grabbers = [ ConFotoGrabber(self.scrape_uri, tags), ClasifGrabber(self.scrape_uri, tags), ]
def edit(slug): entry = get_object_or_404(Entry, Entry.slug == slug) tags = "" for tag in entry.tags: tags = tags + " " + tag.tag if request.method == "POST": if request.form.get("title") and request.form.get("content"): try: entry.title = request.form["title"] entry.content = request.form["content"] entry.archived = request.form.get("archived") or False entry.lastedited = datetime.datetime.now() # convert the string of tags to a list tags = request.form["tags"].split() # present is a check to see if the tag exists present = 0 # add or create tags for tag in tags: for entrytag in entry.tags: if tag == entrytag.tag: present = 1 if present == 0: try: thistag = Tag.get(Tag.tag == tag) entry.tags.add(thistag) except: tag_obj, was_created = Tag.create_or_get(tag=tag) EntryTags.create(tag=tag_obj, entry=entry) present = 0 # remove tags for entrytag in entry.tags: for tag in tags: if entrytag.tag == tag: present = 1 if present == 0: thistag = Tag.get(Tag.tag == entrytag.tag) entry.tags.remove(thistag) present = 0 entry.save() flash("Note updated successfully.", "success") return redirect(url_for("detail", slug=entry.slug)) except: flash("Note title already exists", "danger") return render_template("create.html") else: flash("Title and Content are required.", "danger") return render_template("edit.html", entry=entry, tags=tags)
def edit(slug): entry = get_object_or_404(Entry, Entry.slug == slug) tags = "" for tag in entry.tags: tags = tags + " " + tag.tag if request.method == 'POST': if request.form.get('title') and request.form.get('content'): try: entry.title = request.form['title'] entry.content = request.form['content'] entry.archived = request.form.get('archived') or False entry.lastedited = datetime.datetime.now() # convert the string of tags to a list tags = request.form['tags'].split() # present is a check to see if the tag exists present = 0 # add or create tags for tag in tags: for entrytag in entry.tags: if tag == entrytag.tag: present = 1 if present == 0: try: thistag = Tag.get(Tag.tag == tag) entry.tags.add(thistag) except: tag_obj, was_created = Tag.create_or_get(tag=tag) EntryTags.create(tag=tag_obj, entry=entry) present = 0 # remove tags for entrytag in entry.tags: for tag in tags: if entrytag.tag == tag: present = 1 if present == 0: thistag = Tag.get(Tag.tag == entrytag.tag) entry.tags.remove(thistag) present = 0 entry.save() flash('Note updated successfully.', 'success') return redirect(url_for('detail', slug=entry.slug)) except: flash('Note title already exists', 'danger') return render_template('create.html') else: flash('Title and Content are required.', 'danger') return render_template('edit.html', entry=entry, tags=tags)
def remove_tag_callback(bot, update, data): # data = [user handle, id, ] tag_id = int(data[1]) user = TGUser.get(handle=data[0]) tag = Tag.get(id=tag_id) TGUserToTag.get(user=user, tag=tag).delete_instance() return f"Removed {tag.tag}"
def post(): longitude = request.form.get('longitude', '') latitude = request.form.get('latitude', '') treasure = request.form.getlist('treasure') if not (isfloat(latitude) and isfloat(longitude) and treasure): return redirect('/post.html') try: tags = [Tag.get(tag=x) for x in treasure] except Tag.DoesNotExist: return redirect('/post.html') x, obj_created = Point.get_or_create( latitude=latitude, longitude=longitude, defaults={'treasure': ', '.join(treasure)}) # type:Point,bool if obj_created: for y in tags: PointTag.create(tag=y, point=x) l = LogPoint.create(latitude=latitude, longitude=longitude, treasure=', '.join(treasure), created_date=x.created_date) else: return render_template('post.html', tags=Tag.select().execute(), message='坐标已存在') # return render_template('post.html') # return '坐标已存在 <a href="/post.html">重新分享</a>' return redirect('/')
def tag_button_callback(bot, update, data): # data = [user handle, id, ] tag_id = int(data[1]) user = TGUser.get(handle=data[0]) tag = Tag.get(id=tag_id) TGUserToTag.get_or_create(user=user, tag=tag) return f"Selected {tag.tag}"
def tag_blogs(tag_id): tag = Tag.get(tag_id) if not tag: raise notfound() blogs = get_blogs_from_tag(tag) blogs = render_blogs(blogs) user = ctx.request.user return dict(blogs=blogs, user=user)
def tag_blogs(tag_id): tag = Tag.get(tag_id) if not tag: raise notfound() blogs = get_blogs_from_tag(tag) blogs = render_blogs(blogs) user = ctx.request.user return dict(blogs=blogs,user=user)
def members(): tag = Tag.get("001449249583583e39048657a1c4584960f34e4623e2dae000") if not tag: raise notfound() blogs = get_blogs_from_tag(tag) blogs = render_blogs(blogs) user = ctx.request.user return dict(blogs=blogs,user=user)
def research(): tag = Tag.get("001449249434796934306a1e38243e8b4fde9e013d286fe000") if not tag: raise notfound() blogs = get_blogs_from_tag(tag) blogs = render_blogs(blogs) user = ctx.request.user return dict(blogs=blogs,user=user)
def admin_tag_edit(uid): try: tag_to_edit = Tag.get(Tag.id == uid) all_tags = Tag.select().where(Tag.id != tag_to_edit.id) except Tag.DoesNotExist: abort(404) return render_template('tag_edit.html', editing=True, tag_to_edit=tag_to_edit, all_tags=all_tags)
def remove_blogtag(blog,remove): if not remove: return remove_string = "','".join(remove) s='delete from blogtag where blogtag.blog_id="%s" and blogtag.tag_id in (\'%s\')' % (blog.id,remove_string) logging.info('#########') logging.info(s) db.update(s) for tag_id in remove: tag = Tag.get(tag_id) tag_count_min(tag)
def post(self, postid): title = self.get_argument('title', None) slug = self.get_argument('slug', '') category_id = self.get_argument('category', 1) content = self.get_argument('content', '') tags = self.get_argument('tag', '') category = Category.get(id=int(category_id)) Post.update(title=title, slug=slug, category=category, content=content, tags=tags).where(Post.id == postid).execute() tag_list = set(tags.split(",")) if tag_list: for tag in tag_list: try: Tag.get(name=tag, post=postid) except Tag.DoesNotExist: Tag.create(name=tag, post=postid) self.redirect('/admin/posts') return
def remove_blogtag(blog, remove): if not remove: return remove_string = "','".join(remove) s = "delete from blogtag where blogtag.blog_id=\"%s\" and blogtag.tag_id in ('%s')" % (blog.id, remove_string) logging.info("#########") logging.info(s) db.update(s) for tag_id in remove: tag = Tag.get(tag_id) tag_count_min(tag)
def _save_question(question, fetch_index): # It seems that the the ID of the owner is missing from some records. # This little bit of logic checks to see if it's missing. owner_id = question['owner']['user_id']\ if 'owner' in question and 'user_id' in question['owner']\ else None # Dates are returned by the Stack Exchange API in Unix epoch time. # This inline method converts the timestamps to datetime objects that # can be stored in a Postgres database. Note that the times will be # converted to _local times_ on this server rather than their original # UTC times. I chose to do this as the date of creation of these records # will also be in local time. timestamp_to_datetime = lambda ts: datetime.datetime.fromtimestamp(ts) # Create a snapshot of this question snapshot = QuestionSnapshot.create( fetch_index=fetch_index, question_id=question['question_id'], owner_id=owner_id, comment_count=question['comment_count'], delete_vote_count=question['delete_vote_count'], reopen_vote_count=question['reopen_vote_count'], close_vote_count=question['close_vote_count'], is_answered=question['is_answered'], view_count=question['view_count'], favorite_count=question['favorite_count'], down_vote_count=question['down_vote_count'], up_vote_count=question['up_vote_count'], answer_count=question['answer_count'], score=question['score'], last_activity_date=timestamp_to_datetime( question['last_activity_date']), creation_date=timestamp_to_datetime(question['creation_date']), title=question['title'], body=question['body'], ) # Link this snapshot to all tags related to it for tag_name in question['tags']: if tag_name in tag_cache: tag = tag_cache[tag_name] else: try: tag = Tag.get(tag_name=tag_name) except Tag.DoesNotExist: tag = None tag_cache[tag_name] = tag if tag is not None: QuestionSnapshotTag.create(question_snapshot_id=snapshot.id, tag_id=tag.id)
def delete_entry(kind, entry, from_file=None): """Deletes a file name entry or tag entry from the catalog""" if kind == 'files': to_delete = File.get(File.file_name == entry) to_delete.delete_instance() print "'%s' deleted from catalog!" % entry elif kind == 'tag' and from_file: try: existing_file = File.get(File.file_name == from_file) if existing_file: try: association = FileTag.get(FileTag.file_id == existing_file, FileTag.tag_id == Tag.get(Tag.tag_name == entry)) association.delete_instance() print "Deleted '%s' from '%s'" % (entry, from_file) except: print "'%s' no longer tagged to %s" % (entry, from_file) except: print "'%s' not in catalog" % from_file elif kind == 'tag': tag_item = Tag.get(Tag.tag_name == entry) tag_item.delete_instance() print "'%s' deleted from catalog" % entry else: pass
def _save_question(question, fetch_index): # It seems that the the ID of the owner is missing from some records. # This little bit of logic checks to see if it's missing. owner_id = question['owner']['user_id']\ if 'owner' in question and 'user_id' in question['owner']\ else None # Dates are returned by the Stack Exchange API in Unix epoch time. # This inline method converts the timestamps to datetime objects that # can be stored in a Postgres database. Note that the times will be # converted to _local times_ on this server rather than their original # UTC times. I chose to do this as the date of creation of these records # will also be in local time. timestamp_to_datetime = lambda ts: datetime.datetime.fromtimestamp(ts) # Create a snapshot of this question snapshot = QuestionSnapshot.create( fetch_index=fetch_index, question_id=question['question_id'], owner_id=owner_id, comment_count=question['comment_count'], delete_vote_count=question['delete_vote_count'], reopen_vote_count=question['reopen_vote_count'], close_vote_count=question['close_vote_count'], is_answered=question['is_answered'], view_count=question['view_count'], favorite_count=question['favorite_count'], down_vote_count=question['down_vote_count'], up_vote_count=question['up_vote_count'], answer_count=question['answer_count'], score=question['score'], last_activity_date=timestamp_to_datetime(question['last_activity_date']), creation_date=timestamp_to_datetime(question['creation_date']), title=question['title'], body=question['body'], ) # Link this snapshot to all tags related to it for tag_name in question['tags']: if tag_name in tag_cache: tag = tag_cache[tag_name] else: try: tag = Tag.get(tag_name=tag_name) except Tag.DoesNotExist: tag = None tag_cache[tag_name] = tag if tag is not None: QuestionSnapshotTag.create(question_snapshot_id=snapshot.id, tag_id=tag.id)
def admin_tag_save(): tags = request.form.get('tags') edit_id = request.form.get('tag-edit-id') tags = [tag_json["value"] for tag_json in json.loads(tags)] if tags else None if tags: if edit_id: try: tag_to_edit = Tag.get(Tag.id == edit_id) tag_to_edit.name = tags[0] tag_to_edit.save() flash("Tag edited", "success") except Tag.DoesNotExist: abort(404) else: successes = [] for tag in tags: t, created = Tag.get_or_create(name=tag) successes.append(created) if successes.count(True) == 1: flash( "Tag \"" + ", ".join([ tag for tag, success in zip(tags, successes) if success == True ]) + "\" created!", "success") elif successes.count(True) > 1: flash( "Tags \"" + ", ".join([ tag for tag, success in zip(tags, successes) if success == True ]) + "\" created!", "success") if successes.count(False) == 1: flash( "Tag \"" + ", ".join([ tag for tag, success in zip(tags, successes) if success == False ]) + "\" already existed!", "danger") elif successes.count(False) > 1: flash( "Tags \"" + ", ".join([ tag for tag, success in zip(tags, successes) if success == False ]) + "\" already existed!", "danger") else: flash("No tag names", "danger") return redirect(url_for('admin_tag_list'))
def posts_for_tag(tag_id): try: tag = Tag.get(Tag.tag_id == tag_id) except DoesNotExist: # todo: enable logging for all these exceptions abort(404) posts = Post.get_posts().join(Tag_to_Post).\ where(Tag_to_Post.tag_id == tag_id) how = posts.count() if how: info = u'Статті, відмічені тегом "%s" (%s)' % (tag.text, how) else: info = u'Для рідкісного тега "%s" немає статтей' % tag.text template = env.get_template('post/list.html') return template.render(posts=posts, info=info)
def add_tag(tag): """Adds a tag to the catalog""" tag = tag.strip() new_tag = False try: current_tag = Tag(tag_name=tag) current_tag.save() new_tag = True except IntegrityError: current_tag = Tag.get(Tag.tag_name == tag) return current_tag, new_tag
def create(): if request.method == "POST": if request.form.get("title") and request.form.get("content"): try: entry = Entry.create( title=request.form["title"], content=request.form["content"], archived=request.form.get("archived") or False, ) tags = request.form["tags"].split() # present is a check to see if the tag exists present = 0 # add or create tags for tag in tags: for entrytag in entry.tags: if tag == entrytag.tag: present = 1 if present == 0: try: thistag = Tag.get(Tag.tag == tag) entry.tags.add(thistag) except: tag_obj, was_created = Tag.create_or_get(tag=tag) EntryTags.create(tag=tag_obj, entry=entry) present = 0 flash("Entry created successfully.", "success") return redirect(url_for("detail", slug=entry.slug)) except: flash("Note title already exists", "danger") return render_template("create.html") # TODO Refactor the below and above to make it more DRY or not # to need to display seconds (e.g. add some kind of suffix if entry # already exists) elif request.form.get("content"): entry = Entry.create( title="{:%a %d %b %Y at %H:%M:%S}".format(datetime.datetime.now()), content=request.form["content"] ) flash("Note created successfully.", "success") return redirect(url_for("detail", slug=entry.slug)) else: flash("Content is required.", "danger") return render_template("create.html")
def delete(self, id=None): """ headers = Token args = {} """ user = auth_token() if not user: return response_model(), 401 if not id: return response_model(), 400 try: t = Tag.get(Tag.id == id) t.delete_instance() except: return response_model(), 400 return response_model(), 200
def add_new_tags(tags_string, post_id): """ Add new tags or create connection to post with existed """ tags = tags_string.split(';') for tag in tags: tg = tag.replace(' ', '') if not tg: continue try: old_tag = Tag.get(Tag.text == tag) try: tmp = Tag_to_Post.get(Tag_to_Post.post_id == post_id, Tag_to_Post.tag_id == old_tag.tag_id) except Tag_to_Post.DoesNotExist: Tag_to_Post.create(post_id=post_id, tag_id=old_tag.tag_id) except Tag.DoesNotExist: new_tag = Tag.create(text=tag) Tag_to_Post.create(post_id=post_id, tag_id=new_tag.tag_id) return
def create(): if request.method == 'POST': if request.form.get('title') and request.form.get('content'): try: entry = Entry.create( title=request.form['title'], content=request.form['content'], archived=request.form.get('archived') or False) tags = request.form['tags'].split() # present is a check to see if the tag exists present = 0 # add or create tags for tag in tags: for entrytag in entry.tags: if tag == entrytag.tag: present = 1 if present == 0: try: thistag = Tag.get(Tag.tag == tag) entry.tags.add(thistag) except: tag_obj, was_created = Tag.create_or_get(tag=tag) EntryTags.create(tag=tag_obj, entry=entry) present = 0 flash('Entry created successfully.', 'success') return redirect(url_for('detail', slug=entry.slug)) except: flash('Note title already exists', 'danger') return render_template('create.html') # TODO Refactor the below and above to make it more DRY or not # to need to display seconds (e.g. add some kind of suffix if entry # already exists) elif request.form.get('content'): entry = Entry.create( title="{:%a %d %b %Y at %H:%M:%S}".format(datetime.datetime.now()), content=request.form['content']) flash('Note created successfully.', 'success') return redirect(url_for('detail', slug=entry.slug)) else: flash('Content is required.', 'danger') return render_template('create.html')
def test_tags_become_deleted_on_overwrite(self): #create a file with tags self.sharedfile.description = """#here #is some #tags that I got for #you. #here is another word that #is not to be duplicated.""" self.sharedfile.save() #load the file back up and change the description self.sharedfile = Sharedfile.get("id = %s", self.sharedfile.id) self.sharedfile.description = "some #all #newtags #not #old" self.sharedfile.save() #save the file and check that the new tags are only returned tags = self.sharedfile.tags() for tf in tags: self.assertTrue(tf.name in ['all', 'newtags', 'not', 'old']) #load the deleted tags and check that they are the same as the original tagged_files = TaggedFile.where("deleted = 1") for tf in tagged_files: t = Tag.get('id = %s', tf.tag_id) self.assertTrue(t.name in ['here', 'is', 'tags', 'you'])
def tag_a_file(file_name, tag, new_tag): """Associates a file name with a tag""" if not new_tag: files_with_tag = (File .select() .join(FileTag) .join(Tag) .where(FileTag.tag_id == Tag.get(Tag.tag_name == tag.tag_name))) for f in files_with_tag: if file_name.file_name == f.file_name: return try: ft = FileTag(file_id=file_name, tag_id=tag) ft.save() except IntegrityError: return print "'%s' added to %s tags!" % (tag.tag_name, file_name.file_name)
def admin_tag_delete(): status = {'ok': True} data = request.get_json() if 'id' not in data: abort(400) id_to_delete = data["id"] if id_to_delete: try: tag_to_delete = Tag.get(Tag.id == id_to_delete) posttags_to_delete = PostTag.select().where( PostTag.tag == tag_to_delete) for posttag in posttags_to_delete: posttag.delete_instance() tag_to_delete.delete_instance() except Tag.DoesNotExist: status['ok'] = False return json.dumps(status)
def update(self): """updates a post""" #for catobj in self.categories: # logging.info([catobj.key(),catobj.category,catkeys]) # if catobj.category==self.postcatkey:#AN OLD CATEGORY # catkey=catobj.key() # elif catobj.key() not in self.catkeys:#not used category # catobj.delete() # else: # logging.info(catobj.key().id()) #newcatobj=Category() #newcatobj.category=category #newcatobj.put() #catkey=newcatobj.key() post_tagsdb_values=[] post_tagsdb_keys=[] existingTags=[] existingTagskeys=[] tagsleft=[] #find the existing tags of the post for tagkey in self.posts_tags_db: if tagkey not in self.post_tags_keys: try: tagsleft.append(Tag.get_by_id(tagkey.id()).tag) except AttributeError:#ops a post without a tag continue existingTagskeys.append(tagkey) existingTags.append(db.get(tagkey).tag) #existing Tags for tagkey in self.post_tags_keys:post_tagsdb_values.append(db.get(tagkey).tag)#previous Tags of the post # logging.info([self.posttags,type(self.posttags),type(post_tagsdb_values),post_tagsdb_values]) unchangedtags=[] returnedTags=[] # logging.info(['posttags',self.posttags,post_tagsdb_values]) if post_tagsdb_values:#post does have tags logging.info(post_tagsdb_values) unchangedtags=set(self.posttags) & set( post_tagsdb_values)#changes tags added or removed newtags=set(self.posttags) ^ unchangedtags#new tags for this post oldtags=list(set(post_tagsdb_values)^unchangedtags) logging.info(["new",newtags,"old",oldtags,"unchanged",unchangedtags,list(unchangedtags)]) if list(unchangedtags): unchangedtags=list(unchangedtags) for tag in unchangedtags: tagid=db.get(existingTagskeys[existingTags.index(tag)]).key().id() returnedTags.append({"tag":tag,"tagid":tagid}) else:unchangedtags=[] i=0 logging.info(['Tags from other posts',existingTags]) for tag in oldtags:#tags to be removed tag_key= existingTagskeys[existingTags.index(tag)] if tag not in tagsleft:#delete not used tags tagobj=db.get(tag_key) logging.info(["deleting",tag,tagobj]) tagobj.delete() pos=post_tagsdb_values.index(tag) self.obj.tags.pop(pos-i) i+=1 elif self.posttags:#new tags do exist logging.info(self.posttags) newtags=set(self.posttags)#does not have tags else:newtags=[] if newtags: for tag in list(newtags):#add new tag and update Post logging.info(tag) if tag not in existingTags: tagobj=Tag() tagobj.tag=tag tagid=tagobj.put().id() returnedTags.append({"tag":tag,"tagid":tagid}) else: tag_key= existingTagskeys[existingTags.index(tag)] tagobj=Tag.get(tag_key) returnedTags.append({"tag":tagobj.tag,"tagid":tagobj.key().id()}) self.obj.tags.append(tagobj.key()) if isinstance(self.postcategory,list):self.postcategory=self.postcategory[0] logging.info([self.catdict.values()]) self.obj.title=self.title self.obj.body=self.body self.obj.category=self.catdict.keys()[self.catdict.values().index(self.postcategory)] self.obj.updated=datetime.now() self.obj.put() createIndex([self.obj]) tags=[] [tags.append({"tag":db.get(key).tag,"tagid":db.get(key).key().id()}) for key in self.obj.tags] data=[] updated=str(self.obj.updated.day)+" "+str(months[self.obj.updated.month])+" "+str(self.obj.updated.year) dateposted=str(self.obj.timestamp.day)+" "+str(months[self.obj.timestamp.month])+" "+str(self.obj.timestamp.year) data.append({"title":self.obj.title,"body":self.obj.body,"category":db.get(self.obj.category.key()).category, "catid": db.get(self.obj.category.key()).key().id(),"id":str(self.obj.key().id()),\ "tags":tags,"date":dateposted,"updated":updated}) self.deleteMemcache(self) self.refetch(self) return(data,returnedTags)
def bookmark_edit(id): user = auth.get_logged_in_user() bookmark = {} try: bookmark = Bookmark.get(Bookmark.id == id) bookmark.tags = ' '.join([Tag.get(Tag.id == tagID).name for tagID in [tag.tag for tag in bookmark.Tags]]) except Bookmark.DoesNotExist: flash(u'你要编辑的书签不存在', 'error') return redirect(url_for('page_404')) error = {} if request.method == 'POST': try: bookmark = Bookmark.get(Bookmark.id == request.form['id']) except Bookmark.DoesNotExist: flash(u'你要编辑的书签不存在', 'error') return redirect(url_for('page_404')) if not request.form['url']: error['url'] = u'书签的网址不能为空' if not error: try: db.database.set_autocommit(False) # before update image, should remove old version if bookmark.url != request.form['url']: bookmark.destory_image() bookmark.url = request.form['url'] bookmark.fetch_image() bookmark.title = request.form['title'] 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')) return render_template('bookmark_edit.html', error=error, form=request.form, bookmark=bookmark, user=user)
def get(self, tag_name=None, before_or_after=None, base36_id=None): tag = Tag.get("name=%s", tag_name.lower()) older_link, newer_link = None, None sharedfile_id = None shared_files = [] if not tag: raise tornado.web.HTTPError(404) if base36_id: sharedfile_id = base36decode(base36_id) max_id, since_id = None, None if sharedfile_id and before_or_after == 'before': max_id = sharedfile_id elif sharedfile_id and before_or_after == 'after': since_id = sharedfile_id current_user = self.get_current_user_object() # We're going to older, so ony use max_id. if max_id: shared_files = tag.sharedfiles_paginated(max_id=max_id, per_page=11) # we have nothing on this page, redirect to home page with out params. if len(shared_files) == 0: return self.redirect("/tag" + tag.path()) if len(shared_files) > 10: older_link = "/tag%s/before/%s" % (tag.path(), shared_files[9].share_key) newer_link = "/tag%s/after/%s" % (tag.path(), shared_files[0].share_key) else: newer_link = "/tag%s/after/%s" % (tag.path(), shared_files[0].share_key) # We're going to newer elif since_id: shared_files = tag.sharedfiles_paginated(since_id=since_id, per_page=11) if len(shared_files) <= 10: return self.redirect("/tag" + tag.path()) else: shared_files.pop(0) older_link = "/tag%s/before/%s" % (tag.path(), shared_files[9].share_key) newer_link = "/tag%s/after/%s" % (tag.path(), shared_files[0].share_key) else: # clean home page, only has older link shared_files = tag.sharedfiles_paginated(per_page=11) if len(shared_files) > 10: older_link = "/tag%s/before/%s" % (tag.path(), shared_files[9].share_key) return self.render("tags/tag.html", tag=tag, shared_files=shared_files[0:10], current_user_obj=current_user, older_link=older_link, newer_link=newer_link)
tags = {x.tag for x in Tag.select().execute()} tags.remove('地狱级npc') tags = list(tags) tags_id = [x for x in Tag.select().where(Tag.tag.in_(tags))] q = PointTag.delete().where(PointTag.tag.in_(tags_id)).execute() for p in Point.select(Point): new_tr = [x.tag.tag for x in p.pointtag] if not new_tr: p.delete_instance() else: p.treasure = ', '.join(new_tr) p.save() for p in UserPoint.select(): p.delete_instance() if sys.argv[1] == 'add': if sys.argv[2] == 'tag': Tag.create(sys.argv[3]) if sys.argv[1] == 'delete': if sys.argv[2] == 'tag': t = Tag.get(sys.argv[3]) t.delete() if sys.argv[2] == 'point': p = Point.get(longitude=sys.argv[3], latitude=sys.argv[4]) p.delete_instance() else: t = Tag.select(Tag).execute() for x in t: [print(y.point.treasure) for y in x.pointtag]
def test_many_to_many_relationships(self): """Make sure JournalEntries and Tags can have many to many relationships""" journal_entry_data_1 = { 'title': 'entry 1', 'date': datetime.datetime.now().strftime('%Y-%m-%d'), 'time_spent': '111', 'what_i_learned': 'many to many relationships', 'resources_to_remember': 'docs.peewee-orm.com' } journal_entry_data_2 = { 'title': 'entry 2', 'date': datetime.datetime.now().strftime('%Y-%m-%d'), 'time_spent': '222', 'what_i_learned': 'many to many relationships', 'resources_to_remember': 'docs.peewee-orm.com' } with test_database(TEST_DB, (User, JournalEntry, Tag, JournalEntryTag)): # create the user UserModelTestCase.create_users(1) # create the journal entries journal_entry_data_1['user'] = User.select().get() journal_entry_data_2['user'] = User.select().get() JournalEntry.create(**journal_entry_data_1) JournalEntry.create(**journal_entry_data_2) entry1 = JournalEntry.get(JournalEntry.title == 'entry 1') entry2 = JournalEntry.get(JournalEntry.title == 'entry 2') # create the tags Tag.create_tag(tag='first') Tag.create_tag(tag='both') Tag.create_tag(tag='second') tag1 = Tag.get(Tag.tag == 'first') tag2 = Tag.get(Tag.tag == 'both') tag3 = Tag.get(Tag.tag == 'second') # tie tags to entries entry1.tags.add( [Tag.get(Tag.tag == 'first'), Tag.get(Tag.tag == 'both')]) entry2.tags.add( [Tag.get(Tag.tag == 'second'), Tag.get(Tag.tag == 'both')]) # assertions self.assertIn(tag1, entry1.tags) self.assertIn(tag2, entry1.tags) self.assertNotIn(tag3, entry1.tags) self.assertNotIn(tag1, entry2.tags) self.assertIn(tag2, entry2.tags) self.assertIn(tag3, entry2.tags) self.assertIn(entry1, tag1.journal_entries) self.assertNotIn(entry2, tag1.journal_entries) self.assertIn(entry1, tag2.journal_entries) self.assertIn(entry2, tag2.journal_entries) self.assertNotIn(entry1, tag3.journal_entries) self.assertIn(entry2, tag3.journal_entries)