当前位置: 首页>>代码示例>>Python>>正文


Python model.Post类代码示例

本文整理汇总了Python中model.Post的典型用法代码示例。如果您正苦于以下问题:Python Post类的具体用法?Python Post怎么用?Python Post使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Post类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: post

  def post(self):
    user = self.getAuthentificatedUser()
    if not user:
      return
    try:
      id = int(self.request.get('post_id'))
      post = Post().get(db.Key.from_path('Post', id))
      if post.author != user:
        self.redirect('/')
        return
      body = db.Text(strip_ml_tags(self.request.get('body')))
      postmarkup = create(use_pygments=False)
      post.body = postmarkup(body)
      # replace('\n','<br />')
      if post.body != '':
        post.put()
          # re-index it!
        ix = getdatastoreindex("post_"+str(post.key().id()), schema=SEARCHSCHEMA)
        writer = ix.writer()
        writer.add_document(body=u"%s" % post.body)
        writer.commit()   
    except:
      pass
 
    if self.request.get('page'):
      self.redirect('/view?id=' + str(self.request.get('id')) + '&page=' + self.request.get('page'))
    else:
      self.redirect('/view?id=' + str(self.request.get('id')))
开发者ID:itsredwan,项目名称:tunedforum,代码行数:28,代码来源:main.py

示例2: get

    def get(self, path):
        gdict = self.GET
        path = urllib.unquote(path)
        if path == config.FEED_SRC: #FEED
            self.set_content_type("atom")
            posts = Post.get_feed_post(config.FEED_NUMBER) 
            self.render("feed.xml", {"posts": posts })
            return

        post = Post.get_by_path(path)
        if post:
            p = gdict.get("p", None)
            p = int(p) if p and p.isdigit() else 1

            def post_comment_filter(query):
                query = query.filter("belong =", post)
                if config.COMMENT_NEEDLOGINED:
                    query = query.filter("hashcheck =", True)
                query = query.order("date_created")
                return query

            post_comments = Comment.fetch_page(p, config.COMMENT_PAGE_COUNT, func=post_comment_filter, realtime_count=True)
            context = {"post": post,
                       "post_comments": post_comments, } 
            self.render("single.html", context)
            return 
开发者ID:dreampuf,项目名称:bana,代码行数:26,代码来源:blog_views.py

示例3: get

 def get(self, *post_id):
     self.response.headers['Content-Type'] = 'application/json; charset=UTF-8'
     if post_id:
         post = Post.get_by_id(int(post_id[0]))
         self.write(json.dumps(post.to_dict()))
     else:
         posts_query = Post.all().order('-created')
         posts = posts_query.fetch(10)
         self.write(json.dumps([p.to_dict() for p in posts]))
开发者ID:jamespullar,项目名称:cs253,代码行数:9,代码来源:main.py

示例4: post

 def post(self, subdomain, lense=None):
     if self.request.headers['Content-type'] == 'application/json':
         post = Post(**json.loads(self.request.body))
         post.prefix = self.request.uri
         post.author = self.current_user
         post.save(db=self.db)
         self.set_header('Location', post.url)
         self.set_status(201)
     else:
         self.send_error(500)
开发者ID:palimadra,项目名称:dustbin,代码行数:10,代码来源:app.py

示例5: get

  def get(self):
    self.user()
    (forum, siteroot, tmpldir) = forum_siteroot_tmpldir_from_url(self.request.path_info)
    if not forum or forum.is_disabled:
      return self.redirect("/")
    forum.title_or_url = forum.title or forum.url

    topic_id = self.request.get('id')
    if not topic_id:
      return self.redirect(siteroot)

    topic = db.get(db.Key.from_path('Topic', int(topic_id)))
    if not topic:
      return self.redirect(siteroot)

    # is_moderator = users.is_current_user_admin()
    is_moderator = False
    if topic.is_deleted and not is_moderator:
      return self.redirect(siteroot)

    is_archived = False
    # Note: auto-archiving disabled
    #now = datetime.datetime.now()
    #week = datetime.timedelta(days=7)
    #week = datetime.timedelta(seconds=7)
    #if now > topic.created_on + week:
    #  is_archived = True

    # 200 is more than generous
    MAX_POSTS = 200
    if is_moderator:
      posts = Post.gql("WHERE forum = :1 AND topic = :2 ORDER BY created_on", forum, topic).fetch(MAX_POSTS)
    else:
      posts = Post.gql("WHERE forum = :1 AND topic = :2 AND is_deleted = False ORDER BY created_on", forum, topic).fetch(MAX_POSTS)

    if is_moderator:
      for p in posts:
        if 0 != p.user_ip:
          p.user_ip_str = long2ip(p.user_ip)
        if p.user_homepage:
          p.user_homepage = sanitize_homepage(p.user_homepage)

    tvals = {
      'role': self.role,
      'username': self.username,
      'siteroot' : siteroot,
      'forum' : forum,
      'analytics_code' : forum.analytics_code or "",
      'topic' : topic,
      'is_moderator' : is_moderator,
      'is_archived' : is_archived,
      'posts' : posts
    }
    tmpl = os.path.join("templates/topic.html")
    self.template_out(tmpl, tvals)
