def post(self): sender = self.request.GET.get("from", "") if sender == blogSystem.postEmailAddr: msg = Message(self.request.body) blogEntity = Blog(title = msg.data["email-subject"], content = msg.data["email-text"], createTimeStamp = datetime.now()) blogEntity.publish() return
async def index(request): summary = "This is the test sumary." #users=await User.findAll() blogs = [ Blog(id='1', name='test Blog', summary=summary, create_at=time.time() - 120), Blog(id='2', name='something new', summary=summary, create_at=time.time() - 3600), Blog(id='3', name='learn Switf', summary=summary, create_at=time.time() - 7200) ] cookie_str = request.cookies.get(COOKIE_NAME) user = '' if cookie_str: if 'deleted' in cookie_str: user = '' else: user = await cookie2user(cookie_str) return {'__template__': 'blogs.html', 'blogs': blogs, 'user': user}
def get(self): recentComments = Comment.all().order('-commentTime').fetch(10) recentBlogs = Blog.all().order('-createTimeStamp').fetch(5) links = Link.all() template_values = { 'recentComments': recentComments, 'recentBlogs': recentBlogs, 'links': links } blogid = self.param('p') if (blogid): blogid = int(blogid) blogs = Blog.all().filter('blog_id =', blogid).fetch(1) blog = blogs[0] comments = Comment.all().filter("ownerBlog =", blog).order('commentTime') template_values.update({'blog': blog, 'comments': comments}) self.generateBasePage('singleblog.html', template_values) else: pageIndex = self.param('page') if (pageIndex): pageIndex = int(pageIndex) else: pageIndex = 1 blogs = Blog.all().order('-createTimeStamp') pager = PageManager(query=blogs, items_per_page=blogSystem.posts_per_page) blogs, links = pager.fetch(pageIndex) template_values.update({'blogs': blogs, 'pager': links}) self.generateBasePage('main.html', template_values) return
async def index(request): """首页""" summary = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' blogs = [ Blog(id='1', name='Test Blog', summary=summary, created_at=time.time() - 120), Blog(id='2', name='Something New', summary=summary, created_at=time.time() - 3600), Blog(id='3', name='Learn Swift', summary=summary, created_at=time.time() - 7200) ] user = None try: cookie_str = request.cookies.get(COOKIE_NAME) if 'deleted' not in cookie_str: user = await cookie2user(cookie_str) except: pass return {'__template__': 'blogs.html', 'blogs': blogs, '__user__': user}
def index(request): # users = await User.findAll() # return { # '__template__' : 'test.html', # 'users': users # } summary = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' blogs = [ Blog(id='1', name='Test Blog', summary=summary, created_at=time.time() - 120), Blog(id='2', name='Something New', summary=summary, created_at=time.time() - 3600), Blog(id='3', name='Learn Swift', summary=summary, created_at=time.time() - 7200) ] return { '__template__': 'blogs.html', 'blogs': blogs, # '__user__':request.__user__ }
def api_blogs(*, page='1'): page_index = get_page_index(page) num = yield from Blog.findNumber('count(id)') p = Page(num, page_index) if num == 0: return dict(page=p, blogs=()) blogs = yield from Blog.findAll(orderBy='created_at desc', limit=(p.offset, p.limit)) return dict(page=p, blogs=blogs)
def api_blogs(*,page='1'): page_index = get_page_index(page) num = yield from Blog.findNumber('count(id)') p = Page(num,page_index) if num == 0: return dict(page=p,blogs = ()) blogs = yield from Blog.findAll(orderBy='created_at desc',limit=(p.offset,p.limit)) return dict(page = p,blogs=blogs)
def post(self): sender = self.request.GET.get("from", "") if sender == blogSystem.postEmailAddr: msg = Message(self.request.body) blogEntity = Blog(title=msg.data["email-subject"], content=msg.data["email-text"], createTimeStamp=datetime.now()) blogEntity.publish() return
def index(*, page='1'): page_index = get_page_index(page) num = yield from Blog.findNumber('count(id)') page = Page(num) if num == 0: blogs = [] else: blogs = yield from Blog.findAll(orderBy='created_at desc', limit=(page.offset, page.limit)) return {'__template__': 'blogs.html', 'page': page, 'blogs': blogs}
async def test_index(): """ test_page: show index(blogs)""" summary = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore' \ ' et dolore magna aliqua.' blogs = [Blog(id="tsb1", name="Blog Test 1", summary=summary, createtime=time.time() - 10), Blog(id="tsb2", name="Blog Test 2", summary=summary, createtime=time.time() - 100), Blog(id="tsb3", name="Blog Test 3", summary=summary, createtime=time.time() - 3900), Blog(id="tsb4", name="Blog Test 4", summary=summary, createtime=time.time() - 86400), Blog(id="tsb5", name="Blog Test 5", summary=summary, createtime=time.time() - 86400 * 10)] return dict(blogs=blogs)
def api_create_blog(): i = ctx.request.input(name='', summary='', content='') name = i.name.strip() summary = i.summary.strip() content = i.content.strip() user = ctx.request.user blog = Blog(user_id = user.id, user_name = user.name, name = name, summary = summary, content = content) blog.insert() return blog
async def index(request): summary = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' blogs = [ Blog(id='1', name='Test Blog', summary=summary, created_at=time.time() - 120), Blog(id='2', name='Something New', summary=summary, created_at=time.time() - 3600), Blog(id='4', name='Learn Swift', summary=summary, created_at=time.time() - 7200) ] return { '_template': 'blogs.html', 'blogs': blogs }
def api_create_blog(request, *, name, summary, content): 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()) yield from blog.save() return blog
def api_create_blog(request,*,name,summary,content): 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('conten','content cannot be empty.') blog = Blog(user_id = request.__user__.id,user_name = request.__user__.name,user_image=request.__user__.image,name =name.strip(),content=content.strip(),summary = summary.strip()) yield from blog.save() return blog
def index(*, page='1'): page_index = get_page_index(page) num = yield from Blog.findNumber('count(id)') page = Page(num) if num == 0: blogs = [] else: blogs = yield from Blog.findAll(orderBy='created_at desc', limit=(page.offset, page.limit)) return { '__template__': 'blogs.html', 'page': page, 'blogs': blogs }
def api_create_blog(): i = ctx.request.input(name='', summary='', content='') name = i.name.strip() summary = i.summary.strip() content = i.content.strip() user = ctx.request.user blog = Blog(user_id=user.id, user_name=user.name, name=name, summary=summary, content=content) blog.insert() return blog
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 main(): #webapp2.template.register_template_library('filter.filter') #webapp2.template.register_template_library('filter.recurse') from model import Blog g_blog=Blog.getBlog() if not g_blog: g_blog=Blog(id='default') g_blog.put() g_blog.InitBlogData() g_blog.application=micolog_app g_blog.plugins.register_handlerlist(micolog_app) from django.utils.translation import activate activate(g_blog.language) logging.getLogger().setLevel(logging.DEBUG)
def initialize(self, request, response): self.current='home' webapp.RequestHandler.initialize(self, request, response) os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' from model import User,Blog self.blog = Blog.getBlog() self.login_user = users.get_current_user() self.is_login = (self.login_user != None) self.loginurl=users.create_login_url(self.request.uri) self.logouturl=users.create_logout_url(self.request.uri) self.is_admin = users.is_current_user_admin() if self.is_admin: self.auth = 'admin' self.author=User.all().filter('email =',self.login_user.email()).get() if not self.author: self.author=User(dispname=self.login_user.nickname(),email=self.login_user.email()) self.author.isadmin=True self.author.user=self.login_user self.author.put() elif self.is_login: self.author=User.all().filter('email =',self.login_user.email()).get() if self.author: self.auth='author' else: self.auth = 'login' else: self.auth = 'guest' try: self.referer = self.request.headers['referer'] except: self.referer = None self.template_vals = {'self':self,'blog':self.blog,'current':self.current}
def newpost(): if request.method == 'POST': valid = True title_error = '' body_error = '' title = request.form['title'] body = request.form['body'] current_user = User.query.filter_by(username=session['username']).first() #check if both title and body are there if not title: title_error = "Pleae fill in a title" valid = False if not body: body_error = "Pleae fill in a body" valid = False if valid: #add and commit title and body in a new post if valid new_post = Blog(title, body, current_user) db.session.add(new_post) db.session.commit() return redirect('/blog?post_id={0}'.format(new_post.id)) else: return render_template('newpost.html', title_error=title_error, body_error=body_error) return render_template('newpost.html')
def post(self,page): code=page.param("code") OptionSet.setValue("Akismet_code",code) rm=page.param('autorm') if rm and int(rm)==1: rm=True else: rm=False oldrm = OptionSet.getValue("Akismet_AutoRemove",False) if oldrm!=rm: OptionSet.setValue("Akismet_AutoRemove",rm) spam=page.param("spam") spam = len(spam)>0 and int(spam) or 0 sOther = "" if spam>0: cm = Comment.get_by_id(spam) try: url = Blog.all().fetch(1)[0].baseurl self.SubmitAkismet({ 'user_ip' : cm.ip, 'comment_type' : 'comment', 'comment_author' : cm.author.encode('utf-8'), 'comment_author_email' : cm.email, 'comment_author_url' : cm.weburl, 'comment_content' : cm.content.encode('utf-8') },url,"Spam") sOther = u"<div style='padding:8px;margin:8px;border:1px solid #aaa;color:red;'>评论已删除</div>" cm.delit() except: sOther = u"<div style='padding:8px;margin:8px;border:1px solid #aaa;color:red;'>无法找到对应的评论项</div>" return sOther + self.get(page)
def new_post(): title_header = 'Add Blog Post' user = User.query.filter_by(name=session['username']).first() if request.method == 'POST': title = request.form['title'] body = request.form['body'] validation = validate_post(title, body) if validation == True: new_blog = Blog(title, body, user) db.session.add(new_blog) db.session.commit() return redirect('/blog?id={0}'.format(new_blog.id)) else: return render_template('new_post.html', base_title=title_header, base_header=title_header, title=title, title_err=validation['title_err'], body=body, body_err=validation['body_err']) else: return render_template('new_post.html', base_title=title_header, base_header=title_header)
def get(self): blogs = Blog.all().order('-createTimeStamp').fetch(10) template_values = { 'blogs': blogs } self.generateBasePage('manage/blogs.html',template_values) return
async def api_create_blog(request, *, title, summary, content, cat_name): if request.__user__ is None or not request.__user__.admin: raise APIPermissionError('Only admin can do this!') if not title or not title.strip(): raise APIValueError('title', 'Title can not be empty.') if not summary or not summary.strip(): summary = content.strip()[:200] elif len(summary.strip()) > 200: raise APIValueError('summary', 'Length of summary can not be larger than 200.') if not content or not content.strip(): raise APIValueError('content', 'Content can not be empty.') if not cat_name.strip(): cat_id = None else: cats = await Category.findAll(where='name=?', args=[cat_name.strip()]) if (len(cats) == 0): raise APIValueError('cat_name', 'cat_name is not belong to Category.') cat_id = cats[0].id blog = Blog(user_id=request.__user__.id, user_name=request.__user__.name, user_image=request.__user__.image, title=title.strip(), summary=summary.strip(), content=content.strip(), cat_id=cat_id, cat_name=cat_name.strip()) await blog.save() return blog
def create_post(): if request.method == 'POST': author = User.query.filter_by(username=session['user']).first() blog_title = request.form['blog-title'] blog_body = request.form['blog-body'] title_error = '' body_error = '' if not blog_title: title_error = "All posts need titles, give it one!" if not blog_body: body_error = "You can't have a blog post without a post, get writing!" if not title_error and not body_error: new_post = Blog(blog_title, blog_body, logged_in_user()) db.session.add(new_post) db.session.commit() return redirect('/blog?id={}'.format(new_post.id)) else: return render_template('newpost.html', title="New Post", title_error=title_error, body_error=body_error, blog_title=blog_title, blog_body=blog_body) return render_template('newpost.html', title='New Post')
def api_delete_blog(request, id): check_admin(request) blog = yield from Blog.find(id) if blog is None: return APIResourceNotFoundError('blog') yield from blog.remove() return dict(id=id)
def post(self): checkedIDs= self.request.get_all('checks') for id in checkedIDs: keyID = int(id) blog = Blog.get_by_id(keyID) blog.delete() self.redirect('/admin/blogs') return
def get_blog(id): blog = yield from Blog.find(id) comments = yield from Comment.findAll('blog_id=?', [id], orderBy='created_at desc') for c in comments: c.html_content = text2html(c.content) blog.html_content = markdown2.markdown(blog.content) return {'__template__': 'blog.html', 'blog': blog, 'comments': comments}
def api_delete_blog(request,* ,id): check_admin(request) blog = yield from Blog.find(id) yield from blog.remove() return dict(id = id)
def post(self): checkedIDs = self.request.get_all('checks') for id in checkedIDs: keyID = int(id) blog = Blog.get_by_id(keyID) blog.delete() self.redirect('/admin/blogs') return
def get_blog(parameters, blog_id): response = {'http_status': 404} blog = Blog(blog_id) if not blog.exists: return response response.update(blog.__dict__) response['http_status'] == 200 return response
def add_blog(title, picture, name, text, day, month): blog_object = Blog(title=title, picture=picture, name=name, text=text, day=day, month=month) session.add(blog_object) session.commit()
def create_blog(title, overview): """Create and return a new blog.""" blog = Blog(title=title, overview=overview) db.session.add(blog) db.session.commit() return blog
def index(request): blogs= yield from Blog.findAll() return { '__template__': 'blogs.html', 'blogs': blogs, '__user__':request.__user__ }
async def index(request): summary = 'long long ago, there is a bird, her name is BuGu. One day, she fly to my dream.' blogs = [ Blog(id='1', name="Test Blog", summary=summary, created_at=time.time() - 180), Blog(id='2', name="Somethind New", summary=summary, created_at=time.time() - 60 * 60 * 5), Blog(id='3', name="Learn Python", summary=summary, created_at=time.time() - 60 * 60 * 24 * 3) ] return {'__template__': 'blogs.html', 'blogs': blogs}
def api_create_blog(): article = ctx.request.input(name='', summary='', content='') name = article.name.strip() summary = article.name.strip() content = article.content.strip() if not name: raise APIValueError('name', 'Title is empty') if not summary: raise APIValueError('summary', 'Summary is empty') if not content: raise APIValueError('content', 'No content.') user = ctx.request.user blog = Blog(user_id=user.id, user_name=user.name, name=name, summary=summary, content=content) blog.insert() return blog
def get_blog(id): blog = yield from Blog.find(id) comments = yield from Comment.findAll('blog_id=?', [id], orderBy='created_at desc') for c in comments: c.html_content = text2html(c.content) blog.html_content = markdown2.markdown(blog.content) return { '__template__': 'blog.html', 'blog': blog, 'comments': comments }
async def api_create_blog(request, *, title, summary, content): check_admin(request) if not title or not title.strip(): raise APIValueError('title', 'title 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, avatar_url=request.__user__.avatar_url, title=title.strip(), summary=summary.strip(), content=content.strip()) await blog.save() return blog
def get(self): blogs = Blog.all().order('-createTimeStamp').fetch(10) if blogs and blogs[0]: lastUpdateTime = blogs[0].createTimeStamp lastUpdateTime = lastUpdateTime.strftime("%Y-%m-%dT%H:%M:%SZ") for blog in blogs: blog.formatDate = blog.createTimeStamp.strftime( "%Y-%m-%dT%H:%M:%SZ") self.response.headers['Content-Type'] = 'application/atom+xml' values = {'blogs': blogs, 'lastUpdateTime': lastUpdateTime} self.generateBasePage('atom.xml', values)
def get_load_time(): """Measure website load time""" with database.execution_context() as ctx: all_blog = Blog.select() for blog in all_blog: try: speed_seconds = requests.get( blog.url, timeout=5).elapsed.total_seconds() blog.network = speed_seconds blog.save() except Exception: logger.error('Timeout: name|%s|url|%s' % (blog.name, blog.url))
def get(self): action = self.param('action') if(action == ''): value ={'action':'?action=add'} elif(action=='edit'): key = self.param('key') blog = Blog.get(key) value={'action':'?key='+ key +'&action=edit', 'title':blog.title, 'content':blog.content} self.generateBasePage('manage/addblog.html',value) return
async def api_update_blog(request, name, summary, content, id, **kwargs): """ update an article """ check_permission(request) name, summary, content = check_blog_content(name, summary, content) # update rs = await Blog.update_by(set_dict=dict(name=name, summary=summary, content=content), where_dict=dict(id=id)) if rs != 1: logging.error('update blog error: %s rows affected.' % rs) raise ApiError('update-blog:failed', msg='blog does not exist!') # return same blog blog = Blog(id=id, name=name, summary=summary, content=content, **kwargs) return dict(blog=blog)
def api_create_comment(id, request, *, content): user = request.__user__ if user is None: raise APIPermissionError('Please signin first.') if not content or not content.strip(): raise APIValueError('content') blog = yield from Blog.find(id) if blog is None: raise APIResourceNotFoundError('Blog') comment = Comment(blog_id=blog.id, user_id=user.id, user_name=user.name, user_image=user.image, content=content.strip()) yield from comment.save() return comment
def create_blog(parameters): response = {'http_status': 400} data = {} title = parameters.get('title', False) if not title or title == "": response['error'] = 'Title is required' return response data['title'] = title data['body'] = parameters.get('body', '') blog = Blog() result = blog.create(data) if not result: response['error'] = 'could not create blog post' return response response.update(blog.__dict__) response['http_status'] = 201 return response
def index(request): # users = yield from User.findAll() # if request.__user__: # user = request.__user__ # else: # user = None blogs = yield from Blog.findAll() return { '__template__': 'blogs.html', #'users':users 'blogs': blogs # 'user': user }
def api_update_blog(id, request, *, name, summary, content): logging.info('creating new blogs here with api-blogs-id') check_admin(request) blog = yield from Blog.find(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() yield from blog.update() return blog
def post(self): key = self.param('key') action = self.param('action') title1,content1 = (self.request.get(item) for item in ('title', 'content')) if(not title1)or(not content1): self.error(501,'Please input title and content .') return if(action=='add'): blogEntity = Blog(title = title1, content = content1, createTimeStamp = datetime.now()) blogEntity.publish() self.redirect('/') share2miniblog(blogEntity) elif(action=='edit'): blogEntity = Blog.get(key) blogEntity.title = title1 blogEntity.content = content1 blogEntity.put() self.redirect('/?p=%d'%blogEntity.blog_id)
def get(self, id): gi = GroupInfo.get(id=id) if not gi: raise HTTPError(404) group_name = gi.name creater = User.get(gi.create_id) description = gi.description groups = Group.where(group_id=id) user_ids = groups.col_list(col='user_id') users = User.get_list(id=user_ids) for user_id in user_ids: if user_id not in CACHE: for user in users: if user_id == user.id: CACHE[user_id] = user blogs = Blog.where('user_id in (%s)'%','.join(user_ids)) for blog in blogs: blog.user = CACHE[blog.user_id] return self.render('group.html', gi=gi, creater=creater, groups=groups, users=users, blogs=blogs)
def api_edit_blog(request, *, id, name, summary, content): check_admin(request) if not name or not name.strip(): raise APIValueError('name','name can not be empty') if summary is None or not summary.strip(): raise APIValueError('summary','summary can not be empty') if content is None or not content.strip(): raise APIValueError('content', 'content can not be empty') blog = yield from Blog.find(id) blog.name = name blog.summary = summary blog.content = content yield from blog.update() return blog
def initialize(self, request, response): self.current='home' webapp2.RequestHandler.initialize(self, request, response) if hasattr(self,'setup'): self.setup() from model import User,Blog self.blog = Blog.getBlog() self.login_user = users.get_current_user() self.is_login = (self.login_user != None) self.loginurl=users.create_login_url(self.request.uri) self.logouturl=users.create_logout_url(self.request.uri) self.is_admin = users.is_current_user_admin() if self.is_admin: self.auth = 'admin' self.author=User.query().filter(User.email ==self.login_user.email()).get() if not self.author: self.author=User(dispname=self.login_user.nickname(),email=self.login_user.email()) self.author.level=3 self.author.user=self.login_user self.author.put() elif self.is_login: self.author=User.query().filter(User.email ==self.login_user.email()).get() if self.author: self.auth='author' else: self.auth = 'login' else: self.auth = 'guest' try: self.referer = self.request.headers['referer'] except: self.referer = None self.template_vals = {'self':self,'blog':self.blog,'current':self.current}
def get(self, page): code = OptionSet.getValue("Akismet_code", default="") up = OptionSet.getValue("Akismet_Comments_v0.3", default=[]) rm = OptionSet.getValue("Akismet_AutoRemove", False) if type(up) != type([]): up = [] delkey = page.param("delkey") rekey = page.param("rekey") if rekey or delkey: newup = [] for i in up: cmtkey = i["key"][0] enykey = i["key"][1] if delkey and cmtkey == delkey: cm = Comment.get(cmtkey) db.Model.delete(cm) elif rekey and cmtkey == rekey: cm = Comment.get(cmtkey) eny = Entry.get(enykey) eny.commentcount += 1 eny.put() cm.entry = eny db.Model.put(cm) self.SubmitAkismet( { "user_agent": i["other"]["user_agent"], "referrer": i["other"]["referrer"], "user_ip": cm.ip, "comment_type": "comment", "comment_author": cm.author.encode("utf-8"), "comment_author_email": cm.email, "comment_author_url": cm.weburl, "comment_content": cm.content.encode("utf-8"), }, i["other"].get("url", ""), "Ham", ) else: newup.append(i) if not len(up) == len(newup): OptionSet.setValue("Akismet_Comments_v0.3", newup) up = newup cmts = [(Comment.get(i["key"][0]), Entry.get(i["key"][1])) for i in up] comments = [ u'<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td><a target="_blank" href="/%s">%s</a></td><td><a href="?delkey=%s" title="删除">删除</a> <a href="?rekey=%s" title="这不是一个垃圾评论">还原</a></td></tr>' % ( i[0].date, i[0].author, i[0].content, i[0].email, i[0].ip, i[1].link, i[1].title, str(i[0].key()), str(i[0].key()), ) for i in cmts if i is not None and i[0] is not None ] comments = "".join(comments) apikey = OptionSet.getValue("Akismet_code", default=self.AKISMET_default_Key) if len(apikey) < 5: apikey = self.AKISMET_default_Key api = AkismetManager(apikey, Blog.all()[0].baseurl) if not code: status = "" elif api.IsValidKey(): status = "True" else: status = "False" if rm == True: rmchecked = 'checked="checked"' else: rmchecked = "" return u"""<h3>Akismet</h3> <form action="" method="post"> <p>Akismet Api Key:</p> <input name="code" style="width:400px;" value="%s"> %s <br /> <p>自动删除检测到的垃圾评论: <input type="checkbox" name="autorm" value="1" %s></p> <p>删除一条正常的评论并提交Spam(输入评论的ID):</p> <input name="spam" style="width:400px;" value=""> <br /> <input type="submit" value="submit"> </form> <div> <br /> <h3>被过滤的评论</h3> <table class="widefat"><thead><tr><th>日期</th><th>作者</th><th>内容</th><th>电子邮件</th><th>IP地址</th><th>文章/页面</th><th style="width:15%%;">选择操作</th></tr></thead><tbody>%s </tbody></table> </div>""" % ( code, status, rmchecked, comments, )
def get(self,page): code=OptionSet.getValue("Akismet_code",default="") up=OptionSet.getValue("Akismet_Comments_v0.3",default=[]) if type(up)!=type([]): up=[] delkey = page.param('delkey') rekey = page.param('rekey') if rekey or delkey: newup = [] for i in up: cmtkey = i['key'][0]; enykey = i['key'][1]; if delkey and cmtkey==delkey: cm = Comment.get(cmtkey) db.Model.delete(cm) elif rekey and cmtkey==rekey: cm = Comment.get(cmtkey) eny = Entry.get(enykey) eny.commentcount+=1 eny.put() cm.entry = eny db.Model.put(cm) self.SubmitAkismet({ 'user_agent':i['other']['user_agent'], 'referrer':i['other']['referrer'], 'user_ip' : cm.ip, 'comment_type' : 'comment', 'comment_author' : cm.author.encode('utf-8'), 'comment_author_email' : cm.email, 'comment_author_url' : cm.weburl, 'comment_content' : cm.content.encode('utf-8') },i['other'].get('url',''),"Ham") else: newup.append(i) if not len(up)==len(newup): OptionSet.setValue("Akismet_Comments_v0.3",newup) up = newup cmts = [(Comment.get(i['key'][0]),Entry.get(i['key'][1])) for i in up] comments = [u'<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td><a target="_blank" href="/%s">%s</a></td><td><a href="?delkey=%s" title="删除">删除</a> <a href="?rekey=%s" title="这不是一个垃圾评论">还原</a></td></tr>'%(i[0].date, i[0].author,i[0].content,i[0].email,i[0].ip,i[1].link,i[1].title,str(i[0].key()),str(i[0].key())) for i in cmts] comments = ''.join(comments) apikey = OptionSet.getValue("Akismet_code",default=self.AKISMET_default_Key) if len(apikey)<5: apikey = self.AKISMET_default_Key api = AkismetManager(apikey,Blog.all()[0].baseurl) if not code: status = '' elif api.IsValidKey(): status = 'True' else: status = 'False' return u'''<h3>Akismet</h3> <form action="" method="post"> <p>Akismet Api Key:</p> <input name="code" style="width:400px;" value="%s"> %s <br /> <p>删除一条评论并提交Spam(输入评论的ID):</p> <input name="spam" style="width:400px;" value=""> <br /> <input type="submit" value="submit"> </form> <div> <br /> <h3>被过滤的评论</h3> <table class="widefat"><thead><tr><th>日期</th><th>作者</th><th>内容</th><th>电子邮件</th><th>IP地址</th><th>文章/页面</th><th style="width:15%%;">选择操作</th></tr></thead><tbody>%s </tbody></table> </div>'''%(code,status,comments)
def _get_blogs_by_page(): total = Blog.count_all() page = Page(total, _get_page_index()) blogs = Blog.find_by('order by created_at desc limit ?,?', page.offset, page.limit) return blogs, page
def api_get_blog(*, id): blog = yield from Blog.find(id) return blog