def create_post(): form = PostForm(request.form) if 'username' in session: if request.method == 'POST' and form.validate_on_submit(): try: post = Post(title=form.title.data, preview=form.preview.data, body=form.body.data, author=session['username']) tag_list = re.sub(r'[\s, .]', ' ', form.tags.data).split() for i in set(tag_list): if Tag.query.filter_by(name=i).first(): tag = Tag.query.filter_by(name=i).first() else: tag = Tag(name=i) post.tags.append(tag) post.author = session['username'] if request.form['submit'] == 'draft': post.visible = False db.session.add(post) db.session.commit() flash('Post create') except Exception as e: print(f'Something wrong\n{e.__class__}') raise e return redirect(url_for('posts.index')) elif not form.validate_on_submit(): print('validate: ', form.validate_on_submit()) else: return redirect('/log_in') return render_template('create_post.html', form=form)
def create(): form = RegistrationForm() if form.validate() is False: return render_template('blog/new.html', form=form) else: post = Post() post.title = form.title.data subject_query = PostSubject.query.filter_by(name=form.subject.data) if (subject_query.first()): post.subject_id = subject_query.first().id else: subject = PostSubject() subject.name = form.subject.data db.session.add(subject) db.session.commit() post.subject_id = subject.id post.author = form.author.data post.text_content = form.text_content.data post.text_call = form.text_call.data post.postage_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') post.thumb = form.thumb.data post.active = 0 db.session.add(post) db.session.commit() message = u'Muito obrigado! Seu post foi submetido com sucesso!' flash(message, 'success') return redirect(url_for('blog.admin'))
async def post(request: Request, ident): ident = ident.replace('+', ' ') if ident.isdigit(): post_data = await Post.cache(ident=int(ident)) else: post_data = await Post.get_by_slug(ident) if not post_data: raise HTMLResponse(status_code=404) post = Post(**post_data) stats = await post.stats reaction_type = None liked_comment_ids = [] github_user = request.session.get('github_user') pageview = await post.incr_pageview() related_posts = await post.get_related(limit=4) if github_user: reaction_type = await post.get_reaction_type(github_user['gid']) liked_comment_ids = await post.comment_ids_liked_by(github_user['gid']) post = await post.to_async_dict(**post_data) post.author = config.AttrDict(post.author) return { 'post': post, 'github_user': github_user, 'stats': stats, 'reaction_type': reaction_type, 'liked_comment_ids': liked_comment_ids, 'related_posts': related_posts, 'pageview': pageview }
def create_post_body(errors, form): new_post = Post() new_post.title = form.title.data new_post.text = form.text.data new_post.author = current_user for tag in form.tags.data: new_post.tags.append(Tag.query.filter(Tag.id == tag).first()) # FLUSH(to get post's id) try: db.session.add(new_post) db.session.flush() except: errors.append("Can't flush post id{}".format(new_post.id)) return errors # SAVE IMAGES args = {"post_id": new_post.id} errors = save_image_to_post(errors, form, args) if errors: return errors # COMMIT try: db.session.commit() except: errors.append("Can't save in db post id{}".format(new_post.id)) db.session.rollback() return errors
def create(): form = RegistrationForm() if form.validate() is False: return render_template('blog/new.html', form=form) else: post = Post() post.title = form.title.data post.author = form.author.data post.text_content = form.text_content.data post.text_call = form.text_call.data post.postage_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') post.active = 0 subjects_names = form.subject.data.replace(', ', ',').split(',') for name in subjects_names: subject = Subject.query.filter_by(name=name).first() if (not subject): subject = Subject() subject.name = name post.subjects.append(subject) db.session.add(post) db.session.flush() if len(form.thumb.data.split(',')) > 1: upload_folder = os.path.join(app.config['UPLOAD_FOLDER'], mod.name, str(post.id), 'images') post.thumb = save_b64_image(form.thumb.data.split(',')[1], upload_folder, 'thumb') db.session.commit() message = u'Muito obrigado! Seu post foi submetido com sucesso!' flash(message, 'success') return redirect(url_for('blog.admin'))
def home(request): """ codigo para ajax TOTAL = 5 OFFSET = int(request.GET.get('offset', 0)) END = OFFSET + TOTAL if request.method == 'GET' and request.is_ajax(): print "hola" posts = Post.objects.all()[OFFSET:END] json_list = [] for post in posts: json_list.append({ 'title': post.title, 'content': post.content,'id':post.id }) data = json.dumps(json_list) return HttpResponse(data,content_type='application/json') """ context = RequestContext(request) if request.method == 'POST': title = request.POST["title"] content = request.POST["content"] nPost = Post() nPost.title = title nPost.content = content nPost.publicated = True user = User.objects.get(pk=request.user.id) nPost.author = Author.objects.get(user=user) nPost.save() posts = Post.objects.all() context['posts'] = posts return render_to_response("index.html", context)
def post(self): ''' Send a json data as follow will create a new blog instance: { "title": "Title 1", "slug": "title-1", "abstract": "Abstract for this article", "raw": "The article content", "author": "Gevin", "category": "default", "tags": ["tag1", "tag2"] } ''' data = request.get_json() article = Post() article.title = data.get('title') article.slug = data.get('slug') article.abstract = data.get('abstract') article.raw = data.get('raw') article.author = data.get('author') article.category = data.get('category') article.tags = data.get('tags') article.save() return jsonify(article.to_dict())
def post(self): json_data = request.json errors = PostSchema_add().validate(json_data) if errors: return errors tags = json_data.get('tag') tags_list = [] for i in tags: tag = Tag.objects(name=i) if len(tag) == 0: tag = Tag(name=i).save() else: tag = tag[0] tags_list.append(tag) author_field = json_data.get('author') if author_field is None: return {'errors': 'Not field author'} author = Author.objects(first_name=author_field['first_name'], last_name=author_field['last_name']) if len(author) == 0: author = Author(first_name=author_field['first_name'], last_name=author_field['last_name']) author.save() else: author = author[0] try: p = Post(name=json_data.get('name'), description=json_data.get('description')) p.author = author p.tag = tags_list p.save() user_json = p.to_json() return json.loads(user_json) except (ValidationError, NotUniqueError) as errors: print(errors)
def post(self, title): if self.form.validate(): post = None if self.form.post_id.data: post = yield Post.asyncQuery(id=self.form.post_id.data).first() if post: post.modified_time = datetime.datetime.utcnow() else: post = Post() post.create_time = \ self.BeiJing2UTCTime(self.form.create_time.data) title = self.form.title.data.replace(' ', '-') content = self.form.content.data markdown_text = self.form.markdown.data tags = self.separate_tags(self.form.tags.data) category_str = self.form.category.data.capitalize() category = yield Category.asyncQuery(name=category_str).first() if not category: category = Category() category.name = category_str yield category.save() post.title = title post.content = content post.markdown = markdown_text post.category = category post.tags = tags post.author = self.current_user yield post.save() self.flash("compose finsh!") return self.redirect('/blog') self.render("compose.html", form=self.form)
def mutate(self, info, title, body, email): user = User.query.filter_by(email=email).first() post = Post(title=title, body=body) if user is not None: post.author = user db.session.add(post) db.session.commit() return CreatePost(post=post)
def mutate(self, info, **kwargs): user = User.query.filter_by(uuid=kwargs.get('author_uuid')).first() post = Post(title=kwargs.get('title'), body=kwargs.get('body')) if user is not None: post.author = user db.session.add(post) db.session.commit() return CreatePost(post=post)
def add_post(request): post_content = request.POST['post_content'] post_topic = Topic.objects.get(id=request.POST['topic_id']) newPost = Post() newPost.author = request.user newPost.content = post_content newPost.topic = post_topic newPost.save() return redirect('topic-detail', topic_id=post_topic.id)
def post(self): p = Post() p.author = users.get_current_user() p.content = self.request.get('content') p.title = self.request.get('title') if self.request.get('is_published', None): p.is_published = True p.put() self.redirect('/admin/blog')
def sign(request): form = GuestbookForm(request.POST) if form.is_valid(): post = Post(message=form.clean_data['message']) if users.GetCurrentUser(): post.author = users.GetCurrentUser() post.put() return HttpResponseRedirect('/')
def post(self): post = Post() post.author = User.get_by_id(self.session['user'].email) assert author post.commit = self.request.get('commit') post.image = self.get_uploads('image')[0].key() post.share = bool(self.get('share', False)) post.put() self.JsonResponse({"STATUS": "SUCCESS"})
def add_post(): post_data = request.get_json() new_post = Post(title=post_data['title']) new_post.body = post_data.get('body') new_post.author = post_data.get('author') new_post.comments = [] db.session.add(new_post) db.session.commit() return jsonify(new_post.to_dict()), 201
def post(): if not current_user.is_authenticated: flash('请先登录!') return redirect(url_for('login')) form = PostForm() if form.validate_on_submit(): # TODO: 文章名过长时的错误提示 post = Post(form.title.data, form.content.data) post.author = current_user db.session.add(post) db.session.commit() return redirect(url_for('index')) return render_template('post.html', form=form)
def mutate(self, info, title, body, username): user = User.query.filter_by(username=username).first() post = Post(title=title, body=body) if user is not None: post.author = user else: raise Exception('Invalid User!') db.session.add(post) db.session.commit() return CreatePost(post=post)
def get_posts_by_user(user_id): with sqlite3.connect("./rare.db") as conn: conn.row_factory = sqlite3.Row db_cursor = conn.cursor() db_cursor.execute(""" SELECT p.id, p.user_id, p.category_id, p.title, p.publication_date, p.content, p.approved, u.first_name, u.last_name, c.label, c.deleted FROM posts p JOIN users u ON u.id = p.user_id JOIN Categories c ON c.id = p.category_id WHERE p.user_id = ? ORDER BY p.publication_date """, (user_id)) posts = [] dataset = db_cursor.fetchall() for row in dataset: post = Post(row['id'], row['user_id'], row['category_id'], row['title'], row['publication_date'], row['content'], row['approved']) author = User(first_name=row['first_name'], last_name=row['last_name']) category = Category(row['category_id'], row['label'], row['deleted']) post.author = author.__dict__ post.category = category.__dict__ posts.append(post.__dict__) return json.dumps(posts)
def create_post(author_key, institution_key): """Create post.""" post = Post() post.author = author_key post.institution = institution_key post_hash = getHash(post) post.title = "title %s" % post_hash post.text = "text %s" % post_hash post.last_modified_by = author_key post.put() # update permissions author = author_key.get() author.add_permissions(["edit_post", "remove_post"], post.key.urlsafe()) author.put() post.put() return post
def createPost(): form = postForm() search = searchForm() categories = Category.query.all() if form.validate_on_submit(): post = Post() post.title = form.title.data.strip() post.subtitle = form.subtitle.data.strip() category = db.session.query(Category).filter_by(name=form.category.data).one() post.category = category post.author = current_user post.body = form.body.data.strip() post.tags = form.tags.data.strip() db.session.add(post) db.session.commit() flash('Post Created Successfully') return redirect( url_for('post', post_id = post.id) ) return render_template('newpost.html', form=form, search=search, categories=categories_, cat=categories)
def new_post(): author = User.get_current() title, content = request.form['title'], request.form['content'] tag_names = parse_tag_names(request.form['tags']) f = request.files['featuredImage'] if f.filename == '': featuredImage = None else: featuredImage = Attachment(f.filename, data=f.stream) if featuredImage and not allowed_file(featuredImage.extension): flash('warning', 'Upload a proper image.') return redirect(url_for('post_form')) post = Post() post.title = title post.content = content post.markedContent = markdown(content) post.author = author if featuredImage: post.featuredImage = featuredImage acl = ACL() acl.set_public_read_access(True) acl.set_write_access(author.id, True) post.set_acl(acl) post.save() tags = [] for name in tag_names: tag = Tag.get_by_name(name) if not tag: tag = Tag() tag.name = name tags.append(tag) for tag in tags: m = TagPostMap() m.set({'tag': tag, 'post': post}) m.save() tag.increment('post_count') Tag.save_all(tags) return redirect(url_for('show_post', post_id=post.id))
def home(request): user = request.user if user.is_authenticated(): if request.method == "POST": post = Post() post.post_title = request.POST['title'] post.post_body = request.POST['body'] post.post_time = timezone.now() post.author = request.user post.save() return redirect('/home') user_id = user.id post_list = Post.objects.all().order_by('-post_time') list = Profile.objects.get(profile_owner= user_id).image.thumbnail list_str = str(list)[7:] activity = Activity.objects.all().order_by('-activity_date') notice = Notice.objects.all() return render(request, 'network/home.html', {"posts": post_list, 'user': user, "profile" : list_str, "activities": activity, "notices":notice})
def create(): form = RegistrationForm() if form.validate() is False: form.set_choices() return render_template('blog/new.html', form=form) else: post = Post() post.title = form.title.data post.author = form.author.data post.text_call = form.text_call.data post.last_modification = datetime.now().strftime('%Y-%m-%d %H:%M:%S') post.publish_date = form.publish_date.data.strftime('%Y-%m-%d') post.show_home = form.show_home.data post.active = 0 post.language = form.language.data post.add_subjects(form.subject.data, form.language.data) if form.thumb_src.data: post.thumb_src = form.thumb_src.data db.session.add(post) db.session.flush() text_content = upload_images_to_s3(form.text_content.data, mod.name, post.id) Post.query.get(post.id).text_content = text_content clean_s3_folder(text_content, mod.name, post.id) if len(form.thumb.data.split(',')) > 1: upload_folder = os.path.join(app.config['UPLOAD_FOLDER'], mod.name, str(post.id), 'images') post.thumb = save_b64_image( form.thumb.data.split(',')[1], upload_folder, 'thumb') db.session.commit() log_operation(module=mod.name, operation='create', user=(g.user.id, g.user.email), objs=[(post.id, post.title)]) message = u'Muito obrigado! Seu post foi submetido com sucesso!' flash(message, 'success') return redirect(url_for('blog.admin'))
def mutate(root, info, id, title, content, category, tags, excerpt): """ Create the new post :param root: the root information :param info: information about the request :param id: the id corresponds to the post :param title: title of the post :param content: content of the post (in Markdown format) :param category: category of the post :param tags: a list of tags of the post :param excerpt: brief description about the post. :return: the new post, or None """ viewer = root.get("viewer") if not viewer or not viewer.isAdmin: raise GraphQLError("Permission denied") else: if id is None: post = PostModel() else: print("id", relay.Node.get_node_from_global_id(info, id)) post = relay.Node.get_node_from_global_id(info, id) tags = set(tags) # remove duplicate tags if title == "" or content == "" or category == "" or "" in tags: raise GraphQLError("Missing required fields") post.category = Category.get_query(info).filter_by( name=category).first() or CategoryModel(name=category) post.tags = [ Tag.get_query(info).filter_by(name=tag).first() or TagModel(name=tag) for tag in tags ] post.title = title post.content = content post.publishDate = post.publishDate or datetime.datetime.utcnow() post.lastUpdateDate = datetime.datetime.utcnow() post.author = viewer post.excerpt = excerpt db_session.add(post) db_session.commit() return SetPost(post=post)
def create_post(payload): form = PostForm(request.form) groups = Group.query.all() form.group.choices = [(g.id, g.name) for g in groups] if request.method == "POST": try: userinfo=session[constants.PROFILE_KEY] author = userinfo.get("name"), post = Post() form.populate_obj(post) post.group_id= request.form.get("group") post.author = author post.insert() return redirect (url_for("home")) except Exception as e: print(e) abort(400) return render_template("new_post.html", form=form)
def post(self): if self.request.get("key"): key = self.request.get("key") post = ndb.Key("Post", int(key)).get() else: post = Post() #if users.get_current_user(): # post.author = Post(author = users.get_current_user()) user = users.get_current_user() post.author = user post.contact_phone = self.request.get('contact') post.contact_email = self.request.get('email') post.title = self.request.get('title') post.description = self.request.get('description') post.price = self.request.get('price') post.category = self.request.get('category') if self.request.get('picture') == '': self.response.out.write('No image') else: post.picture = self.request.get('picture') post.put() self.redirect("/")
def post(self, title): if self.form.validate(): post = None if self.form.post_id.data: post = yield Post.asyncQuery(id=self.form.post_id.data).first() if post: post.modified_time = datetime.datetime.utcnow() else: post = Post() post.create_time = \ self.BeiJing2UTCTime(self.form.create_time.data) title = self.form.title.data.replace(' ', '-') content = self.form.content.data markdown_text = self.form.markdown.data tags = self.separate_tags(self.form.tags.data) category_str = self.form.category.data.capitalize() category = yield Category.asyncQuery( name=category_str).first() if not category: category = Category() category.name = category_str yield category.save() post.title = title post.content = content post.markdown = markdown_text post.category = category post.tags = tags post.author = self.current_user yield post.save() self.flash("compose finsh!") return self.redirect('/blog') self.render("compose.html", form=self.form)
def answer(request): """Adds an answer from a user to a topic.""" try: topic_pk = request.GET["sujet"] except KeyError: raise Http404 # Retrieve current topic. g_topic = get_object_or_404(Topic, pk=topic_pk) if not g_topic.forum.can_read(request.user): raise PermissionDenied # Making sure posting is allowed if g_topic.is_locked: raise PermissionDenied # Check that the user isn't spamming if g_topic.antispam(request.user): raise PermissionDenied last_post_pk = g_topic.last_message.pk # Retrieve 10 last posts of the current topic. posts = \ Post.objects.filter(topic=g_topic) \ .prefetch_related() \ .order_by("-pubdate" )[:10] # User would like preview his post or post a new post on the topic. if request.method == "POST": data = request.POST newpost = last_post_pk != int(data["last_post"]) # Using the « preview button », the « more » button or new post if "preview" in data or newpost: form = PostForm(g_topic, request.user, initial={"text": data["text" ]}) form.helper.form_action = reverse("zds.forum.views.answer") \ + "?sujet=" + str(g_topic.pk) return render_template("forum/post/new.html", { "text": data["text"], "topic": g_topic, "posts": posts, "last_post_pk": last_post_pk, "newpost": newpost, "form": form, }) else: # Saving the message form = PostForm(g_topic, request.user, request.POST) if form.is_valid(): data = form.data post = Post() post.topic = g_topic post.author = request.user post.text = data["text"] post.text_html = emarkdown(data["text"]) post.pubdate = datetime.now() post.position = g_topic.get_post_count() + 1 post.ip_address = get_client_ip(request) post.save() g_topic.last_message = post g_topic.save() #Send mail subject = "ZDS - Notification : " + g_topic.title from_email = "Zeste de Savoir <{0}>".format(settings.MAIL_NOREPLY) followers = g_topic.get_followers_by_email() for follower in followers: receiver = follower.user if receiver == request.user: continue pos = post.position - 1 last_read = TopicRead.objects.filter( topic=g_topic, post__position=pos, user=receiver).count() if last_read > 0: message_html = get_template('email/notification/new.html') \ .render( Context({ 'username': receiver.username, 'title':g_topic.title, 'url': settings.SITE_URL + post.get_absolute_url(), 'author': request.user.username }) ) message_txt = get_template('email/notification/new.txt').render( Context({ 'username': receiver.username, 'title':g_topic.title, 'url': settings.SITE_URL + post.get_absolute_url(), 'author': request.user.username }) ) msg = EmailMultiAlternatives( subject, message_txt, from_email, [ receiver.email]) msg.attach_alternative(message_html, "text/html") msg.send() # Follow topic on answering if not g_topic.is_followed(user=request.user): follow(g_topic) return redirect(post.get_absolute_url()) else: return render_template("forum/post/new.html", { "text": data["text"], "topic": g_topic, "posts": posts, "last_post_pk": last_post_pk, "newpost": newpost, "form": form, }) else: # Actions from the editor render to new.html. text = "" # Using the quote button if "cite" in request.GET: post_cite_pk = request.GET["cite"] post_cite = Post.objects.get(pk=post_cite_pk) if not post_cite.is_visible: raise PermissionDenied for line in post_cite.text.splitlines(): text = text + "> " + line + "\n" text = u"{0}Source:[{1}]({2}{3})".format( text, post_cite.author.username, settings.SITE_URL, post_cite.get_absolute_url()) form = PostForm(g_topic, request.user, initial={"text": text}) form.helper.form_action = reverse("zds.forum.views.answer") \ + "?sujet=" + str(g_topic.pk) return render_template("forum/post/new.html", { "topic": g_topic, "posts": posts, "last_post_pk": last_post_pk, "form": form, })
def new(request): """Creates a new topic in a forum.""" try: forum_pk = request.GET["forum"] except KeyError: raise Http404 forum = get_object_or_404(Forum, pk=forum_pk) if not forum.can_read(request.user): raise PermissionDenied if request.method == "POST": # If the client is using the "preview" button if "preview" in request.POST: form = TopicForm(initial={"title": request.POST["title"], "subtitle": request.POST["subtitle"], "text": request.POST["text"]}) return render_template("forum/topic/new.html", {"forum": forum, "form": form, "text": request.POST["text"]}) form = TopicForm(request.POST) data = form.data if form.is_valid(): # Treat title (tags, title) = get_tag_by_title(data["title"]) # Creating the thread n_topic = Topic() n_topic.forum = forum n_topic.title = title n_topic.subtitle = data["subtitle"] n_topic.pubdate = datetime.now() n_topic.author = request.user n_topic.save() # add tags n_topic.add_tags(tags) n_topic.save() # Adding the first message post = Post() post.topic = n_topic post.author = request.user post.text = data["text"] post.text_html = emarkdown(request.POST["text"]) post.pubdate = datetime.now() post.position = 1 post.ip_address = get_client_ip(request) post.save() n_topic.last_message = post n_topic.save() # Follow the topic follow(n_topic) return redirect(n_topic.get_absolute_url()) else: form = TopicForm() return render_template("forum/topic/new.html", {"forum": forum, "form": form})
def answer(request): """Adds an answer from a user to a topic.""" try: topic_pk = request.GET["sujet"] except: # problem in variable format raise Http404 # Retrieve current topic. g_topic = get_object_or_404(Topic, pk=topic_pk) if not g_topic.forum.can_read(request.user): raise PermissionDenied # Making sure posting is allowed if g_topic.is_locked: raise PermissionDenied # Check that the user isn't spamming if g_topic.antispam(request.user): raise PermissionDenied last_post_pk = g_topic.last_message.pk # Retrieve last posts of the current topic. posts = Post.objects.filter(topic=g_topic) \ .prefetch_related() \ .order_by("-pubdate")[:settings.POSTS_PER_PAGE] # User would like preview his post or post a new post on the topic. if request.method == "POST": data = request.POST newpost = last_post_pk != int(data["last_post"]) # Using the « preview button », the « more » button or new post if "preview" in data or newpost: form = PostForm(g_topic, request.user, initial={"text": data["text"]}) form.helper.form_action = reverse("zds.forum.views.answer") \ + "?sujet=" + str(g_topic.pk) return render_template("forum/post/new.html", { "text": data["text"], "topic": g_topic, "posts": posts, "last_post_pk": last_post_pk, "newpost": newpost, "form": form, }) else: # Saving the message form = PostForm(g_topic, request.user, request.POST) if form.is_valid(): data = form.data post = Post() post.topic = g_topic post.author = request.user post.text = data["text"] post.text_html = emarkdown(data["text"]) post.pubdate = datetime.now() post.position = g_topic.get_post_count() + 1 post.ip_address = get_client_ip(request) post.save() g_topic.last_message = post g_topic.save() #Send mail subject = "ZDS - Notification : " + g_topic.title from_email = "Zeste de Savoir <{0}>".format(settings.MAIL_NOREPLY) followers = g_topic.get_followers_by_email() for follower in followers: receiver = follower.user if receiver == request.user: continue pos = post.position - 1 last_read = TopicRead.objects.filter( topic=g_topic, post__position=pos, user=receiver).count() if last_read > 0: message_html = get_template('email/notification/new.html') \ .render( Context({ 'username': receiver.username, 'title':g_topic.title, 'url': settings.SITE_URL + post.get_absolute_url(), 'author': request.user.username }) ) message_txt = get_template('email/notification/new.txt').render( Context({ 'username': receiver.username, 'title':g_topic.title, 'url': settings.SITE_URL + post.get_absolute_url(), 'author': request.user.username }) ) msg = EmailMultiAlternatives( subject, message_txt, from_email, [ receiver.email]) msg.attach_alternative(message_html, "text/html") msg.send() # Follow topic on answering if not g_topic.is_followed(user=request.user): follow(g_topic) return redirect(post.get_absolute_url()) else: return render_template("forum/post/new.html", { "text": data["text"], "topic": g_topic, "posts": posts, "last_post_pk": last_post_pk, "newpost": newpost, "form": form, }) else: # Actions from the editor render to new.html. text = "" # Using the quote button if "cite" in request.GET: post_cite_pk = request.GET["cite"] post_cite = Post.objects.get(pk=post_cite_pk) if not post_cite.is_visible: raise PermissionDenied for line in post_cite.text.splitlines(): text = text + "> " + line + "\n" text = u"{0}Source:[{1}]({2}{3})".format( text, post_cite.author.username, settings.SITE_URL, post_cite.get_absolute_url()) form = PostForm(g_topic, request.user, initial={"text": text}) form.helper.form_action = reverse("zds.forum.views.answer") \ + "?sujet=" + str(g_topic.pk) return render_template("forum/post/new.html", { "topic": g_topic, "posts": posts, "last_post_pk": last_post_pk, "form": form, })
def new(request): """Creates a new topic in a forum.""" try: forum_pk = request.GET["forum"] except: # problem in variable format raise Http404 forum = get_object_or_404(Forum, pk=forum_pk) if not forum.can_read(request.user): raise PermissionDenied if request.method == "POST": # If the client is using the "preview" button if "preview" in request.POST: form = TopicForm(initial={"title": request.POST["title"], "subtitle": request.POST["subtitle"], "text": request.POST["text"]}) return render_template("forum/topic/new.html", {"forum": forum, "form": form, "text": request.POST["text"]}) form = TopicForm(request.POST) data = form.data if form.is_valid(): # Treat title (tags, title) = get_tag_by_title(data["title"]) # Creating the thread n_topic = Topic() n_topic.forum = forum n_topic.title = title n_topic.subtitle = data["subtitle"] n_topic.pubdate = datetime.now() n_topic.author = request.user n_topic.save() # add tags n_topic.add_tags(tags) n_topic.save() # Adding the first message post = Post() post.topic = n_topic post.author = request.user post.text = data["text"] post.text_html = emarkdown(request.POST["text"]) post.pubdate = datetime.now() post.position = 1 post.ip_address = get_client_ip(request) post.save() n_topic.last_message = post n_topic.save() # Follow the topic follow(n_topic) return redirect(n_topic.get_absolute_url()) else: form = TopicForm() return render_template("forum/topic/new.html", {"forum": forum, "form": form})
def parse_post(self, content, owner): from models import Post from vkontakte_users.models import User remote_id = content['id'][4:] try: instance = Post.objects.get(remote_id=remote_id) except Post.DoesNotExist: instance = Post(remote_id=remote_id) post_text = content.find('div', {'class': 'wall_post_text'}) if post_text: instance.text = post_text.text # date instance.date = self.parse_container_date(content) # likes instance.likes = self.parse_container_likes(content, 'post_like_count fl_l') # comments show_comments = content.find('div', {'class': 'wrh_text'}) if show_comments: comments_words = show_comments.text.split(' ') if len(comments_words) in [3, 4]: # Показать все 95 комментариев # Показать 91 комментарий instance.comments = int(comments_words[-2]) elif len(comments_words) == 6: # Показать последние 100 комментариев из 170 instance.comments = int(comments_words[-1]) else: raise VkontakteParseError( "Error number of words in show all comments message: '%s'" % show_comments.text.encode('utf-8')) else: instance.comments = len( content.findAll('div', {'class': 'reply_text'})) # author owner_slug = content.find('a', {'class': 'author'})['href'][1:] if owner and owner.screen_name == owner_slug: instance.author = owner else: # author is someone else, # possible user, becouse the group can post only on it's own wall, where owner is defined avatar = content.find('a', { 'class': 'post_image' }).find('img')['src'] name_parts = content.find('a', {'class': 'author'}).text.split(' ') user = get_object_by_slug(owner_slug) if user: user.first_name = name_parts[0] if len(name_parts) > 1: user.last_name = name_parts[1] user.photo = avatar user.save() instance.author = user instance.fetched = datetime.now() if owner: instance.owner = owner #<td> # <div class="published_by_title"><a class="published_by" href="/yullz">Yulya Tsareva</a> </div> # <div class="published_by_date"><a class="published_by_date" href="/wall59124156_8301" onclick="return showWiki({w: 'wall59124156_8301'}, false, event);" >29 янв 2013 в 15:51</a></div> #</td> try: slug = content.find('a', {'class': 'published_by'})['href'][1:] post_link = content.find('a', {'class': 'published_by_date'}) instance.copy_owner = get_object_by_slug(slug) instance.copy_post = Post.objects.get_or_create( remote_id=content.find( 'a', {'class': 'published_by_date'})['href'][5:], defaults={ 'owner': instance.copy_owner, 'date': self.parse_date(post_link.text) })[0] except: pass # <div class="published_comment wall_post_text">дядька молодец</div> copy_text = content.find('div', {'class': 'published_comment wall_post_text'}) if copy_text: instance.copy_text = copy_text.text post_parsed.send(sender=Post, instance=instance, raw_html=str(content)) return instance
app = create_app('application.config.DevelopmentConfig') app.app_context().push() user1 = User(name="Bob marlin ", email='*****@*****.**') user2 = User(name="Leonardo cohen", email='*****@*****.**') user3 = User(name="Chris deburge", email='*****@*****.**') db.session.add(user1) db.session.add(user2) db.session.add(user3) db.session.flush() post1 = Post() post1.title = "Blog Post Title 1" post1.body = "This is the first blog post 1" post1.author = user1 post1.user = user1 post2 = Post() post2.title = "Blog Post Title 2" post2.body = "This is the first blog post 2" post2.author = user2 post2.user = user2 db.session.add(post1) db.session.add(post2) db.session.commit() print(User.query.all()) print(Post.query.all())
def parse_post(self, content, wall_owner): from models import Post from vkontakte_users.models import User remote_id = content['id'][4:] try: instance = Post.objects.get(remote_id=remote_id) except Post.DoesNotExist: instance = Post(remote_id=remote_id) post_text = content.find('div', {'class': 'wall_post_text'}) if post_text: instance.text = post_text.text # date instance.date = self.parse_container_date(content) # likes instance.likes = self.parse_container_likes(content, 'post_like_count fl_l') # comments show_comments = content.find('div', {'class': 'wrh_text'}) if show_comments: comments_words = show_comments.text.split(' ') if len(comments_words) in [3,4]: # Показать все 95 комментариев # Показать 91 комментарий instance.comments = int(comments_words[-2]) elif len(comments_words) == 6: # Показать последние 100 комментариев из 170 instance.comments = int(comments_words[-1]) else: raise VkontakteParseError("Error number of words in show all comments message: '%s'" % show_comments.text.encode('utf-8')) else: instance.comments = len(content.findAll('div', {'class': 'reply_text'})) # author owner_slug = content.find('a', {'class': 'author'})['href'][1:] if wall_owner and wall_owner.screen_name == owner_slug: instance.author = wall_owner else: # author is someone else, # possible user, becouse the group can post only on it's own wall, where wall_owner is defined avatar = content.find('a', {'class': 'post_image'}).find('img')['src'] name_parts = content.find('a', {'class': 'author'}).text.split(' ') user = get_object_by_slug(owner_slug) if user: user.first_name = name_parts[0] if len(name_parts) > 1: user.last_name = name_parts[1] user.photo = avatar user.save() instance.author = user instance.fetched = datetime.now() if wall_owner: instance.wall_owner = wall_owner #<td> # <div class="published_by_title"><a class="published_by" href="/yullz">Yulya Tsareva</a> </div> # <div class="published_by_date"><a class="published_by_date" href="/wall59124156_8301" onclick="return showWiki({w: 'wall59124156_8301'}, false, event);" >29 янв 2013 в 15:51</a></div> #</td> try: slug = content.find('a', {'class': 'published_by'})['href'][1:] post_link = content.find('a', {'class': 'published_by_date'}) instance.copy_owner = get_object_by_slug(slug) instance.copy_post = Post.objects.get_or_create(remote_id=content.find('a', {'class': 'published_by_date'})['href'][5:], defaults={ 'wall_owner': instance.copy_owner, 'date': self.parse_date(post_link.text) })[0] except: pass # <div class="published_comment wall_post_text">дядька молодец</div> copy_text = content.find('div', {'class': 'published_comment wall_post_text'}) if copy_text: instance.copy_text = copy_text.text post_parsed.send(sender=Post, instance=instance, raw_html=str(content)) return instance
def get(self): """Reset entities.""" Utils._assert( self.request.host in [ "backend.plataformacis.org", "backend.eciis-splab.appspot.com" ], "The production environment can not be redefined", NotAuthorizedException) clear_data_store() self.response.headers[ 'Content-Type'] = 'application/json; charset=utf-8' response = {"msg": "Datastore Cleaned"} self.response.write(json.dumps(response)) # Initialize the datastore jsonList = [] # new User Mayza mayza = User() mayza.name = 'Mayza Nunes' mayza.cpf = '089.675.908-90' mayza.email = ['*****@*****.**'] mayza.photo_url = getGravatar(mayza.email) mayza.state = 'active' mayza.put() # new User Maiana maiana = User() maiana.name = 'Maiana Brito' maiana.cpf = '089.675.908-65' maiana.email = ['*****@*****.**'] maiana.photo_url = getGravatar(maiana.email) maiana.state = 'active' maiana.put() # new User Raoni raoni = User() raoni.name = 'Raoni Smaneoto' raoni.cpf = '089.675.908-65' raoni.email = ['*****@*****.**'] raoni.photo_url = getGravatar(raoni.email) raoni.state = 'active' raoni.put() # new User Luiz luiz = User() luiz.name = 'Luiz Silva' luiz.cpf = '089.675.908-65' luiz.email = ['*****@*****.**'] luiz.photo_url = getGravatar(luiz.email) luiz.state = 'active' luiz.put() # new User Ruan ruan = User() ruan.name = 'Ruan Silveira' ruan.cpf = '089.675.908-65' ruan.email = ['*****@*****.**'] ruan.photo_url = getGravatar(ruan.email) ruan.state = 'active' ruan.put() # new User Tiago tiago = User() tiago.name = 'Tiago Pereira' tiago.cpf = '089.675.908-65' tiago.email = ['*****@*****.**'] tiago.photo_url = getGravatar(tiago.email) tiago.state = 'active' tiago.put() # new User Admin admin = User() admin.name = 'Administrador da Plataforma Virtual CIS' admin.cpf = '000.000.000-01' admin.email = ['*****@*****.**', '*****@*****.**'] admin.photo_url = "app/images/avatar.png" admin.state = 'active' admin.put() # new User Other Admin other_admin = User() other_admin.name = 'Teste Admin' other_admin.cpf = '089.675.908-65' other_admin.email = ['*****@*****.**', '*****@*****.**'] other_admin.photo_url = "app/images/avatar.png" other_admin.state = 'active' other_admin.put() jsonList.append({"msg": "database initialized with a few users"}) # new Institution Ministério da Saúde address_data = { 'street': 'Esplanada dos Ministérios Bloco G ', 'neighbourhood': 'Zona Cívico-Administrativa', 'city': 'Brasília', 'cep': '70058-900 ', 'federal_state': 'Distrito Federal', 'country': 'Brasil' } address_key = Address.create(address_data) data = { 'name': 'Ministério da Saúde', 'acronym': 'MS', 'legal_nature': 'PUBLIC', 'address': address_key, 'actuation_area': 'GOVERNMENT_AGENCIES', 'description': 'Ministério da Saúde', 'photo_url': 'https://i1.wp.com/notta.news/wp-content/uploads/2017/08/tbg_20170713080909_62787.jpg?w=1024', 'email': '*****@*****.**', 'phone_number': '61 3315-2425', 'state': 'active', 'institutional_email': '*****@*****.**', 'leader': ' Ministro Ricardo Barros', } data_deciis = { 'name': 'Departamento do Complexo Industrial e Inovação em Saúde', 'acronym': 'DECIIS', 'legal_nature': 'PUBLIC', 'address': address_key, 'actuation_area': 'GOVERNMENT_AGENCIES', 'description': 'Departamento do Complexo Industrial e Inovação em Saúde', 'photo_url': 'http://www.plataformacis.org/images/logo.png', 'email': '*****@*****.**', 'state': 'active', 'institutional_email': '*****@*****.**', 'leader': ' Ministro Ricardo Barros' } ms = createInstitution(data, admin) deciis = createInstitution(data_deciis, admin) deciis.trusted = True for user in [ mayza, maiana, luiz, raoni, ruan, tiago, admin, other_admin ]: user.follow(deciis.key) user.follow(ms.key) deciis.follow(user.key) ms.follow(user.key) deciis.put() ms.put() admin.add_permissions(permissions.DEFAULT_ADMIN_PERMISSIONS, ms.key.urlsafe()) create_profile(admin, ms) admin.add_permissions(permissions.DEFAULT_ADMIN_PERMISSIONS, deciis.key.urlsafe()) admin.add_permissions(permissions.DEFAULT_SUPER_USER_PERMISSIONS, deciis.key.urlsafe()) create_profile(admin, deciis) admin.put() address_data = { 'number': '882', 'street': 'Avenida Aprígio Veloso', 'neighbourhood': 'Universitário', 'city': 'Campina Grande', 'federal_state': 'Paraíba', 'cep': '58428-830', 'country': 'Brasil' } address_key = Address.create(address_data) data = { 'name': 'Laboratório de Avaliação e Desenvolvimento de Biomateriais do Nordeste', 'acronym': 'CERTBIO', 'cnpj': '18.104.068/0001-86', 'legal_nature': 'PUBLIC', 'address': address_key, 'actuation_area': 'RESEARCH_INSTITUTE', 'description': 'Ensaio Químico - Determinação de Material Volátil por Gravimetria e Ensaio Biológico - Ensaio de Citotoxicidade', 'photo_url': 'https://pbs.twimg.com/profile_images/1782760873/Logo_do_site_400x400.jpg', 'email': '*****@*****.**', 'institutional_email': '*****@*****.**', 'phone_number': '83 3322-4455', 'state': 'active', 'leader': 'User' } certbio = createInstitution(data, other_admin) for user in [mayza, other_admin]: certbio.add_member(user) user.add_institution(certbio.key) user.follow(certbio.key) create_profile(user, certbio) for user in [mayza, maiana, luiz, raoni, ruan, tiago, other_admin]: certbio.follow(user.key) user.follow(certbio.key) address_data = { 'number': '1445', 'street': 'Rua Dom Pedro II', 'neighbourhood': 'Prata', 'city': 'Campina Grande', 'cep': '58400-565', 'federal_state': 'Paraíba', 'country': 'Brasil' } address_key = Address.create(address_data) data = { 'name': 'Software Practice Laboratory', 'acronym': 'SPLAB', 'cnpj': '18.104.068/0001-56', 'legal_nature': 'PUBLIC', 'address': address_key, 'actuation_area': 'COLLEGE', 'description': """The mission of the Software Practices Laboratory (SPLab) is to promote the development of the state-of-the-art in the theory and practice of Software Engineering.""", 'email': '*****@*****.**', 'institutional_email': '*****@*****.**', 'phone_number': '83 3322-7865', 'state': 'active', 'leader': 'User' } splab = createInstitution(data, other_admin) for user in [other_admin]: splab.add_member(user) user.add_institution(splab.key) user.follow(splab.key) create_profile(user, splab) for user in [maiana, luiz, raoni, ruan, tiago, other_admin]: splab.follow(user.key) user.follow(splab.key) # new Institution eciis address_data = { 'number': '456', 'street': 'Rua Francisco Lopes', 'neighbourhood': 'Centenário', 'city': 'Campina Grande', 'cep': '58428-080', 'federal_state': 'Paraíba', 'country': 'Brasil' } address_key = Address.create(address_data) data = { 'name': 'Complexo Industrial da Saude', 'acronym': 'e-ciis', 'cnpj': '18.104.068/0001-30', 'legal_nature': 'PUBLIC', 'address': address_key, 'actuation_area': 'COLLEGE', 'description': 'The mission of the e-CIIS is to promote the development of the state-of-the-art in the theory and practice of Software Engineering.', 'photo_url': 'http://www.paho.org/bra/images/stories/BRA01A/logobireme.jpg', 'email': '*****@*****.**', 'institutional_email': '*****@*****.**', 'phone_number': '83 3322-7865', 'state': 'active', 'leader': 'User' } eciis = createInstitution(data, other_admin) for user in [maiana, luiz, raoni, ruan, tiago, mayza, other_admin]: eciis.add_member(user) user.add_institution(eciis.key) user.follow(eciis.key) create_profile(user, eciis) for user in [mayza, maiana, luiz, raoni, ruan, tiago, other_admin]: eciis.follow(user.key) eciis.parent_institution = splab.key eciis.put() splab.children_institutions = [eciis.key] splab.put() jsonList.append( {"msg": "database initialized with a few institutions"}) other_admin.institutions_admin = [certbio.key, eciis.key, splab.key] other_admin.add_permissions(permissions.DEFAULT_ADMIN_PERMISSIONS, certbio.key.urlsafe()) other_admin.add_permissions(permissions.DEFAULT_ADMIN_PERMISSIONS, splab.key.urlsafe()) other_admin.add_permissions(permissions.DEFAULT_ADMIN_PERMISSIONS, eciis.key.urlsafe()) other_admin.put() # POST of Mayza To Certbio Institution mayza_post = Post() mayza_post.title = "Novo edital do CERTBIO" mayza_post.text = TEXT mayza_post.author = mayza.key mayza_post.institution = certbio.key mayza_post.last_modified_by = mayza.key mayza_post.put() add_comments_to_post(mayza, maiana, mayza_post, mayza.institutions[0], 2) mayza.add_permissions(['edit_post', 'remove_post'], mayza_post.key.urlsafe()) # POST of Mayza To Certbio Institution with image post_with_image = Post() post_with_image.title = "Post do CERTBIO com imagem" post_with_image.photo_url = "https://workingatbooking.com/content/uploads/2017/04/womenintech_heroimage.jpg" post_with_image.text = TEXT post_with_image.author = mayza.key post_with_image.institution = certbio.key post_with_image.last_modified_by = mayza.key post_with_image.put() add_comments_to_post(mayza, raoni, post_with_image, mayza.institutions[0], 1) mayza.add_permissions(['edit_post', 'remove_post'], post_with_image.key.urlsafe()) # Side efect of a post mayza.posts = [mayza_post.key, post_with_image.key] mayza.put() eciis.posts = [] eciis.put() certbio.posts = [mayza_post.key] certbio.put() splab.posts = [] splab.put() jsonList.append({"msg": "database initialized with a few posts"}) self.response.write(json.dumps(jsonList))
def answer(request): ''' Adds an answer from a user to a topic ''' try: topic_pk = request.GET['sujet'] except KeyError: raise Http404 g_topic = get_object_or_404(Topic, pk=topic_pk) if not g_topic.forum.can_read(request.user): raise Http404 posts = Post.objects.filter(topic=g_topic).order_by('-pubdate')[:3] last_post_pk = g_topic.last_message.pk # Making sure posting is allowed if g_topic.is_locked: raise Http404 # Check that the user isn't spamming if g_topic.antispam(request.user): raise Http404 # If we just sent data if request.method == 'POST': data = request.POST newpost = last_post_pk != int(data['last_post']) # Using the « preview button », the « more » button or new post if 'preview' in data or 'more' in data or newpost: return render_template( 'forum/answer.html', { 'text': data['text'], 'topic': g_topic, 'posts': posts, 'last_post_pk': last_post_pk, 'newpost': newpost }) # Saving the message else: form = PostForm(request.POST) if form.is_valid() and data['text'].strip() != '': data = form.data post = Post() post.topic = g_topic post.author = request.user post.text = data['text'] post.text_html = emarkdown(data['text']) post.pubdate = datetime.now() post.position = g_topic.get_post_count() + 1 post.ip_address = get_client_ip(request) post.save() g_topic.last_message = post g_topic.save() # Follow topic on answering if not g_topic.is_followed(): follow(g_topic) return redirect(post.get_absolute_url()) else: raise Http404 else: text = '' # Using the quote button if 'cite' in request.GET: post_cite_pk = request.GET['cite'] post_cite = Post.objects.get(pk=post_cite_pk) for line in post_cite.text.splitlines(): text = text + '> ' + line + '\n' text = u'**{0} a écrit :**\n{1}\n'.format( post_cite.author.username, text) return render_template( 'forum/answer.html', { 'topic': g_topic, 'text': text, 'posts': posts, 'last_post_pk': last_post_pk })
def new(request): ''' Creates a new topic in a forum ''' try: forum_pk = request.GET['forum'] except KeyError: raise Http404 forum = get_object_or_404(Forum, pk=forum_pk) if request.method == 'POST': # If the client is using the "preview" button if 'preview' in request.POST: return render_template( 'forum/new.html', { 'forum': forum, 'title': request.POST['title'], 'subtitle': request.POST['subtitle'], 'text': request.POST['text'], }) form = TopicForm(request.POST) if form.is_valid() and data['text'].strip() != '': data = form.data # Creating the thread n_topic = Topic() n_topic.forum = forum n_topic.title = data['title'] n_topic.subtitle = data['subtitle'] n_topic.pubdate = datetime.now() n_topic.author = request.user n_topic.save() # Adding the first message post = Post() post.topic = n_topic post.author = request.user post.text = data['text'] post.text_html = emarkdown(request.POST['text']) post.pubdate = datetime.now() post.position = 1 post.ip_address = get_client_ip(request) post.save() n_topic.last_message = post n_topic.save() # Follow the topic follow(n_topic) return redirect(n_topic.get_absolute_url()) else: # TODO: add errors to the form and return it raise Http404 else: form = TopicForm() return render_template('forum/new.html', { 'form': form, 'forum': forum })