开发者ID:ignovak,项目名称:uarat,代码行数:55,代码来源:main.py

示例6: post_add

def post_add():
    if request.method == "POST":
        post = Post(request.form["author"], request.form["title"], request.form["content"], request.form["published"])
        post_add = post.add(post)
        if not post_add:
            flash("Add was successful")
            return redirect(url_for("post_index"))
        else:
            error = post_add
            flash(error)
    return render_template("add.html")
开发者ID:nausheenfatma,项目名称:WebAppWithFlask,代码行数:11,代码来源:controller.py

示例7: get

def get(name=None):
	if name == None:
		posts = Post.all()
		posts.order('-date_create')
		return render_template('index.html', posts=posts)
	else:
		try:
			post = Post.all().filter('url', name).get()
			return render_template('read_post.html', post=post)
		except:
			abort(404)
开发者ID:Algy,项目名称:micro-blog,代码行数:11,代码来源:views.py

示例8: load

 def load(self):
     import os
     from model import Post
     posts_dir = os.path.join(self.dir, 'posts')
     for name in os.listdir(posts_dir):
         path = os.path.join(posts_dir, name)
         post = Post(path)
         if post.is_draft():
             self.draft_posts.append(post)
         else:
             self.posts.append(post)
     self.loaded = True
开发者ID:rklyne,项目名称:blog-code,代码行数:12,代码来源:dataset.py

示例9: add_entry

def add_entry():
    if not session.get('logged_in'):
        abort(401)

    entry = Post(request.form['title'], request.form['text'], session['user_id'], datetime.now())
    if request.files['picture']:
        entry.set_image(request.files['picture'])
    db.session.add(entry)
    db.session.commit()

    flash('New entry was successfully posted')
    return redirect(url_for('show_entries'))
开发者ID:Flaw,项目名称:MicroBlog,代码行数:12,代码来源:microblog.py

示例10: get

    def get(self, category, page=1):
        page = int(page)
        category = category[:-1]
        count, data = Post.get_post(page=page, pagesize=blogconfig['pagesize'], category=category)

        self.datamap['recent'] = Post.get_recent_post()
        self.datamap['count'] = count
        self.datamap['data'] = data
        self.datamap['pageurl'] = 'category'
        self.datamap['page'] = page
        self.datamap['pagecount'] = int(math.ceil(float(count) / blogconfig['pagesize']))
        rtn = render.blog_index(self.datamap)
        self.write(rtn)
        return rtn
开发者ID:yibin001,项目名称:pyblog,代码行数:14,代码来源:blog.py

示例11: post

    def post(self):
        subject = self.request.get("subject")
        content = self.request.get("content")

        if subject and content:
            post = Post(subject = subject, content = content)
            post.put()
            memcache.set('time', time.time())

            post_id = post.key().id()

            self.redirect("/%i" % post_id)
        else:
            error = "both subject and content required to post"
            self.render_page(error = error, subject = subject, content = content)
开发者ID:jamespullar,项目名称:cs253,代码行数:15,代码来源:main.py

示例12: PostForm

