def home(): user = { 'username': '******', 'age': 27 } websites = ['baidu.com', 'google.com'] #新建两篇文章 art1 = Art(title='大海') art2 = Art(title='小人') #新建两个标签 tag1 = Tag(name='酸') tag2 = Tag(name='甜') #添加多对多关系,文章1添加两个标签 art1.tags.append(tag1) art1.tags.append(tag2) # 添加多对多关系,文章2添加两个标签 art2.tags.append(tag1) art2.tags.append(tag2) #添加部分 db.session.add(art1) db.session.add(art2) db.session.add(tag1) db.session.add(tag2) db.session.commit() return render_template('home.html', user=user, websites=websites)
def test_post_tag(self): t1 = Tag(name='iot') t2 = Tag(name='web') p1 = Post(content='This is a post contain iot and web tags.') p2 = Post(content='This is a post contain web.') p1.add_all_tags([t1, t2]) p2.tags.append(t2) self.session.add_all([t1, t2, p1, p2]) self.session.commit() self.assertCountEqual(t1.posts, [p1]) self.assertCountEqual(t2.posts, [p1, p2]) self.assertCountEqual(p1.tags, [t1, t2]) self.assertCountEqual(p2.tags, [t2])
async def api_create_blog(request, *, name, summary, content, selectedTags): check_admin(request) if not name or not name.strip(): raise APIValueError("name", "name cannot be empty.") if not summary or not summary.strip(): raise APIValueError("summary", "summary cannot be empty.") if not content or not content.strip(): raise APIValueError("content", "content cannot be empty.") blog = Blog( user_id=request.__user__.id, user_name=request.__user__.name, user_image=request.__user__.image, name=name.strip(), summary=summary.strip(), content=content.strip(), ) await blog.save() for selectedTag in selectedTags: if selectedTag["key"]: blog_tag = BlogTag(blog_id=blog.id, tag_id=selectedTag["key"]) await blog_tag.save() else: tag = Tag(name=selectedTag["value"]) await tag.save() blog_tag = BlogTag(blog_id=blog.id, tag_id=tag.id) await blog_tag.save() return blog
def load_waymarks(): """Load points from Waymark scraped txt file into database""" print "Waymark Murals SF" for row in open("seed_data/waymarks.txt"): row = row.rstrip() latitude, longitude, title, artist, details, media_url = row.split('|') tag = Tag(latitude=latitude, longitude=longitude, title=title, artist=artist, details=details, primary_image=media_url) db.session.add(tag) db.session.commit() tag_genre = TagGenre(tag_id=tag.tag_id, genre="art") db.session.add(tag_genre) db.session.commit()
def load_art_points_Oakland(): """Load points from Oakland public art csv data into database""" print "Tags Oakland" with open("seed_data/Oakland_Civic_Art.csv") as csv_file: for row in csv.reader(csv_file): title, artist, artist_origin, year, temp_or_perm, in_or_out, media, media_detail, location, address = row #parse location information into latitude and longitude lat_long = location.split('\n')[-1][1:-1].split(", ") latitude = float(lat_long[0]) longitude = float(lat_long[1]) tag = Tag(latitude=latitude, longitude=longitude, title=title, artist=artist, details=media_detail) db.session.add(tag) db.session.commit() tag_genre = TagGenre(tag_id=tag.tag_id, genre="art") db.session.add(tag_genre) db.session.commit()
def load_art_points_SF(): """Load points from SF public art csv data into database""" print "Tags SF" Tag.query.delete() with open("seed_data/SF_Civic_Art.csv") as csv_file: for row in csv.reader(csv_file): artist, created_at, patron, size, geometry, location, details, source, title = row[ 3:12] latitude = json.loads(geometry)['coordinates'][1] longitude = json.loads(geometry)['coordinates'][0] tag = Tag(latitude=latitude, longitude=longitude, title=title, artist=artist, details=details) db.session.add(tag) db.session.commit() tag_genre = TagGenre(tag_id=tag.tag_id, genre="art") db.session.add(tag_genre) db.session.commit()
def load_freesound_audio(): """Load points gathered from Freesound API""" print "Freesound SF" for row in open("seed_data/freesounds.txt"): row = row.rstrip() latitude, longitude, title, details, audio_url = row.split('|') tag = Tag(latitude=latitude, longitude=longitude, title=title, details=details) db.session.add(tag) db.session.commit() tag_genre = TagGenre(tag_id=tag.tag_id, genre="audio") db.session.add(tag_genre) media = Media(tag_id=tag.tag_id, media_url=audio_url, media_type="audio") db.session.add(media) db.session.commit()
def get_tags_by_names(tags): sql = '''SELECT * FROM tag WHERE name in %(name)s''' rows = pg_select(sql, {'name': tuple(tags)}) tags = [Tag(*row) for row in rows] return tags
async def api_create_tag(request, *, name): check_admin(request) if not name or not name.strip(): raise APIValueError("name", "name cannot be empty.") tag = Tag(name=name.strip()) await tag.save() return tag
def add_tag(): """Add/edit a tag""" # hold a list of new tags from string input new_tags = [] # Get form variables image_id = request.form["image_id"] tag_string = request.form["query"] new_tags = get_tags_from_string(tag_string) if not image_id: raise Exception("No image to tag") all_tags = Image_Tags.query.filter_by(image_id=image_id).all() if all_tags: # add new tag to list of tags stored in db flash("Tag added.") else: # add new tag list to database tag_label = Tag(tag_label=tag_label) flash("Tag added.") db.session.add(tag_label) db.session.commit() return redirect("/images/%s" % image_id)
def pub(ctx,request:YuHeLg.Request): payload = request.json post = Post() try: post.title = payload.get("title") post.author_id = request.user.id post.postdate = datetime.datetime.now() cont = Content() cont.content = payload.get("content") post.content = cont tags = payload["tags"] except Exception as e: print(e) raise exc.HTTPBadRequest() taglist = re.split('[\s,]',tags) for tag in taglist: t = session.query(Tag).filter(Tag.tag == tag).first() if t is None: t = Tag() t.tag = tag session.add(t) pt = Post_tag() pt.tag = t pt.post = post session.add(pt) session.add(post) try: session.commit() return jsonify(post_id=post.id) except: session.rollback() raise exc.HTTPInternalServerError()
def add_or_rm_tags(): """Lets an admin add or remove a tag to the tag table. Currently this route is throwing an ERROR. Please investigate.""" if current_user.id == 1: if request.form.get("newtag", False): newtag = request.form["newtag"] tag_to_add = Tag(tag_name=newtag) db.session.add(tag_to_add) if request.form.get("rmtag", False): rmtag = request.form["rmtag"] try: Tag.query.filter_by(tag_name=rmtag).delete() except: print("Tag deletion Invalid") db.session.commit() return render_template("homepage.html")
def post(self): created = datetime.strptime(request.json['created'], '%Y-%m-%dT%H:%M:%S.%fZ') request.json['created'] = created tag = Tag(**request.json) session.add(tag) session.commit() return tag.id
def create_tag(session: helpers.extend.session, user: hug.directives.user, response, warehouse_id: int, name): """Creates a tag""" return helpers.do_in_warehouse( "tag", queries.with_editor_role( queries.user_warehouse(session, user, warehouse_id)), lambda warehouse: Tag(warehouse=warehouse, name=name))
def createTag(self, request, context): db_project = session.query(Project).filter_by(id=request.project_id).first() tag = Tag(name=request.name, project_id=db_project.id, user_id=request.user_id, created_at=date.today()) session.add(tag) session.commit() db_tag = session.query(Tag).filter_by(name=request.name, project_id=request.project_id).first() return message.TagResponse(id=str(db_tag.id), name=db_tag.name, project_id=str(db_tag.project_id))
def get_tag(tagname, session): """Return or create a Tag object for this tag name.""" tag = session.query(Tag).filter_by(text=tagname).first() if not tag: tag = Tag(tagname) session.add(tag) session.commit() return tag
def create_initial_tags(): """creates all records in the tags table""" for tag in tags_list: temp_tag = Tag(tag_name=tag) db.session.add(temp_tag) db.session.commit()
def create_tag(tag): """Create a tag.""" tag = Tag(tag=tag) db.session.add(tag) db.session.commit() return tag
def create_tag(tagword): """Create new keyword""" tag = Tag(tagword=tagword) db.session.add(tag) db.session.commit() return tag
def add_post(post, fix_photosets, blog_name="", offline_mode=False, monolithic=False): tag_list = [] for tag_element in post.find_all("tag"): this_tag = Tag(post_id=post["id"], tag=tag_element.text.strip()) tag_list.append(this_tag) base_post = Post( id=post["id"], # url=post["url"], # url_with_slug=post["url-with-slug"], # slug=post["slug"], type=post["type"], # state=post["state"], # date_gmt=post["date-gmt"], # date=post["date"], unix_timestamp=post["unix-timestamp"], # format=post["format"], # reblog_key=post["reblog-key"], is_reblog=post["is_reblog"], tumblelog=post["tumblelog"], tags=tag_list, # private=post.get("private", "false"), # width=int(post.get("width")) if post.get("width") else None, # width=post.get("width"), # height=post.get("height"), # direct_video=post.get("direct-video"), audio_plays=post.get("audio-plays")) if offline_mode: replace_links(post, blog_name, monolithic) specific_post = None if post["type"] == "regular": specific_post = make_regular(post) elif post["type"] == "photo": specific_post = make_photo(post, fix_photosets, blog_name) elif post["type"] == "link": specific_post = make_link(post) elif post["type"] == "answer": specific_post = make_answer(post) elif post["type"] == "quote": specific_post = make_quote(post) elif post["type"] == "conversation": specific_post = make_conversation(post) elif post["type"] == "video": specific_post = make_video(post) elif post["type"] == "audio": specific_post = make_audio(post) return base_post, specific_post
def add_tag_data(tag): """Assume tag is a tag in string form. Add it to the database.""" add_tag = Tag(tag=tag) db.session.add(add_tag) try: db.session.commit() except (Exception, exc.SQLAlchemyError, exc.InvalidRequestError, exc.IntegrityError) as e: print(tag + '\n' + str(e))
def get_tags_by_ids(ids): sql = '''SELECT * FROM tag WHERE tag_id in %(ids)s''' if len(ids) == 0: return [] rows = pg_select(sql, {'ids': tuple(ids)}) tags = [Tag(*row) for row in rows] return tags
def edit_workflow(workflow_id): wf = Workflow.query.filter_by(id=workflow_id).first() if wf is None: abort(404) if wf.user_id != current_user.id: abort(403) if request.method == "GET": tag_str = " ".join([t.name for t in wf.tags]) return render_template("edit.html", workflow=wf, tag_str=tag_str) elif request.method == "POST": form = NewWorkflow() tags = [] for tag in form.tag.data.split(" "): tag_name = tag.strip() t = Tag.query.filter_by(name=tag_name).first() if t is None: t = Tag(tag_name) db.session.add(t) db.session.commit() tags.append(t) subdir = os.path.join("static", "workflows", str(wf.id)) if form.knwf.data.filename: filename = secure_filename(form.knwf.data.filename) form.knwf.data.save(os.path.join(subdir, filename)) zfile = ZipFile(form.knwf.data) node_list = [] for name in zfile.namelist(): if name.endswith("workflow.svg"): png_file = os.path.join(subdir, "workflow.png") s = zfile.read(name) svg2png(bytestring=s, write_to=png_file) tname = name.split("/")[1] node_name = tname.split("(")[0] if not node_name.startswith( "workflow") and not node_name.startswith("."): node_name = node_name.rstrip() node_list.append(node_name) nl = list(set(node_list)) nodes = [] for node_name in nl: n = Node.query.filter_by(name=node_name).first() if n is None: n = Node(node_name) db.session.add(n) db.session.commit() nodes.append(n) wf.workflow = filename wf.nodes = nodes wf.tags = tags wf.name = form.name.data wf.content = form.content.data wf.rendered_content = md.convert(wf.content) db.session.commit() return redirect(url_for("display_workflow", workflow_id=workflow_id))
def tag_document(document, tagname): """Given a document object, tag it with the named tag. Optionally create the tag if it doesn't exist yet. """ session = get_session() tag = session.query(Tag).filter_by(text=tagname).first() if not tag: tag = Tag(tagname) session.add(tag) document.tags.append(tag) session.commit()
def load_tags(tags_filename): print("Tags") Tag.query.delete() for row in open(tags_filename): row = row.rstrip() tag = Tag(tag_word=row) # We need to add to the session or it won't ever be stored db.session.add(tag) # Once we're done, we should commit our work db.session.commit()
def create_tag(): tag_name = request.json['tag_name'] new_tag = Tag(tag_name) try: db.session.add(new_tag) db.session.commit() except: return 'Tag have already existed!' return tag_schema.jsonify(new_tag)
def new_workflow(): form = NewWorkflow() # Don't pass request.form if form.validate_on_submit(): tags = [] for tag in form.tag.data.split(" "): tag_name = tag.strip() t = Tag.query.filter_by(name=tag_name).first() if t is None: t = Tag(tag_name) db.session.add(t) db.session.commit() tags.append(t) wf = Workflow(name=form.name.data, user_id=current_user.id, content=form.content.data) db.session.add(wf) db.session.commit() filename = secure_filename(form.knwf.data.filename) subdir = os.path.join("static", "workflows", str(wf.id)) if not os.path.exists(subdir): os.mkdir(subdir) form.knwf.data.save(os.path.join(subdir, filename)) zfile = ZipFile(form.knwf.data) node_list = [] for name in zfile.namelist(): if name.endswith("workflow.svg"): png_file = os.path.join(subdir, "workflow.png") s = zfile.read(name) svg2png(bytestring=s, write_to=png_file) tname = name.split("/")[1] node_name = tname.split("(")[0] if not node_name.startswith( "workflow") and not node_name.startswith("."): node_name = node_name.rstrip() node_list.append(node_name) nl = list(set(node_list)) nodes = [] for node_name in nl: n = Node.query.filter_by(name=node_name).first() if n is None: n = Node(node_name) db.session.add(n) db.session.commit() nodes.append(n) wf.workflow = filename wf.tags = tags wf.nodes = nodes db.session.commit() return redirect(url_for("index")) flash_errors(form) return render_template("new.html", form=form)
def parse_tags(tags_list_dict): if tags_list_dict is not None and len(tags_list_dict) > 0: tags_list = [] for tag_dict in tags_list_dict: tag = Tag() tag.unique_slug = tag_dict["slug"] tag.name = tag_dict["name"] tag.post_count = tag_dict["postCount"] metadata_dict = tag_dict["metadata"] if metadata_dict is not None: tag.follower_count = metadata_dict["followerCount"] tags_list.append(to_dict(tag)) return tags_list
async def api_update_blog(id, request, *, name, summary, content, selectedTags): check_admin(request) blog = await Blog.find(id) blog_tags = await BlogTag.findAll("`blog_id`=?", [id]) if not name or not name.strip(): raise APIValueError("name", "name cannot be empty.") if not summary or not summary.strip(): raise APIValueError("summary", "summary cannot be empty.") if not content or not content.strip(): raise APIValueError("content", "content cannot be empty.") blog.name = name.strip() blog.summary = summary.strip() blog.content = content.strip() await blog.update() # for selectedTag in selectedTags: # if selectedTag['key']=='': # tag = Tag(name=selectedTag['value']) # await tag.save() # blog_tag = BlogTag(blog_id=blog.id,tag_id=tag.id) # await blog_tag.save() # selectedTags.remove(selectedTag) for blog_tag in blog_tags: for selectedTag in selectedTags: if blog_tag.id == selectedTag["key"]: blog_tags.remove(blog_tag) selectedTags.remove(selectedTag) for selectedTag in selectedTags: if selectedTag["key"]: blog_tag = BlogTag(blog_id=blog.id, tag_id=selectedTag["key"]) await blog_tag.save() else: tag = Tag(name=selectedTag["value"]) await tag.save() blog_tag = BlogTag(blog_id=blog.id, tag_id=tag.id) await blog_tag.save() tags = [] for blog_tag in blog_tags: tags.append(await Tag.find(blog_tag.tag_id)) for tag in tags: if (await BlogTag.findNumber("count(id)", "`tag_id`=?", [tag.id])) == 1: await tag.remove() for blog_tag in blog_tags: await blog_tag.remove() return blog
def addpost(): if not session.get('logged_in'): abort(401) elif request.method == 'POST': tagtemp = [] taglist = request.form['tags'].split(',') for i in taglist: tagtemp.append(Tag(name=i)) db.session.add(Post(tags=tagtemp, post_content=request.form['content'], post_title=request.form[ 'title'], category_id=request.form['category'], post_name=request.form['postname'], tags_name=request.form['tags'])) db.session.commit() return redirect(url_for('newpost'))