class PostForm(Form):
	title = TextField('Titulo:', [
		validators.Length(min=5, max=60, message="O Titulo deve ter entre 5 a 60 caracteres.")
	])
	text =  TextAreaField('Texto:', [
		validators.Length(min=5, message="O Texto deve ter no minimo 5 caracteres.")
	])
	tags = TextField('Tags:',[
		validators.required(message="Informe uma tag.")
	])
		
	def __init__(self, model_instance = None, *args, **kwargs):
		"""Método construtor da classe, preenche model ao criar form."""
		kwargs['csrf_enabled'] = False
		super(PostForm, self).__init__(*args, **kwargs)
		self.model = None
		if model_instance:
			self.title.data = model_instance.title
			self.text.data = model_instance.text
			self.tags.data = self.get_tags( model_instance.tags )
			self.model = model_instance
			 
	def save(self):
		"""Método responsável em salvar post no bigtable."""
		if self.model:
			self.model.title = self.title.data
			self.model.text = self.text.data
			self.model.tags = self.set_tags(self.tags.data)
		else:	
			self.model = Post(
							title = self.title.data,
							text = self.text.data,
							tags = self.set_tags(self.tags.data)
						)
		self.model.put()
		return self.model

	def get_tags(self, tags):
		"""Metodo que recupera valor do atributo tags."""
		tstr = ""
		for tag in tags:
			tstr += "%s," % tag
		return tstr[:-1]

	def set_tags(self, tags):
		"""Método que define valor para o atributo tags."""
		tag = TagCategory()
		return tag.string_to_category( tags )	
开发者ID:Algy,项目名称:micro-blog,代码行数:48,代码来源:forms.py

示例13: run

	def run(self):
		if not self.options.file:
			raise Exception("Missing an argument")

		print "File name:", self.options.file

		existing = Post.by_file(self.options.file)
		if existing:
			content = open(self.options.file).read()

			# validate that it's markdown
			md = markdown.Markdown(extensions=['meta', 'codehilite'])
			md.convert(content)

			existing.markdown_content = content

			st = os.stat(self.options.file)
			existing.time_modified = datetime.datetime.fromtimestamp(st[stat.ST_MTIME])

			meta.session.add(existing)
			meta.session.commit()

			print "updated blog post %s" % existing
		else:
			post = Post(self.options.file)
			meta.session.add(post)
			meta.session.commit()

			print "Added blog post %s" % meta.session.query(Post).filter(Post.id == post.id).all()
开发者ID:fudong1127,项目名称:roaring-tofu,代码行数:29,代码来源:add_post.py

示例14: post

    def post(self, postId):
        title = self.get_argument('title', '')
        content = self.get_argument('content', '', strip=False)
        status = self.get_argument('status', 0)
        tag = self.get_arguments('tag', [])
        category = self.get_arguments('category', [])
        input_category = self.get_argument('input_category', '')
        input_tag = self.get_argument('input_tag', '')
        posttype = self.get_argument('posttype', 0)
        alias = self.get_argument('alias', '')
        tag = list(set(tag + input_tag.split(',')))
        category = list(set(category + input_category.split(',')))
        commentstatus = self.get_argument('commentstatus', 0)
        password = self.get_argument('password', '')

        if title == '' or content == '':
            self.datamap['message'] = u'标题与内容不能为空'
        else:
            rtn = Post.edit_post(id=postId, title=title, content=content, status=status, commentstatus=commentstatus,
                                 password=password, tag=tag, category=category, posttype=posttype, alias=alias)
            if rtn:
                self.flash(u'修改成功')
            else:
                self.flash(u'修改失败')
            self.redirect('/admin/post/edit/' + postId + '/')
开发者ID:yibin001,项目名称:pyblog,代码行数:25,代码来源:admin.py

示例15: get

    def get(self):
        page = int(self.get_argument('page', '1'))
        key = self.get_argument('key', '')
        act = self.get_argument('act', '')
        if act == 'delete':
            Post.delete_post_by_id(int(self.get_argument('id', 0)))
        pagesize = 20
        count, blogs = Post.get_post(page=page, pagesize=pagesize, showall=True, keyword=key, onlypost=False)

        for x in blogs:
            x.length = len(x.content)
        self.datamap['count'] = count
        self.datamap['posts'] = blogs
        self.datamap['page'] = int(page)
        self.datamap['pagecount'] = int(math.ceil(float(count) / pagesize))
        self.write(render_admin.post(self.datamap))
开发者ID:yibin001,项目名称:pyblog,代码行数:16,代码来源:admin.py


注:本文中的model.Post类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。