code stringlengths 1 1.49M | vector listlengths 0 7.38k | snippet listlengths 0 7.38k |
|---|---|---|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Ignacio Andreu <plunchete at gmail dot com>
#
# This file is part of "debug_mode_on".
#
# "debug_mode_on" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "debug_mode_on" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>.
#
from handlers.BaseHandler import *
class SearchResult(BaseHandler):
def execute(self):
self.render('templates/search-result.html')
| [
[
1,
0,
0.8462,
0.0385,
0,
0.66,
0,
437,
0,
1,
0,
0,
437,
0,
0
],
[
3,
0,
0.9615,
0.1154,
0,
0.66,
1,
821,
0,
1,
0,
0,
94,
0,
1
],
[
2,
1,
0.9808,
0.0769,
1,
0.06,
... | [
"from handlers.BaseHandler import *",
"class SearchResult(BaseHandler):\n\tdef execute(self):\n\t\tself.render('templates/search-result.html')",
"\tdef execute(self):\n\t\tself.render('templates/search-result.html')",
"\t\tself.render('templates/search-result.html')"
] |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Alberto Gimeno <gimenete at gmail dot com>
#
# This file is part of "debug_mode_on".
#
# "debug_mode_on" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "debug_mode_on" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>.
#
from handlers.BaseHandler import *
class Tag(BaseHandler):
def execute(self):
tag = self.request.path.split('/', 2)[2]
query = model.Article.all().filter('tags =', tag).filter('draft', False).filter('deletion_date', None).order('-creation_date')
self.values['articles'] = self.paging(query, 10)
self.add_tag_cloud()
self.values['tag'] = tag
self.render('templates/tag.html')
| [
[
1,
0,
0.697,
0.0303,
0,
0.66,
0,
437,
0,
1,
0,
0,
437,
0,
0
],
[
3,
0,
0.8788,
0.2727,
0,
0.66,
1,
493,
0,
1,
0,
0,
94,
0,
9
],
[
2,
1,
0.9091,
0.2121,
1,
0.35,
... | [
"from handlers.BaseHandler import *",
"class Tag(BaseHandler):\n\n\tdef execute(self):\n\t\ttag = self.request.path.split('/', 2)[2]\n\t\tquery = model.Article.all().filter('tags =', tag).filter('draft', False).filter('deletion_date', None).order('-creation_date')\n\t\tself.values['articles'] = self.paging(query,... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import BaseHandler
class NotFound(BaseHandler):
def execute(self):
self.not_found() | [
[
1,
0,
0.8214,
0.0357,
0,
0.66,
0,
437,
0,
1,
0,
0,
437,
0,
0
],
[
3,
0,
0.9464,
0.1429,
0,
0.66,
1,
658,
0,
1,
0,
0,
94,
0,
1
],
[
2,
1,
0.9821,
0.0714,
1,
0.57,
... | [
"from handlers.BaseHandler import BaseHandler",
"class NotFound(BaseHandler):\n\n\tdef execute(self):\n\t\tself.not_found()",
"\tdef execute(self):\n\t\tself.not_found()",
"\t\tself.not_found()"
] |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import model
import logging
from google.appengine.api import memcache
from google.appengine.ext import webapp
from handlers.BaseHandler import BaseHandler
class ImageBrowser(BaseHandler):
def execute(self):
user = self.values['user']
#TODO PAGINATE
if user:
list = ""
if user.rol == 'admin':
images = model.Image.all()
else:
images = model.Image.gql('WHERE author_nickname=:1', user.nickname)
self.values['images'] = images
self.render('templates/editor/browse.html')
return
| [
[
1,
0,
0.5,
0.0227,
0,
0.66,
0,
722,
0,
1,
0,
0,
722,
0,
0
],
[
1,
0,
0.5227,
0.0227,
0,
0.66,
0.2,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.5682,
0.0227,
0,
0.66,
... | [
"import model",
"import logging",
"from google.appengine.api import memcache",
"from google.appengine.ext import webapp",
"from handlers.BaseHandler import BaseHandler",
"class ImageBrowser(BaseHandler):\n \n def execute(self):\n user = self.values['user']\n \n #TODO PAGINATE\n ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import datetime
import os
import model
import logging
from google.appengine.api import memcache
from google.appengine.ext import webapp
from handlers.AuthenticatedHandler import AuthenticatedHandler
class ImageUploader(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
if method == 'GET':#Request identifies actions
action = self.get_param('act')
url_path = self.get_param('url')
query = model.Image.gql('WHERE url_path=:1', url_path )
image = query.get()
if not image:
self.render_json({ 'saved': False, 'msg': self.getLocale('Not found') })
elif user.nickname != image.author_nickname and user.rol != 'admin':
self.render_json({ 'saved': False, 'msg': self.getLocale('Not allowed') })
elif action == 'del': #delete image
image.delete()
self.render_json({ 'saved': True })
else:
self.render_json({ 'saved': False })
else:#File upload
# Get the uploaded file from request.
upload = self.request.get("upload")
nick = user.nickname
dt = datetime.datetime.now()
prnt = dt.strftime("%Y%m%d%H%M%S")
url_path = nick +"/"+ prnt
try:
query = model.Image.all(keys_only=True).filter('url_path', url_path)
entity = query.get()
if entity:
raise Exception('unique_property must have a unique value!')
image = model.Image(author=user,
author_nickname=nick,
thumbnail=upload,
url_path=url_path)
image.put()
self.values["label"] = self.getLocale("Uploaded as: %s") % url_path
except:
self.values["label"] = self.getLocale('Error saving image')
self.render("/translator-util.html")
return | [
[
1,
0,
0.275,
0.0125,
0,
0.66,
0,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.2875,
0.0125,
0,
0.66,
0.1429,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.3,
0.0125,
0,
0.66... | [
"import datetime",
"import os",
"import model",
"import logging",
"from google.appengine.api import memcache",
"from google.appengine.ext import webapp",
"from handlers.AuthenticatedHandler import AuthenticatedHandler",
"class ImageUploader(AuthenticatedHandler):\n \n def execute(self):\n ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import re
import model
import datetime
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.runtime.apiproxy_errors import CapabilityDisabledError
from utilities import Constant
from utilities.AppProperties import AppProperties
class BaseHandler(webapp.RequestHandler):
#########################
### Handler functions ###
#########################
def get(self):
if self.request.url.split('/')[2] == AppProperties().getAppDic().get(Constant.domain):#'vikuit.com':
self.redirect(self.get_application().url + self.request.url.split('/', 3)[3], permanent=True)# 'http://www.vikuit.com/'
return
try:
self.common_stuff()
self.pre_execute()
except CapabilityDisabledError:
self.values = {}
self.render('templates/maintenace.html')
return
def post(self):
self.common_stuff()
self.pre_execute()
def pre_execute(self):
self.execute()
def common_stuff(self):
self.values = {}
self.user = None
import session
#app = model.Application.all().get()
app = self.get_application()
if app:
self.sess = session.Session(app.session_seed)
if self.sess.load():
self.user = self.get_current_user()
elif self.is_google_account():
#google account users.get_current_user()
#user only arrives here 1 time per session
self.user = self.get_current_user()
if self.user:
redirect, self.user = self.store_google_account()
self.sess.store(str(self.user.key()), 7200)
if redirect:
# redirect to preferences page
self.redirect("/module/user.edit")
if self.user.banned_date is not None:
msg = self.getLocale("User '%s' was blocked. Contact with an administrator.") % self.user.nickname()
self.show_error( msg )
else:
self.sess = None
redirect = '%s?%s' % (self.request.path, self.request.query)
self.values['sess'] = self.sess
self.values['redirect'] = redirect
self.values['app'] = self.get_application()
self.values['activity_communities'] = self.communities_by_activity()
if self.user:
self.values['auth'] = self.sess.auth
self.values['logout'] = '/module/user.logout?redirect_to=%s&auth=%s' % (self.quote(redirect), self.sess.auth)
"""
user_data = model.UserData.gql('WHERE email=:1', user.email()).get()
if not user_data:
user_data = model.UserData(email=user.email(),
nickname=user.nickname(),
articles=0,
draft_articles=0,
messages=0,
draft_messages=0,
comments=0,
rating_count=0,
rating_total=0,
rating_average=0,
threads=0,
responses=0,
communities=0,
favourites=0,
public=False)
user_data.put()
self.values['user'] = user_data
"""
# TODO deprecated, use self.user instead
self.values['user'] = self.user
else:
self.user = None
self.values['user'] = None
self.values['login'] = '/module/user.login?redirect_to=%s' % self.quote(redirect) # users.create_login_url(self.values['redirect'])
self.values['glogin'] = users.create_login_url(self.values['redirect'])
#################################################
### Authentication and Autorization functions ###
#################################################
def hash(self, login, p, times=100):
import sha
p = p.encode('ascii', 'ignore')
p = '%s:%s' % (login, p)
for i in range(0, times):
p = sha.new(p).hexdigest()
return p
def can_write(self, community):
if community.all_users is None or community.all_users:
return True
user = self.values['user']
if not user:
return False
if model.CommunityUser.all().filter('community', community).filter('user', user).get():
return True
return False
def check_password(self, user, password):
times = 100
user_password = user.password
s = user.password.split(':')
if len(s) > 1:
times = int(s[0])
user_password = s[1]
return self.hash(user.nickname, password, times) == user_password
def hash_password(self, nickname, password):
times = 1
return '%d:%s' % (times, self.hash(nickname, password, times))
def auth(self):
token = self.values['auth']
b = token == self.get_param('auth')
if not b:
self.forbidden()
return b
def get_current_user(self):
if self.sess.user:##first
return db.get(self.sess.user)
user = users.get_current_user()#login with google account
# if user:
# user = model.UserData.gql('WHERE email=:1', user.email()).get()
return user
def is_google_account(self):
user = users.get_current_user()
if user:
return True
else:
return False
def store_google_account(self):
googleAcc = users.get_current_user()
user = model.UserData.gql('WHERE email=:1', googleAcc.email()).get()
redirectPreferences = False
if user is None:
redirectPreferences = True
nick = self.getNickname(googleAcc.nickname())
user = model.UserData(nickname=nick,
email=googleAcc.email(),
password=None,#Change to optional
articles=0,
draft_articles=0,
messages=0,
draft_messages=0,
comments=0,
rating_count=0,
rating_total=0,
rating_average=0,
threads=0,
responses=0,
communities=0,
favourites=0,
public=False,
contacts=0)
user.registrationType = 1 #Google identifier
user.last_login = datetime.datetime.now()
user.put()
if redirectPreferences:
# Is new user
app = model.Application.all().get()
if app:
app.users += 1
app.put()
memcache.delete('app')
return redirectPreferences, user
def getNickname(self, nick, isMail=True):
if isMail:
return nick.split('@')[0]
else:
return nick
###########################
### Bussiness functions ###
###########################
def add_user_subscription(self, user, subscription_type, subscription_id):
user_subscription = model.UserSubscription(user=user,
user_nickname=user.nickname,
user_email=user.email,
subscription_type=subscription_type,
subscription_id=subscription_id,
creation_date = datetime.datetime.now())
subscription = model.UserSubscription.all().filter('user', user).filter('subscription_type', subscription_type).filter('subscription_id', subscription_id).get()
if subscription is None:
user_subscription.put()
def remove_user_subscription(self, user, subscription_type, subscription_id):
user_subscription = model.UserSubscription.all().filter('user', user).filter('subscription_type', subscription_type).filter('subscription_id', subscription_id).get()
if user_subscription is not None:
user_subscription.delete()
def add_follower(self, community=None, user=None, article=None, thread=None, nickname=None):
object_type = None
obj = None
if user is not None:
object_type = 'user'
obj = user
elif community is not None:
object_type = 'community'
obj = community
elif thread is not None:
object_type = 'thread'
obj = thread
elif article is not None:
object_type = 'article'
obj = article
if object_type is None:
return None
follower = model.Follower.all().filter('object_type', object_type).filter('object_id', obj.key().id()).get()
if follower:
if nickname not in follower.followers:
follower.followers.append(nickname)
follower.put()
else:
follower = model.Follower(object_type=object_type,
object_id=obj.key().id(),
followers=[nickname])
follower.put()
def remove_follower(self, community=None, user=None, article=None, thread=None, nickname=None):
object_type = None
obj = None
if user is not None:
object_type = 'user'
obj = user
elif community is not None:
object_type = 'community'
obj = community
elif thread is not None:
object_type = 'thread'
obj = thread
elif article is not None:
object_type = 'article'
obj = article
if object_type is None:
return None
follower = model.Follower.all().filter('object_type', object_type).filter('object_id', obj.key().id()).get()
if follower:
if nickname in follower.followers:
follower.followers.remove(nickname)
follower.put()
def create_event(self, event_type, followers,
user, user_to=None, community=None, article=None, thread=None, creation_date=None,
response_number=0):
event = model.Event(event_type=event_type,
followers=followers,
user=user,
user_nickname=user.nickname,
response_number=response_number)
if user_to is not None:
event.user_to = user_to
event.user_to_nickname = user_to.nickname
if community is not None:
event.community = community
event.community_title = community.title
event.community_url_path = community.url_path
if article is not None:
event.article = article
event.article_title = article.title
event.article_author_nickname = article.author_nickname
event.article_url_path = article.url_path
if thread is not None:
event.thread = thread
event.thread_title = thread.title
event.thread_url_path = thread.url_path
if creation_date is None:
event.creation_date = datetime.datetime.now()
else:
event.creation_date = creation_date
event.put()
def get_followers(self, user=None, community=None, thread=None, article=None):
object_type = None
obj = None
if user is not None:
object_type = 'user'
obj = user
elif community is not None:
object_type = 'community'
obj = community
elif thread is not None:
object_type = 'thread'
obj = thread
elif article is not None:
object_type = 'article'
obj = article
if object_type is None:
return None
object_id = obj.key().id()
follower = model.Follower.all().filter('object_type', object_type).filter('object_id', object_id).get()
if not follower:
follower = model.Follower(object_type=object_type, object_id=object_id, followers=[])
follower.put()
return follower.followers
def create_task(self, task_type, priority, data):
import simplejson
t = model.Task(task_type=task_type, priority=priority, data=simplejson.dumps(data))
t.put()
def is_contact(self, this_user):
user = self.values['user']
if not user:
return False
if model.Contact.all().filter('user_from', user).filter('user_to', this_user).get():
return True
return False
def create_community_subscribers(self, community):
if not community.subscribers:
com = [g.user.email for g in model.CommunityUser.all().filter('community', community).fetch(1000) ]
community.subscribers = list(set(com))
# I use strings in order to distinguish three values into the templates
# 'True', 'False', and None
def joined(self, community):
gu = model.CommunityUser.gql('WHERE community=:1 and user=:2', community, self.values['user']).get()
if gu is not None:
return 'True'
return 'False'
def communities_by_activity(self):
key = 'activity_communities'
g = memcache.get(key)
if g is not None:
return g
else:
communities = model.Community.all().order('-activity').fetch(15)
memcache.add(key, communities, 3600)
return communities
def add_categories(self):
cats = list(model.Category.all().order('title'))
categories = {}
for category in cats:
# legacy code
if not category.url_path:
category.url_path = self.to_url_path(category.title)
category.put()
# end
if category.parent_category is None:
categories[str(category.key())] = category
for category in cats:
if category.parent_category is not None:
parent_category = categories[str(category.parent_category.key())]
if not parent_category.subcategories:
parent_category.subcategories = []
parent_category.subcategories.append(category)
ret = [categories[key] for key in categories]
ret.sort()
self.values['categories'] = ret
def add_tag_cloud(self):
self.values['tag_cloud'] = self.cache('tag_cloud', self.get_tag_cloud)
def get_tag_cloud(self):
return self.tag_list(model.Tag.all().order('-count').fetch(30))
def parse_tags(self, tag_string):
tags = [self.to_url_path(t) for t in tag_string.split(',')]
return list(set(tags))
def delete_tags(self, tags):
tags=set(tags)
for tag in tags:
t = model.Tag.gql('WHERE tag=:1', tag).get()
if t:
if t.count == 1:
t.delete()
else:
t.count = t.count - 1
t.put()
def update_tags(self, tags):
tags=set(tags)
for tag in tags:
t = model.Tag.gql('WHERE tag=:1', tag).get()
if not t:
tg = model.Tag(tag=tag,count=1)
tg.put()
else:
t.count = t.count + 1
t.put()
def tag_list(self, tags):
tagdict={}
for t in tags:
tagdict[t.tag] = t.count
if not tagdict:
return []
maxcount = max(t.count for t in tags)
taglist = [(tag, 6*tagdict[tag]/maxcount, tagdict[tag]) for tag in tagdict.keys()]
taglist.sort()
return taglist
###############################
### Evnironment And Renders ###
###############################
def create_jinja_environment(self):
env = AppProperties().getJinjaEnv()
env.filters['relativize'] = self.relativize
env.filters['markdown'] = self.markdown
env.filters['smiley'] = self.smiley
env.filters['pagination'] = self.pagination
env.filters['media'] = self.media_content
env.filters['quote'] = self.quote
return env
def get_template(self, env, f):
p = f.split('/')
if p[0] == 'templates':
f = '/'.join(p[1:])
t = env.get_template(f)
return t
def render_chunk(self, f, params):
env = self.create_jinja_environment()
t = self.get_template(env, f)
return t.render(params)
def render(self, f):
self.response.headers['Content-Type'] = 'text/html;charset=UTF-8'
self.response.headers['Pragma'] = 'no-cache'
self.response.headers['Cache-Control'] = 'no-cache'
self.response.headers['Expires'] = 'Wed, 27 Aug 2008 18:00:00 GMT'
self.response.out.write(self.render_chunk(f, self.values))
def render_json(self, data):
import simplejson
self.response.headers['Content-Type'] = 'application/json;charset=UTF-8'
self.response.headers['Pragma'] = 'no-cache'
self.response.headers['Cache-Control'] = 'no-cache'
self.response.headers['Expires'] = 'Wed, 27 Aug 2008 18:00:00 GMT'
self.response.out.write(simplejson.dumps(data))
def relativize(self, value):
now = datetime.datetime.now()
try:
diff = now - value
except TypeError:
return ''
days = diff.days
seconds = diff.seconds
if days > 365:
return self.getLocale("%d years") % (days / 365, ) #u"%d años" % (days / 365, )
if days > 30:
return self.getLocale("%d months") % (days / 30, ) #u"%d meses" % (days / 30, )
if days > 0:
return self.getLocale("%d days") % (days, ) # u"%d días" % (days, )
if seconds > 3600:
return self.getLocale("%d hours") % (seconds / 3600, ) # u"%d horas" % (seconds / 3600, )
if seconds > 60:
return self.getLocale("%d minutes") % (seconds / 60, ) # u"%d minutos" % (seconds / 60, )
return self.getLocale("%d seconds") % (seconds, ) # u"%d segundos" % (seconds, )
def smiley(self, value):
return value
def markdown(self, value):
try:
import markdown
except ImportError:
return "error"
else:
return markdown.markdown(value, [], safe_mode='escape')
def quote(self, value):
import urllib
value = self.get_unicode(value)
return urllib.quote((value).encode('UTF-8'))
def media_content(self,value):
import MediaContentFilters as contents
value=contents.media_content(value)
return value
###########################
### Utilities functions ###
###########################
def mail(self, subject, body, to=[], bcc=[]):
app = self.get_application()
subject = "%s %s" % (app.mail_subject_prefix, subject)
body = """
%s
%s
""" % (body,app.mail_footer)
queue = model.MailQueue(subject=subject, body=body, to=to, bcc=bcc)
queue.put()
def show_error(self, message):
self.values['message'] = message
self.render('templates/error.html')
"""
def handle_exception(self, exception):
self.response.clear()
self.response.set_status(500)
self.render('templates/error500.html')
"""
def not_found(self):
self.response.clear()
self.response.set_status(404)
self.render('templates/error404.html')
def forbidden(self):
self.response.clear()
self.response.set_status(403)
self.render('templates/error403.html')
def getLocale(self, label):
return self.render_chunk("/translator-util.html", {"label": label})
def get_application(self):
return self.cache('app', self.fetch_application)
def fetch_application(self):
return model.Application.all().get()
def value(self, key):
try:
return self.values[key]
except KeyError:
return None
def not_none(self, value):
if not value:
return ''
return value
def get_param(self, key):
return self.get_unicode(self.request.get(key))
def get_unicode(self, value):
try:
value = unicode(value, "utf-8")
except TypeError:
return value
return value
def cache(self, key, function, timeout=0):
# import logging
# logging.debug('looking for %s in the cache' % key)
data = memcache.get(key)
if data is not None:
# logging.debug('%s is already in the cache' % key)
return data
else:
data = function.__call__()
# logging.debug('inserting %s in the cache' % key)
memcache.add(key, data, timeout)
return data
"""
def cache_this(self, function, timeout=600):
key = '%s?%s' % (self.request.path, self.request.query)
return self.cache(key, function, timeout)
def pre_pag(self, query, max, default_order=None):
try:
p = int(self.get_param('p'))
except ValueError:
p = 1
offset = (p-1)*max
o = self.get_param('o')
if o:
query = query.order(o)
self.values['o'] = o
elif default_order:
query = query.order(default_order)
return [obj for obj in query.fetch(max+1, offset)]
def post_pag(self, a, max):
try:
p = int(self.get_param('p'))
except ValueError:
p = 1
self.values['p'] = p
if p > 1:
self.values['prev'] = p-1
l = len(a)
if l > max:
self.values['len'] = max
self.values['next'] = p+1
return a[:max]
self.values['len'] = l
o = self.get_param('o')
if o:
self.values['o'] = o
return a
"""
def paging(self, query, max, default_order=None, total=-1, accepted_orderings=[], key=None, timeout=300):
if total > 0:
pages = total / max
if total % max > 0:
pages += 1
self.values['pages'] = pages
i = 1
pagesList = []
while i <= pages:
pagesList.append(i)
i += 1
self.values['pagesList'] = pagesList
try:
p = int(self.get_param('p'))
if p < 1:
p = 1
except ValueError:
p = 1
self.values['p'] = p
offset = (p-1)*max
#if offset > 1000:
# return None
o = self.get_param('o')
if o and o in accepted_orderings:
query = query.order(o)
self.values['o'] = o
elif default_order:
query = query.order(default_order)
# caching
if not key is None:
a = memcache.get(key)
if a is None:
a = [obj for obj in query.fetch(max+1, offset)]
memcache.add(key, a, timeout)
else:
a = [obj for obj in query.fetch(max+1, offset)]
#
if p > 1:
self.values['prev'] = p-1
l = len(a)
if l > max:
self.values['len'] = max
self.values['next'] = p+1
return a[:max]
self.values['len'] = l
return a
def pagination(self, value):
##Pagination
if self.value('prev') or self.value('next'):
params = []
p = self.value('p')
q = self.value('q')
a = self.value('a')
t = self.value('t')
o = self.value('o')
cat = self.value('cat')
pages = self.value('pages')
# order
if cat:
params.append('cat=%s' % cat)
# query string
if q:
params.append('q=%s' % q)
# type
if t:
params.append('t=%s' % t)
# order
if o:
params.append('o=%s' % o)
# anchor
if a:
a = '#%s' % str(a)
else:
a = ''
self.values['p'] = p
self.values['common'] = '%s%s' % ('&'.join(params), a)
return ''
def to_url_path(self, value):
value = value.lower()
# table = maketrans(u'áéíóúÁÉÍÓÚñÑ', u'aeiouAEIOUnN')
# value = value.translate(table)
value = value.replace(u'á', 'a')
value = value.replace(u'é', 'e')
value = value.replace(u'í', 'i')
value = value.replace(u'ó', 'o')
value = value.replace(u'ú', 'u')
value = value.replace(u'Á', 'A')
value = value.replace(u'É', 'E')
value = value.replace(u'Í', 'I')
value = value.replace(u'Ó', 'O')
value = value.replace(u'Ú', 'U')
value = value.replace(u'ñ', 'n')
value = value.replace(u'Ñ', 'N') # TODO improve + review URL path allowed chars
value = '-'.join(re.findall('[a-zA-Z0-9]+', value))
return value
def clean_ascii(self, value):
# table = maketrans(u'áéíóúÁÉÍÓÚñÑ', u'aeiouAEIOUnN')
# value = value.translate(table)
value = value.replace(u'á', 'a')
value = value.replace(u'é', 'e')
value = value.replace(u'í', 'i')
value = value.replace(u'ó', 'o')
value = value.replace(u'ú', 'u')
value = value.replace(u'Á', 'A')
value = value.replace(u'É', 'E')
value = value.replace(u'Í', 'I')
value = value.replace(u'Ó', 'O')
value = value.replace(u'Ú', 'U')
value = value.replace(u'ñ', 'n')
value = value.replace(u'Ñ', 'N') # TODO improve + review URL path allowed chars
value = ' '.join(re.findall('[a-zA-Z0-9()_\.:;-]+', value))
return value
def unique_url_path(self, model, url_path):
c = 1
url_path_base = url_path
while True:
query = db.Query(model)
query.filter('url_path =', url_path)
count = query.count(1)
if count > 0:
url_path = '%s-%d' % (url_path_base, c)
c = c + 1
continue
break
return url_path | [
[
1,
0,
0.0259,
0.0012,
0,
0.66,
0,
540,
0,
1,
0,
0,
540,
0,
0
],
[
1,
0,
0.0271,
0.0012,
0,
0.66,
0.1,
722,
0,
1,
0,
0,
722,
0,
0
],
[
1,
0,
0.0283,
0.0012,
0,
0.6... | [
"import re",
"import model",
"import datetime",
"from google.appengine.ext import db",
"from google.appengine.ext import webapp",
"from google.appengine.api import users",
"from google.appengine.api import memcache",
"from google.appengine.runtime.apiproxy_errors import CapabilityDisabledError",
"fr... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.api import mail
from google.appengine.ext import db
from handlers.BaseHandler import *
import re
class Invite(BaseHandler):
def execute(self):
user = self.values['user']
method = self.request.method
app = self.get_application()
if not user:
self.redirect('/module/user.login')
if method == 'GET':
#u"""Te invito a visitar %s, %s.\n %s
self.values['personalmessage'] = self.getLocale("Let me invite you to visit %s, %s. %s") % (app.name, app.subject, app.url)
self.render('templates/invite-friends.html')
return
elif self.auth():
contacts = self.get_param('contacts').replace(' ','')
contacts = contacts.rsplit(',',19)
if contacts[0]=='' or not contacts:
self.values['failed']=True
self.render('templates/invite-friends.html')
return
self.values['_users'] = []
invitations = []
for contact in contacts:
#FIXME inform the user about bad formed mails
if re.match('\S+@\S+\.\S+', contact):
u = model.UserData.gql('WHERE email=:1', contact).get()
if u:
self.values['_users'].append(u)
else:
invitations.append(contact)
personalmessage = self.get_param('personalmessage')
subject = self.getLocale("%s invites you to participate in %s") % (user.nickname, app.name)
body = self.getLocale("Let me invite you to visit %s, %s. %s") % (app.name, app.subject, app.url)
if personalmessage:
body = u"%s \n\n\n\n\t %s" % (self.clean_ascii(personalmessage), self.get_application().url)
self.mail(subject=subject, body=body, bcc=invitations)
self.values['sent'] = True
self.values['invitations'] = invitations
self.render('templates/invite-friends.html')
| [
[
1,
0,
0.2987,
0.013,
0,
0.66,
0,
279,
0,
1,
0,
0,
279,
0,
0
],
[
1,
0,
0.3117,
0.013,
0,
0.66,
0.25,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.3247,
0.013,
0,
0.66,... | [
"from google.appengine.api import mail",
"from google.appengine.ext import db",
"from handlers.BaseHandler import *",
"import re",
"class Invite(BaseHandler):\n\t\n\tdef execute(self):\n\t\tuser = self.values['user']\n\t\tmethod = self.request.method\n\n\t\tapp = self.get_application()",
"\tdef execute(se... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import time
import model
import datetime
import markdown
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from time import strftime, gmtime, time
from utilities.AppProperties import AppProperties
class Feed(webapp.RequestHandler):
def get(self):
data = memcache.get(self.request.path)
if not data:
time = 600
params = self.request.path.split('/', 4)
if not params[2]:
latest = model.Article.gql('WHERE draft=:1 AND deletion_date=:2 ORDER BY creation_date DESC LIMIT 20', False, None)
data = self.to_rss(self.get_application().name, latest)
elif params[2] == 'mblog':
query = model.Mblog.all().filter('deletion_date', None).order('-creation_date')
latest = [o for o in query.fetch(25)]
data = self.posts_to_rss(self.getLocale("Microbblogging"), latest)
time = 200
elif params[2] == 'tag':
query = model.Article.all().filter('deletion_date', None).filter('tags =', params[3]).order('-creation_date')
latest = [o for o in query.fetch(10)]
data = self.to_rss(self.getLocale("Articles labeled with %s") % params[3], latest)
elif params[3] == 'community.forum':
community = model.Community.gql('WHERE url_path=:1',params[4]).get()
if not community:
community = model.Community.gql('WHERE old_url_path=:1',params[4]).get()
threads = model.Thread.gql('WHERE community=:1 ORDER BY creation_date DESC LIMIT 20', community)
data = self.threads_to_rss(self.getLocale("Forum %s") % community.title, threads)
elif params[3] == 'community':
community = model.Community.gql('WHERE url_path=:1',params[4]).get()
if not community:
community = model.Community.gql('WHERE old_url_path=:1',params[4]).get()
community_articles = model.CommunityArticle.gql('WHERE community=:1 ORDER BY creation_date DESC LIMIT 20', community)
latest = [gi.article for gi in community_articles]
data = self.to_rss(self.getLocale("Articles by community %s") % community.title, latest)
elif params[3] == 'user':
latest = model.Article.gql('WHERE author_nickname=:1 AND draft=:2 AND deletion_date=:3 ORDER BY creation_date DESC LIMIT 20', params[4], False, None)
data = self.to_rss(self.getLocale("Articles by %s") % params[3], latest)
else:
data = self.not_found()
memcache.add(self.request.path, data, time)
self.response.headers['Content-Type'] = 'application/rss+xml'
self.response.out.write(template.render('templates/feed.xml', data))
def threads_to_rss(self, title, threads):
articles = []
url = self.get_application().url
md = markdown.Markdown()
for i in threads:
article = {
'title': i.title,
'link': "%s/module/community.forum/%s" % (url, i.url_path),
'description': md.convert(i.content),
'pubDate': self.to_rfc822(i.creation_date),
'guid':"%s/module/community.forum/%s" % (url,i.url_path),
'author': i.author_nickname
# guid como link para mantener compatibilidad con feed.xml
}
articles.append(article)
values = {
'title': title,
'self': url+self.request.path,
'link': url,
'description': '',
'articles': articles
}
return values
def posts_to_rss(self, title, list):
posts = []
url = self.get_application().url
for i in list:
post = {
'title': "%s" % i.content,
'link': "%s/module/mblog.edit/%s" % (url, i.key().id()),
'description': "%s" % i.content,
'pubDate': self.to_rfc822(i.creation_date),
'guid':"%s/module/mblog.edit/%s" % (url,i.key().id()),
'author': i.author_nickname
}
posts.append(post)
values = {
'title': title,
'self': url+self.request.path,
'link': url,
'description': '%s Microbblogging' % self.get_application().name,
'articles': posts
}
return values
def to_rss(self, title, latest):
import MediaContentFilters as contents
articles = []
url = self.get_application().url
md = markdown.Markdown()
for i in latest:
if i.author.not_full_rss:
content = md.convert(i.description)
else:
content = md.convert(i.content)
content = contents.media_content(content)
article = {
'title': i.title,
'link': "%s/module/article/%s" % (url, i.url_path),
'description': content,
'pubDate': self.to_rfc822(i.creation_date),
'guid':"%s/module/article/%d/" % (url, i.key().id()),
'author': i.author_nickname
}
articles.append(article)
values = {
'title': title,
'self': url+self.request.path,
'link': url,
'description': '',
'articles': articles
}
return values
def to_rfc822(self, date):
return date.strftime("%a, %d %b %Y %H:%M:%S GMT")
def get_application(self):
app = memcache.get('app')
import logging
if not app:
app = model.Application.all().get()
memcache.add('app', app, 0)
return app
def not_found(self):
url = self.get_application().url
values = {
'title': self.get_application().name,
'self': url,
'link': url,
'description': '',
'articles': ''
}
return values
### i18n
def getLocale(self, label):
env = AppProperties().getJinjaEnv()
t = env.get_template("/translator-util.html")
return t.render({"label": label})
| [
[
1,
0,
0.1204,
0.0052,
0,
0.66,
0,
654,
0,
1,
0,
0,
654,
0,
0
],
[
1,
0,
0.1257,
0.0052,
0,
0.66,
0.1111,
722,
0,
1,
0,
0,
722,
0,
0
],
[
1,
0,
0.1309,
0.0052,
0,
... | [
"import time",
"import model",
"import datetime",
"import markdown",
"from google.appengine.api import memcache",
"from google.appengine.ext import webapp",
"from google.appengine.ext.webapp import template",
"from time import strftime, gmtime, time",
"from utilities.AppProperties import AppProperti... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Alberto Gimeno <gimenete at gmail dot com>
#
# This file is part of "debug_mode_on".
#
# "debug_mode_on" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "debug_mode_on" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>.
#
from handlers.BaseHandler import *
class ForumList(BaseHandler):
def execute(self):
self.values['tab'] = '/forum.list'
query = model.Thread.all().filter('parent_thread', None)
app = self.get_application()
key = '%s?%s' % (self.request.path, self.request.query)
results = 10
if app.max_results:
results = app.max_results
threads = self.paging(query, results, '-last_response_date', app.threads, ['-last_response_date'], key)
# migration
for t in threads:
if not t.last_response_date:
last_response = model.Thread.all().filter('parent_thread', t).order('-creation_date').get()
if last_response:
t.last_response_date = last_response.creation_date
else:
t.last_response_date = t.creation_date
t.put()
# end migration
self.values['threads'] = threads
self.add_tag_cloud()
self.render('templates/forum-list.html')
| [
[
1,
0,
0.4792,
0.0208,
0,
0.66,
0,
437,
0,
1,
0,
0,
437,
0,
0
],
[
3,
0,
0.7604,
0.5,
0,
0.66,
1,
302,
0,
1,
0,
0,
94,
0,
11
],
[
2,
1,
0.7812,
0.4583,
1,
0.46,
... | [
"from handlers.BaseHandler import *",
"class ForumList(BaseHandler):\n\n\tdef execute(self):\n\t\tself.values['tab'] = '/forum.list'\n\t\tquery = model.Thread.all().filter('parent_thread', None)\n\t\tapp = self.get_application()\n\t\tkey = '%s?%s' % (self.request.path, self.request.query)\n\t\tresults = 10",
"\... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import time
import datetime
import re
from google.appengine.ext import db
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
class MBlogEdit(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
key = self.get_param('key')
action = self.get_param('act')
if method == 'GET':
if key:#Unused - This case is to allow edit a post and add comments in a single post page
# show edit form
post = model.Mblog.get_by_id(key)
if not post:
self.not_found()
return
if not user.nickname == post.author.nickname and user.rol != 'admin':
self.forbidden()
return
self.values['key'] = key
self.values['content'] = post.content
self.render('templates/module/mblog/mblog-edit.html')
else:
self.not_found()
return
elif self.auth():
# new post
if not action:
content = self.get_param('content')
if not content or len(content) == 0:
self.render_json({ 'saved': False, 'msg': self.getLocale('Content is empty') })
return
if len(content) > 150:
self.render_json({ 'saved': False, 'msg': self.getLocale('Content is too large') })
return
if not re.match(u"^[A-Za-z0-9_-àáèéíòóúÀÁÈÉÍÒÓÚïü: ,=\./&¿\?!¡#\(\)]*$", content):
self.render_json({ 'saved': False, 'msg': self.getLocale('Content is invalid') })
return
post = model.Mblog(author=user,
author_nickname=user.nickname,
content=content,
responses=0)
post.put()
self.render_json({ "saved": True, 'key' : str(post.key()) })
return
elif action == 'del' and key:
post = model.Mblog.get_by_id(long(key))
if not post:
self.render_json({ 'saved': False, 'msg': self.getLocale('Not found') })
return
if not user.nickname == post.author.nickname and user.rol != 'admin':
self.render_json({ 'saved': False, 'msg': self.getLocale('Not allowed') })
return
post.deletion_date = datetime.datetime.now()
post.deletion_user = user.nickname
post.put()
self.render_json({ 'saved': True })
return
else:
self.render_json({ 'saved': False, 'msg': self.getLocale('Not found') })
return
#UPDATE CACHE
| [
[
1,
0,
0.2447,
0.0106,
0,
0.66,
0,
654,
0,
1,
0,
0,
654,
0,
0
],
[
1,
0,
0.2553,
0.0106,
0,
0.66,
0.1667,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.266,
0.0106,
0,
0... | [
"import time",
"import datetime",
"import re",
"from google.appengine.ext import db",
"from google.appengine.api import memcache",
"from handlers.AuthenticatedHandler import *",
"class MBlogEdit(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tmethod = self.request.method\n\t\tuser = self.values['use... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class MessageEdit(AuthenticatedHandler):
def execute(self):
user = self.values['user']
user_to = model.UserData.all().filter('nickname', self.get_param('user_to')).get()
if not user_to:
self.not_found()
return
method = self.request.method
if method == 'GET':
self.values['user_to'] = self.get_param('user_to')
title = self.get_param('title')
if not title:
title = "New message..."
elif not title.startswith('Re:'):
title = 'Re:%s' % title
self.values['title'] = title
self.render('templates/module/message/message-edit.html')
return
elif self.auth():
title = self.get_param('title')
message = model.Message(user_from = user,
user_from_nickname = user.nickname,
user_to = user_to,
user_to_nickname = user_to.nickname,
content=self.get_param('content'),
title=self.get_param('title'),
url_path = '-',
read=False)
message.put()
message.url_path = ('%d/%s') % (message.key().id(), self.to_url_path(title))
message.put()
if not user.sent_messages:
user.sent_messages = 0
if not user_to.unread_messages:
user_to.unread_messages = 0
user.sent_messages += 1
user_to.unread_messages += 1
user.put()
user_to.put()
app = self.get_application()
subject = self.getLocale("%s has send you a missage") % user.nickname # "%s te ha enviado un mensaje"
# %s te ha enviado un mensaje.\nLeelo en:\n%s/message.inbox\n
body = self.getLocale("%s has send you a missage.\nRead it at:\n%s/message.inbox\n") % (user.nickname, app.url)
self.mail(subject=subject, body=body, to=[user_to.email])
self.redirect('/message.sent')
| [
[
1,
0,
0.2949,
0.0128,
0,
0.66,
0,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.6538,
0.6795,
0,
0.66,
1,
482,
0,
1,
0,
0,
116,
0,
26
],
[
2,
1,
0.6667,
0.6538,
1,
0.19... | [
"from handlers.AuthenticatedHandler import *",
"class MessageEdit(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tuser = self.values['user']\n\t\tuser_to = model.UserData.all().filter('nickname', self.get_param('user_to')).get()\n\t\tif not user_to:\n\t\t\tself.not_found()\n\t\t\treturn",
"\tdef execute(sel... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import datetime
from handlers.AuthenticatedHandler import *
class MessageDelete(AuthenticatedHandler):
def execute(self):
user = self.values['user']
key = self.request.get('key')
message = model.Message.get(key)
if not message:
self.not_found()
return
if not self.auth():
return
if user.nickname == message.user_to_nickname:
message.to_deletion_date = datetime.datetime.now()
message.put()
self.redirect('/message.inbox')
elif user.nickname == message.user_from_nickname:
message.from_deletion_date = datetime.datetime.now()
message.put()
self.redirect('/message.sent')
else:
self.forbidden() | [
[
1,
0,
0.4694,
0.0204,
0,
0.66,
0,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.5102,
0.0204,
0,
0.66,
0.5,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.7755,
0.4694,
0,
0.6... | [
"import datetime",
"from handlers.AuthenticatedHandler import *",
"class MessageDelete(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tuser = self.values['user']\n\t\tkey = self.request.get('key')\n\t\tmessage = model.Message.get(key)\n\t\tif not message:\n\t\t\tself.not_found()",
"\tdef execute(self):\n\... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class MessageRead(AuthenticatedHandler):
def execute(self):
user = self.values['user']
url_path = self.request.path.split('/', 2)[2]
message = model.Message.gql('WHERE url_path=:1', url_path).get()
if message.user_to_nickname != user.nickname and message.user_from_nickname != user.nickname:
self.forbidden()
return
if message.user_to_nickname == user.nickname and not message.read:
message.read = True
message.put()
user.unread_messages -= 1
user.put()
self.values['message'] = message
self.render('templates/module/message/message-read.html') | [
[
1,
0,
0.5476,
0.0238,
0,
0.66,
0,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.7976,
0.4286,
0,
0.66,
1,
720,
0,
1,
0,
0,
116,
0,
7
],
[
2,
1,
0.8214,
0.381,
1,
0.42,
... | [
"from handlers.AuthenticatedHandler import *",
"class MessageRead(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tuser = self.values['user']\n\t\turl_path = self.request.path.split('/', 2)[2]\n\t\tmessage = model.Message.gql('WHERE url_path=:1', url_path).get()\n\t\tif message.user_to_nickname != user.nicknam... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class MessageInbox(AuthenticatedHandler):
def execute(self):
user = self.values['user']
query = model.Message.all().filter('user_to', user).filter('to_deletion_date', None)
self.values['messages'] = self.paging(query, 10, '-creation_date', user.messages, ['-creation_date'])
self.render('templates/module/message/message-inbox.html')
| [
[
1,
0,
0.7188,
0.0312,
0,
0.66,
0,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.875,
0.2188,
0,
0.66,
1,
190,
0,
1,
0,
0,
116,
0,
5
],
[
2,
1,
0.9062,
0.1562,
1,
0.12,
... | [
"from handlers.AuthenticatedHandler import *",
"class MessageInbox(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tuser = self.values['user']\n\t\tquery = model.Message.all().filter('user_to', user).filter('to_deletion_date', None)\n\t\tself.values['messages'] = self.paging(query, 10, '-creation_date', user.m... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class MessageSent(AuthenticatedHandler):
def execute(self):
user = self.values['user']
query = model.Message.all().filter('user_from', user).filter('from_deletion_date', None)
self.values['messages'] = self.paging(query, 10, '-creation_date', user.sent_messages, ['-creation_date'])
self.render('templates/module/message/message-sent.html')
| [
[
1,
0,
0.7188,
0.0312,
0,
0.66,
0,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.875,
0.2188,
0,
0.66,
1,
49,
0,
1,
0,
0,
116,
0,
5
],
[
2,
1,
0.9062,
0.1562,
1,
0.31,
... | [
"from handlers.AuthenticatedHandler import *",
"class MessageSent(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tuser = self.values['user']\n\t\tquery = model.Message.all().filter('user_from', user).filter('from_deletion_date', None)\n\t\tself.values['messages'] = self.paging(query, 10, '-creation_date', use... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
from google.appengine.api import users
class UserFavourites(BaseHandler):
def execute(self):
self.values['tab'] = '/module/user.list'
nickname = self.request.path.split('/')[3]
this_user = model.UserData.gql('WHERE nickname=:1', nickname).get()
if not this_user:
self.not_found()
return
# TODO: not show if the user profile is not public
self.values['this_user'] = this_user
query = model.Favourite.all().filter('user', this_user)
favs = self.paging(query, 10, '-creation_date', this_user.favourites, ['-creation_date'])
self.values['favourites'] = favs
self.render('templates/module/user/user-favourites.html')
| [
[
1,
0,
0.575,
0.025,
0,
0.66,
0,
437,
0,
1,
0,
0,
437,
0,
0
],
[
1,
0,
0.6,
0.025,
0,
0.66,
0.5,
279,
0,
1,
0,
0,
279,
0,
0
],
[
3,
0,
0.825,
0.375,
0,
0.66,
1... | [
"from handlers.BaseHandler import *",
"from google.appengine.api import users",
"class UserFavourites(BaseHandler):\n\n\tdef execute(self):\n\t\tself.values['tab'] = '/module/user.list'\n\t\tnickname = self.request.path.split('/')[3]\n\t\tthis_user = model.UserData.gql('WHERE nickname=:1', nickname).get()\n\t\t... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import model
from handlers.BaseHandler import *
class UserResetPassword(BaseHandler):
def execute(self):
method = self.request.method
if method == 'GET':
nickname = self.request.get('nickname')
token = self.request.get('token')
u = model.UserData.all().filter('nickname =', nickname).filter('token =', token).get()
if not u:
self.render('templates/module/user/user-resetpassword-error.html')
else:
self.values['token'] = token
self.values['nickname'] = nickname
self.render('templates/module/user/user-resetpassword.html')
else:
token = self.request.get('token')
nickname = self.request.get('nickname')
password = self.request.get('password')
re_password = self.request.get('re_password')
if not password or len(password) < 4:
self.show_error(nickname, token, "Password must contain 4 chars at least")
return
if password != re_password:
self.show_error(nickname, token, "New password and validation password are not equal")
return
u = model.UserData.all().filter('nickname =', nickname).filter('token =', token).get()
if not u:
self.render('templates/module/user/user-resetpassword-error.html')
return
u.token = None
u.password = self.hash_password(nickname, password)
u.put()
self.render('templates/module/user/user-resetpassword-login.html')
def show_error(self, nickname, token, error):
self.values['nickname'] = nickname
self.values['token'] = token
self.values['error'] = error
self.render('templates/module/user/user-resetpassword.html') | [
[
1,
0,
0.3333,
0.0145,
0,
0.66,
0,
722,
0,
1,
0,
0,
722,
0,
0
],
[
1,
0,
0.3478,
0.0145,
0,
0.66,
0.5,
437,
0,
1,
0,
0,
437,
0,
0
],
[
3,
0,
0.6884,
0.6377,
0,
0.6... | [
"import model",
"from handlers.BaseHandler import *",
"class UserResetPassword(BaseHandler):\n\n\tdef execute(self):\n\t\tmethod = self.request.method\n\n\t\tif method == 'GET':\n\t\t\tnickname = self.request.get('nickname')\n\t\t\ttoken = self.request.get('token')",
"\tdef execute(self):\n\t\tmethod = self.r... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
from google.appengine.api import users
class UserEvents(AuthenticatedHandler):
def execute(self):
user = self.get_current_user()
query = model.Event.all().filter('followers', user.nickname)
self.values['events'] = self.paging(query, 10, '-creation_date')
self.render('templates/module/user/user-events.html')
| [
[
1,
0,
0.7188,
0.0312,
0,
0.66,
0,
548,
0,
1,
0,
0,
548,
0,
0
],
[
1,
0,
0.75,
0.0312,
0,
0.66,
0.5,
279,
0,
1,
0,
0,
279,
0,
0
],
[
3,
0,
0.9062,
0.2188,
0,
0.66,... | [
"from handlers.AuthenticatedHandler import *",
"from google.appengine.api import users",
"class UserEvents(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tuser = self.get_current_user()\n\t\tquery = model.Event.all().filter('followers', user.nickname)\n\t\tself.values['events'] = self.paging(query, 10, '-cr... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class UserPromote(AuthenticatedHandler):
def execute(self):
self.values['tab'] = '/module/user.list'
user = self.values['user']
app = self.get_application()
self.values['user_url'] = '%s/module/user/%s' % (app.url, user.nickname)
self.render('templates/module/user/user-promote.html')
| [
[
1,
0,
0.7188,
0.0312,
0,
0.66,
0,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.8906,
0.25,
0,
0.66,
1,
580,
0,
1,
0,
0,
116,
0,
2
],
[
2,
1,
0.9219,
0.1875,
1,
0.7,
... | [
"from handlers.AuthenticatedHandler import *",
"class UserPromote(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tself.values['tab'] = '/module/user.list'\n\t\tuser = self.values['user']\n\t\tapp = self.get_application()\n\t\tself.values['user_url'] = '%s/module/user/%s' % (app.url, user.nickname)\n\t\tself.r... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.api import mail
from handlers.AuthenticatedHandler import *
class UserContact(AuthenticatedHandler):
def execute(self):
user = self.values['user']
user_to = model.UserData.all().filter('nickname', self.get_param('user_to')).get()
if not user_to:
self.not_found()
return
if not self.auth():
return
contact = model.Contact.all().filter('user_from', user).filter('user_to', user_to).get()
if not contact:
contact = model.Contact(user_from=user,
user_to=user_to,
user_from_nickname=user.nickname,
user_to_nickname=user_to.nickname)
contact.put()
user.contacts += 1
user.put()
self.add_follower(user=user_to, nickname=user.nickname)
followers = list(self.get_followers(user=user))
followers.append(user.nickname)
if not user_to.nickname in followers:
followers.append(user_to.nickname)
self.create_event(event_type='contact.add', followers=followers, user=user, user_to=user_to)
app = self.get_application()
subject = self.getLocale("%s has added you as contact") % user.nickname # "%s te ha agregado como contacto"
# %s te ha agregado como contacto en %s\nPuedes visitar su perfil en: %s/module/user/%s\n
body = self.getLocale("%s has added you as contact in %s\nVisit profile page: %s/module/user/%s\n") % (user.nickname, app.url, app.url, user.nickname)
self.mail(subject=subject, body=body, to=[user_to.email])
if self.get_param('x'):
self.render_json({ 'action': 'added' })
else:
self.redirect('/module/user/%s' % user_to.nickname)
else:
contact.delete()
user.contacts -= 1
user.put()
self.remove_follower(user=user_to, nickname=user.nickname)
if self.get_param('x'):
self.render_json({ 'action': 'deleted' })
else:
self.redirect('/module/user/%s' % user_to.nickname)
| [
[
1,
0,
0.3067,
0.0133,
0,
0.66,
0,
279,
0,
1,
0,
0,
279,
0,
0
],
[
1,
0,
0.32,
0.0133,
0,
0.66,
0.5,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.6733,
0.6667,
0,
0.66,... | [
"from google.appengine.api import mail",
"from handlers.AuthenticatedHandler import *",
"class UserContact(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tuser = self.values['user']\n\t\tuser_to = model.UserData.all().filter('nickname', self.get_param('user_to')).get()\n\t\tif not user_to:\n\t\t\tself.not_f... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
from google.appengine.api import users
class UserArticles(BaseHandler):
def execute(self):
self.values['tab'] = '/module/user.list'
nickname = self.request.path.split('/')[3]
this_user = model.UserData.gql('WHERE nickname=:1', nickname).get()
if not this_user:
self.not_found()
return
# TODO: not show if the user profile is not public
self.values['this_user'] = this_user
query = model.Article.all().filter('author =', this_user).filter('draft =', False).filter('deletion_date', None)
self.values['articles'] = self.paging(query, 10, '-creation_date', this_user.articles, ['-creation_date'])
self.render('templates/module/user/user-articles.html')
| [
[
1,
0,
0.5897,
0.0256,
0,
0.66,
0,
437,
0,
1,
0,
0,
437,
0,
0
],
[
1,
0,
0.6154,
0.0256,
0,
0.66,
0.5,
279,
0,
1,
0,
0,
279,
0,
0
],
[
3,
0,
0.8333,
0.359,
0,
0.66... | [
"from handlers.BaseHandler import *",
"from google.appengine.api import users",
"class UserArticles(BaseHandler):\n\n\tdef execute(self):\n\t\tself.values['tab'] = '/module/user.list'\n\t\tnickname = self.request.path.split('/')[3]\n\t\tthis_user = model.UserData.gql('WHERE nickname=:1', nickname).get()\n\t\tif... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import img
from google.appengine.ext import db
from google.appengine.api import images
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
class UserEdit(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
if method == 'GET':
self.values['google_adsense'] = self.not_none(user.google_adsense)
self.values['google_adsense_channel'] = self.not_none(user.google_adsense_channel)
self.values['real_name'] = self.not_none(user.real_name)
self.values['links'] = [(link.split('##', 2)[1], link.split('##', 2)[0]) for link in user.list_urls]
self.values['im_addresses'] = [(link.split('##', 2)[1], link.split('##', 2)[0]) for link in user.im_addresses]
self.values['country'] = self.not_none(user.country)
self.values['city'] = self.not_none(user.city)
self.values['about'] = self.not_none(user.about_user)
self.values['personal_message'] = self.not_none(user.personal_message);
if user.not_full_rss:
self.values['not_full_rss'] = user.not_full_rss
self.render('templates/module/user/user-edit.html')
elif self.auth():
user.google_adsense = self.get_param('google_adsense')
user.google_adsense_channel = self.get_param('google_adsense_channel')
user.real_name = self.get_param('real_name')
user.personal_message = self.get_param('personal_message')
user.country = self.get_param('country')
if self.get_param('not_full_rss'):
user.not_full_rss = True
else:
user.not_full_rss = False
image = self.request.get("img")
if image:
image = images.im_feeling_lucky(image, images.JPEG)
user.avatar = img.resize(image, 128, 128)
user.thumbnail = img.resize(image, 48, 48)
if not user.image_version:
user.image_version = 1
else:
memcache.delete('/images/user/avatar/%s/%d' % (user.nickname, user.image_version))
memcache.delete('/images/user/thumbnail/%s/%d' % (user.nickname, user.image_version))
user.image_version += 1
memcache.delete('/images/user/avatar/%s' % (user.nickname))
memcache.delete('/images/user/thumbnail/%s' % (user.nickname))
user.city = self.get_param('city')
user.list_urls = []
blog = self.get_param('blog')
if blog:
if not blog.startswith('http'):
linkedin = 'http://' + blog
user.list_urls.append(blog + '##blog')
linkedin = self.get_param('linkedin')
if linkedin:
if not linkedin.startswith('http'):
linkedin = 'http://' + linkedin
user.list_urls.append(linkedin + '##linkedin')
ohloh = self.get_param('ohloh')
if ohloh:
if not ohloh.startswith('http'):
linkedin = 'http://' + ohloh
user.list_urls.append(ohloh + '##ohloh')
user.im_addresses = []
msn = self.get_param('msn')
if msn:
user.im_addresses.append(msn + '##msn')
jabber = self.get_param('jabber')
if jabber:
user.im_addresses.append(jabber + '##jabber')
gtalk = self.get_param('gtalk')
if gtalk:
user.im_addresses.append(gtalk + '##gtalk')
user.about_user = self.get_param('about_user')
user.put()
followers = list(self.get_followers(user=user))
followers.append(user.nickname)
self.create_event(event_type='user.edit', followers=followers, user=user)
self.redirect('/module/user/%s' % user.nickname)
| [
[
1,
0,
0.2,
0.0087,
0,
0.66,
0,
200,
0,
1,
0,
0,
200,
0,
0
],
[
1,
0,
0.2174,
0.0087,
0,
0.66,
0.2,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.2261,
0.0087,
0,
0.66,
... | [
"import img",
"from google.appengine.ext import db",
"from google.appengine.api import images",
"from google.appengine.api import memcache",
"from handlers.AuthenticatedHandler import *",
"class UserEdit(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tmethod = self.request.method\n\t\tuser = self.valu... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
from google.appengine.api import users
class UserForums(BaseHandler):
def execute(self):
self.values['tab'] = '/module/user.list'
nickname = self.request.path.split('/')[3]
this_user = model.UserData.gql('WHERE nickname=:1', nickname).get()
if not this_user:
self.not_found()
return
# TODO: not show if the user profile is not public
self.values['this_user'] = this_user
query = model.Thread.all().filter('author', this_user).filter('parent_thread', None)
self.values['threads'] = self.paging(query, 10, '-creation_date', this_user.threads, ['-creation_date'])
self.render('templates/module/user/user-forums.html')
| [
[
1,
0,
0.5897,
0.0256,
0,
0.66,
0,
437,
0,
1,
0,
0,
437,
0,
0
],
[
1,
0,
0.6154,
0.0256,
0,
0.66,
0.5,
279,
0,
1,
0,
0,
279,
0,
0
],
[
3,
0,
0.8333,
0.359,
0,
0.66... | [
"from handlers.BaseHandler import *",
"from google.appengine.api import users",
"class UserForums(BaseHandler):\n\n\tdef execute(self):\n\t\tself.values['tab'] = '/module/user.list'\n\t\tnickname = self.request.path.split('/')[3]\n\t\tthis_user = model.UserData.gql('WHERE nickname=:1', nickname).get()\n\t\tif n... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
from google.appengine.api import users
class UserDrafts(AuthenticatedHandler):
def execute(self):
user = self.get_current_user()
query = model.Article.all().filter('author =', user).filter('draft =', True).filter('deletion_date', None)
self.values['articles'] = self.paging(query, 10, '-last_update', user.draft_articles, ['-last_update'])
self.render('templates/module/user/user-drafts.html')
| [
[
1,
0,
0.7188,
0.0312,
0,
0.66,
0,
548,
0,
1,
0,
0,
548,
0,
0
],
[
1,
0,
0.75,
0.0312,
0,
0.66,
0.5,
279,
0,
1,
0,
0,
279,
0,
0
],
[
3,
0,
0.9062,
0.2188,
0,
0.66,... | [
"from handlers.AuthenticatedHandler import *",
"from google.appengine.api import users",
"class UserDrafts(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tuser = self.get_current_user()\n\t\tquery = model.Article.all().filter('author =', user).filter('draft =', True).filter('deletion_date', None)\n\t\tself.... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import datetime
from handlers.BaseHandler import *
from google.appengine.api import users
class UserList(BaseHandler):
def execute(self):
self.values['tab'] = '/module/user.list'
app = self.get_application()
query = model.UserData.all()
key = '%s?%s' % (self.request.path, self.request.query)
results = 10
if app.max_results:
results = app.max_results
users = self.paging(query, results, '-articles', app.users, ['-creation_date', '-articles'], key)
if users is not None:
self.values['users'] = users
self.add_tag_cloud()
self.render('templates/module/user/user-list.html')
| [
[
1,
0,
0.5476,
0.0238,
0,
0.66,
0,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.5952,
0.0238,
0,
0.66,
0.3333,
437,
0,
1,
0,
0,
437,
0,
0
],
[
1,
0,
0.619,
0.0238,
0,
0... | [
"import datetime",
"from handlers.BaseHandler import *",
"from google.appengine.api import users",
"class UserList(BaseHandler):\n\n\tdef execute(self):\n\t\tself.values['tab'] = '/module/user.list'\n\t\tapp = self.get_application()\n\t\tquery = model.UserData.all()\n\t\tkey = '%s?%s' % (self.request.path, se... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import re
import model
from img import *
from utilities import session
from google.appengine.ext import webapp
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class UserChangePassword(AuthenticatedHandler):
def execute(self):
method = self.request.method
if method == 'GET':
self.values['redirect_to'] = self.request.get('redirect_to')
self.render('templates/module/user/user-changepassword.html')
elif self.auth():
old_password = self.request.get('old_password')
password = self.request.get('password')
re_password = self.request.get('re_password')
if not password or len(password) < 4:
self.show_error( "Password must contain 4 chars at least")
return
if password != re_password:
self.show_error("New password and validation password are not equal")
return
user = self.values['user']
if self.check_password(user, old_password):
user.password = self.hash_password(user.nickname, password)
user.put()
rt = self.request.get('redirect_to')
if not rt:
rt = '/'
self.redirect(rt)
else:
self.show_error("Incorrect password")
return
def show_error(self, error):
self.values['error'] = error
self.render('templates/module/user/user-changepassword.html') | [
[
1,
0,
0.3382,
0.0147,
0,
0.66,
0,
540,
0,
1,
0,
0,
540,
0,
0
],
[
1,
0,
0.3529,
0.0147,
0,
0.66,
0.1429,
722,
0,
1,
0,
0,
722,
0,
0
],
[
1,
0,
0.3824,
0.0147,
0,
... | [
"import re",
"import model",
"from img import *",
"from utilities import session",
"from google.appengine.ext import webapp",
"from google.appengine.ext import db",
"from handlers.AuthenticatedHandler import *",
"class UserChangePassword(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tmethod = sel... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
from google.appengine.api import users
class UserContacts(BaseHandler):
def execute(self):
self.values['tab'] = '/module/user.list'
nickname = self.request.path.split('/')[3]
this_user = model.UserData.gql('WHERE nickname=:1', nickname).get()
if not this_user:
self.not_found()
return
# TODO: not show if the user profile is not public
self.values['this_user'] = this_user
query = model.Contact.all().filter('user_from', this_user)
contacts = self.paging(query, 27, '-creation_date', this_user.contacts, ['-creation_date'])
self.values['users'] = contacts
self.render('templates/module/user/user-contacts.html')
| [
[
1,
0,
0.575,
0.025,
0,
0.66,
0,
437,
0,
1,
0,
0,
437,
0,
0
],
[
1,
0,
0.6,
0.025,
0,
0.66,
0.5,
279,
0,
1,
0,
0,
279,
0,
0
],
[
3,
0,
0.825,
0.375,
0,
0.66,
1... | [
"from handlers.BaseHandler import *",
"from google.appengine.api import users",
"class UserContacts(BaseHandler):\n\n\tdef execute(self):\n\t\tself.values['tab'] = '/module/user.list'\n\t\tnickname = self.request.path.split('/')[3]\n\t\tthis_user = model.UserData.gql('WHERE nickname=:1', nickname).get()\n\t\tif... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
from google.appengine.api import users
class UserView(BaseHandler):
def execute(self):
self.values['tab'] = '/module/user.list'
nickname = self.request.path.split('/')[3]
this_user = model.UserData.gql('WHERE nickname=:1', nickname).get()
if not this_user:
self.not_found()
return
# TODO: not show if the user profile is not public
user = self.values['user']
contact = False
if user and user.nickname != this_user.nickname:
self.values['canadd'] = True
contact = self.is_contact(this_user)
self.values['is_contact'] = contact
if (user is not None and this_user.nickname == user.nickname) or contact:
self.values['im_addresses'] = [(link.split('##', 2)[1], link.split('##', 2)[0]) for link in this_user.im_addresses]
else:
self.values['im_addresses'] = []
self.values['this_user'] = this_user
linksChanged = False
counter = 0
for link in this_user.list_urls:
if not link.startswith('http'):
linksChanged = True
link = 'http://' + link
this_user.list_urls[counter] = link
if link.startswith('http://https://'):
linksChanged = True
link = link[7:len(link)]
this_user.list_urls[counter] = link
counter += 1
if linksChanged:
this_user.put()
links = [(link.split('##', 2)[1], link.split('##', 2)[0]) for link in this_user.list_urls]
self.values['links'] = links
self.values['personal_message'] = this_user.personal_message
self.values['articles'] = model.Article.all().filter('author =', this_user).filter('draft =', False).filter('deletion_date', None).order('-creation_date').fetch(5)
self.values['communities'] = model.CommunityUser.all().filter('user =', this_user).order('-creation_date').fetch(18)
self.values['contacts'] = model.Contact.all().filter('user_from', this_user).order('-creation_date').fetch(18)
self.render('templates/module/user/user-view.html')
| [
[
1,
0,
0.3333,
0.0145,
0,
0.66,
0,
437,
0,
1,
0,
0,
437,
0,
0
],
[
1,
0,
0.3478,
0.0145,
0,
0.66,
0.5,
279,
0,
1,
0,
0,
279,
0,
0
],
[
3,
0,
0.6884,
0.6377,
0,
0.6... | [
"from handlers.BaseHandler import *",
"from google.appengine.api import users",
"class UserView(BaseHandler):\n\n\tdef execute(self):\n\t\tself.values['tab'] = '/module/user.list'\n\t\tnickname = self.request.path.split('/')[3]\n\t\tthis_user = model.UserData.gql('WHERE nickname=:1', nickname).get()\n\t\tif not... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import model
from handlers.BaseHandler import *
from google.appengine.api import users
class UserLogout(BaseHandler):
def execute(self):
#Check if google account is in use
#User registered with different user in vikuit and google
user = users.get_current_user()
userLocalId = self.sess.user
googleAc = False
if user and userLocalId:
userLocal = db.get(userLocalId)
if userLocal and user.email() == userLocal.email:
googleAc = True
redirect = '/'
try:
if self.auth():
self.sess.store('', 0)
if self.request.referrer:
redirect = self.request.referrer
except KeyError:
self.redirect(redirect)
return
if googleAc:
self.redirect(users.create_logout_url(redirect))
else:
self.redirect(redirect) | [
[
1,
0,
0.4259,
0.0185,
0,
0.66,
0,
722,
0,
1,
0,
0,
722,
0,
0
],
[
1,
0,
0.4444,
0.0185,
0,
0.66,
0.3333,
437,
0,
1,
0,
0,
437,
0,
0
],
[
1,
0,
0.463,
0.0185,
0,
0... | [
"import model",
"from handlers.BaseHandler import *",
"from google.appengine.api import users",
"class UserLogout(BaseHandler):\n\n\tdef execute(self):\n\t\t#Check if google account is in use\n\t\t#User registered with different user in vikuit and google\n\t\tuser = users.get_current_user()\n\t\tuserLocalId =... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import model
import random
from handlers.BaseHandler import *
from google.appengine.api import mail
from utilities.AppProperties import AppProperties
class UserForgotPassword(BaseHandler):
def execute(self):
method = self.request.method
if method == 'GET':
self.values['redirect_to'] = self.request.get('redirect_to')
self.render('templates/module/user/user-forgotpassword.html')
else:
email = self.request.get('email')
u = model.UserData.all().filter('email =', email).get()
if not u:
self.show_error(email, "No user found with this mail")
return
# only local accounts can reset password
app = self.get_application()
subject = self.getLocale("Password recovery")#u"Recuperar password"
if u.registrationType is None or u.registrationType == 0:
u.token = self.hash(str(random.random()), email)
u.put()
#Haz click en el siguiente enlace para proceder a establecer tu password.\n%s/module/user.resetpassword?nickname=%s&token=%s
body = self.getLocale("Click this link to set your password.\n%s/module/user.resetpassword?nickname=%s&token=%s") % (app.url, u.nickname, u.token)
else:
accountProvider = AppProperties().getAccountProvider(u.registrationType)
body = self.getLocale("You have requested to recover password but credentials you use in %s are from %s. Review your login information.") % (app.name, accountProvider)
self.mail(subject=subject, body=body, to=[u.email])
self.values['token'] = u.token
self.values['email'] = email
self.values['redirect_to'] = self.request.get('redirect_to')
self.render('templates/module/user/user-forgotpassword-sent.html')
def show_error(self, email, error):
self.values['email'] = email
self.values['error'] = error
self.render('templates/module/user/user-forgotpassword.html') | [
[
1,
0,
0.3433,
0.0149,
0,
0.66,
0,
722,
0,
1,
0,
0,
722,
0,
0
],
[
1,
0,
0.3582,
0.0149,
0,
0.66,
0.2,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.3881,
0.0149,
0,
0.6... | [
"import model",
"import random",
"from handlers.BaseHandler import *",
"from google.appengine.api import mail",
"from utilities.AppProperties import AppProperties",
"class UserForgotPassword(BaseHandler):\n\n\tdef execute(self):\n\t\tmethod = self.request.method\n\t\t\n\t\tif method == 'GET':\n\t\t\tself.... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
from google.appengine.api import users
class UserCommunities(BaseHandler):
def execute(self):
self.values['tab'] = '/module/user.list'
nickname = self.request.path.split('/')[3]
this_user = model.UserData.gql('WHERE nickname=:1', nickname).get()
if not this_user:
self.not_found()
return
# TODO: not show if the user profile is not public
self.values['this_user'] = this_user
query = model.CommunityUser.all().filter('user', this_user)
communities = self.paging(query, 10, '-creation_date', this_user.communities, ['-creation_date'])
self.values['communities'] = communities
self.render('templates/module/user/user-communities.html')
| [
[
1,
0,
0.575,
0.025,
0,
0.66,
0,
437,
0,
1,
0,
0,
437,
0,
0
],
[
1,
0,
0.6,
0.025,
0,
0.66,
0.5,
279,
0,
1,
0,
0,
279,
0,
0
],
[
3,
0,
0.825,
0.375,
0,
0.66,
1... | [
"from handlers.BaseHandler import *",
"from google.appengine.api import users",
"class UserCommunities(BaseHandler):\n\n\tdef execute(self):\n\t\tself.values['tab'] = '/module/user.list'\n\t\tnickname = self.request.path.split('/')[3]\n\t\tthis_user = model.UserData.gql('WHERE nickname=:1', nickname).get()\n\t\... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import re
import random
import model
from handlers.BaseHandler import *
from os import environ
from recaptcha import captcha
class UserRegister(BaseHandler):
def execute(self):
method = self.request.method
if method == 'GET':
self.send_form(None)
else:
if self.get_param('x'):
# check if nickname is available
nickname = self.request.get('nickname')
email = self.request.get('email')
message = self.validate_nickname(nickname)
if message:
self.render_json({'valid': False, 'message': message})
else :
self.render_json({'valid': True })
return
else:
# Validate captcha
challenge = self.request.get('recaptcha_challenge_field')
response = self.request.get('recaptcha_response_field')
remoteip = environ['REMOTE_ADDR']
cResponse = captcha.submit(
challenge,
response,
self.get_application().recaptcha_private_key,
remoteip)
if not cResponse.is_valid:
# If the reCAPTCHA server can not be reached,
# the error code recaptcha-not-reachable will be returned.
self.send_form(cResponse.error_code)
return
nickname = self.request.get('nickname')
email = self.request.get('email')
password = self.request.get('password')
re_email = self.request.get('re_email')
re_password = self.request.get('re_password')
if not self.get_param('terms-and-conditions'):
self.show_error(nickname, email, "You must accept terms and conditions" )
return
if not re.match('^[\w\.-]{3,}@([\w-]{2,}\.)*([\w-]{2,}\.)[\w-]{2,4}$', email):
self.show_error(nickname, email, "Enter a valid mail" )
return
if not re.match('^[\w\.-]+$', nickname):
self.show_error(nickname, email, "Username can contain letters, numbers, dots, hyphens and underscores" )
return
if not password or len(password) < 4 or len(password) > 30:
self.show_error(nickname, email, "Password must contain between 4 and 30 chars" )
return
message = self.validate_nickname(nickname)
if message:
self.show_error(nickname, email, message)
return
u = model.UserData.all().filter('email =', email).get()
if u:
self.show_error(nickname, email, "This mail already exists" )
return
if email != re_email:
self.show_error(nickname, email, "Mail and validation mail are not equals" )
return
if password != re_password:
self.show_error(nickname, email, "New password and validation password are not equal" )
return
times = 5
user = model.UserData(nickname=nickname,
email=email,
password=self.hash_password(nickname, password),
articles=0,
draft_articles=0,
messages=0,
draft_messages=0,
comments=0,
rating_count=0,
rating_total=0,
rating_average=0,
threads=0,
responses=0,
communities=0,
favourites=0,
public=False,
contacts=0)
user.registrationType = 0#local identifier
user.put()
app = model.Application.all().get()
if app:
app.users += 1
app.put()
memcache.delete('app')
#send welcome email
app = self.get_application()
subject = self.getLocale("Welcome to %s") % app.name
bt = "Thanks for signing in %s. %s team welcome you to our social network. \n\nComplete your profile \n%s/module/user.edit\n\nPublish articles, \n\n\nBe part of the communities that interest you. Each community has a forum to share or discuss with people to whom the same interests as you.\nCommunities list %s/module/community.list\nThread list %s/forum.list\n\n\n\nFor futher information check our FAQ page\n%s/html/faq.html\n\nBest regards,\n\n%s Team."
body = self.getLocale(bt) % (app.name, app.name, app.url, app.url, app.url, app.url, app.name)
self.mail(subject=subject, body=body, to=[user.email])
self.sess.store(str(user.key()), 7200)
rt = self.request.get('redirect_to')
if not rt:
rt = '/'
self.redirect(rt)
def show_error(self, nickname, email, error):
chtml = self.get_captcha(None)
self.values['captchahtml'] = chtml
self.values['nickname'] = nickname
self.values['email'] = email
self.values['error'] = error
self.render('templates/module/user/user-register.html')
def match(self, pattern, value):
m = re.match(pattern, value)
if not m or not m.string[m.start():m.end()] == value:
return None
return value
def send_form(self, error):
chtml = self.get_captcha(error)
self.values['captchahtml'] = chtml
self.values['redirect_to'] = self.request.get('redirect_to')
self.render('templates/module/user/user-register.html')
def get_captcha(self, error):
chtml = captcha.displayhtml(
public_key = self.get_application().recaptcha_public_key,
use_ssl = False,
error = error)
return chtml
def validate_nickname(self, nickname):
if len(nickname) < 4:
return self.getLocale("Username must contain 4 chars at least")
if len(nickname) > 20:
return self.getLocale("Username must contain less than 20 chars")
u = model.UserData.all().filter('nickname =', nickname).get()
if u:
return self.getLocale("User already exists")
return '' | [
[
1,
0,
0.125,
0.0054,
0,
0.66,
0,
540,
0,
1,
0,
0,
540,
0,
0
],
[
1,
0,
0.1304,
0.0054,
0,
0.66,
0.1667,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.1359,
0.0054,
0,
0... | [
"import re",
"import random",
"import model",
"from handlers.BaseHandler import *",
"from os import environ",
"from recaptcha import captcha",
"class UserRegister(BaseHandler):\n\n\tdef execute(self):\n\t\tmethod = self.request.method\n\t\tif method == 'GET':\n\t\t\tself.send_form(None)\n\t\telse:\n\t\t... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import model
import random
import datetime
from handlers.BaseHandler import *
class UserLogin(BaseHandler):
def execute(self):
self.sess.valid = False
method = self.request.method
if method == 'GET':
self.values['redirect_to'] = self.request.get('redirect_to')
self.render('templates/module/user/user-login.html')
else:
nickname = self.request.get('nickname')
password = self.request.get('password')
user = model.UserData.gql('WHERE nickname=:1', nickname).get()
if user:
if user.registrationType is not None and user.registrationType > 0:
self.show_error("", "Invalid login method")
return##No es posible cambiar el pass si el user no es de vikuit
if self.check_password(user, password):
if user.banned_date is not None:
self.show_error(nickname, "User '%s' was blocked. Contact with an administrator.")
return
user.last_login = datetime.datetime.now()
user.password = self.hash_password(user.nickname, password) # if you want to change the way the password is hashed
user.put()
if self.get_param('remember') == 'remember':
expires = 1209600
else:
expires = 7200
self.sess.store(str(user.key()), expires)
rt = self.request.get('redirect_to')
if rt:
if rt.find("user.login") >-1:
self.redirect('/')
else:
self.redirect(rt)
else:
self.redirect('/')
else:
self.show_error("", "Invalid user or password")
else:
self.show_error("", "Invalid user or password")
def show_error(self, nickname, error):
self.values['nickname'] = nickname
self.values['error'] = error
self.render('templates/module/user/user-login.html') | [
[
1,
0,
0.2933,
0.0133,
0,
0.66,
0,
722,
0,
1,
0,
0,
722,
0,
0
],
[
1,
0,
0.3067,
0.0133,
0,
0.66,
0.25,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.32,
0.0133,
0,
0.66... | [
"import model",
"import random",
"import datetime",
"from handlers.BaseHandler import *",
"class UserLogin(BaseHandler):\n\t\n\tdef execute(self):\n\t\tself.sess.valid = False\n\t\t\n\t\tmethod = self.request.method\n\t\t\n\t\tif method == 'GET':",
"\tdef execute(self):\n\t\tself.sess.valid = False\n\t\t\... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class AdminUsers(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
if method == 'GET':
self.render('templates/module/admin/admin-users.html')
elif self.auth():
nickname = self.get_param('nickname')
if nickname is None or nickname == '':
self.values['m'] = "Complete Nickname field"
self.render('/admin-users.html')
return
u = model.UserData.all().filter('nickname', nickname).get()
if u is None:
self.values['m'] = "User '%s' doesn't exists"
self.values['arg'] = nickname
self.render('/admin-users.html')
return
action = self.get_param('action')
if action == 'block_user':
u.banned_date = datetime.datetime.now()
u.put()
self.values['m'] = "User '%s' was blocked"
self.values['arg'] = nickname
elif action == 'unblock_user':
u.banned_date = None
u.put()
self.values['m'] = "User '%s' was unlocked"
self.values['arg'] = nickname
else:
self.values['m'] = "Action '%s' not found"
self.values['arg'] = action
self.render('/admin-users.html') | [
[
1,
0,
0.3692,
0.0154,
0,
0.66,
0,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.7,
0.6154,
0,
0.66,
1,
169,
0,
1,
0,
0,
116,
0,
14
],
[
2,
1,
0.7154,
0.5846,
1,
0.81,
... | [
"from handlers.AuthenticatedHandler import *",
"class AdminUsers(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tmethod = self.request.method\n\t\tuser = self.values['user']\n\t\tself.values['tab'] = '/admin'\n\t\t\n\t\tif user.rol != 'admin':",
"\tdef execute(self):\n\t\tmethod = self.request.method\n\t\tu... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
# (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com>
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import img
from google.appengine.api import images
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
from utilities.AppProperties import AppProperties
class AdminApplication(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
if method == 'GET':
app = self.get_application()
self.values['m'] = self.get_param('m')
if not app:
app = model.Application()
self.values['app'] = app
self.values['appName'] = self.not_none(app.name)
self.values['appSubject'] = self.not_none(app.subject)
self.values['locale'] = self.not_none(app.locale)
self.values['url'] = self.not_none(app.url)
self.render('templates/module/admin/admin-application.html')
elif self.auth():
app = self.get_application()
if not app:
app = model.Application()
app.users = model.UserData.all().count()
app.communities = model.Community.all().count()
app.threads = model.Thread.all().filter('parent_thread', None).count()
app.articles = model.Article.all().filter('draft =', False).filter('deletion_date', None).count()
app.name = self.get_param('appName')
app.subject = self.get_param("appSubject")
app.locale = self.get_param("locale")
app.url = self.get_param('url')
app.put()
memcache.delete('app')
AppProperties().updateJinjaEnv()
self.redirect('/module/admin.application?m='+self.getLocale('Updated')) | [
[
1,
0,
0.3382,
0.0147,
0,
0.66,
0,
200,
0,
1,
0,
0,
200,
0,
0
],
[
1,
0,
0.3676,
0.0147,
0,
0.66,
0.2,
279,
0,
1,
0,
0,
279,
0,
0
],
[
1,
0,
0.3824,
0.0147,
0,
0.6... | [
"import img",
"from google.appengine.api import images",
"from google.appengine.api import memcache",
"from handlers.AuthenticatedHandler import *",
"from utilities.AppProperties import AppProperties",
"class AdminApplication(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tmethod = self.request.method... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
# (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com>
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import img
from google.appengine.api import images
from google.appengine.api import memcache
from handlers.module.admin.AdminApplication import *
from handlers.AuthenticatedHandler import *
from utilities.AppProperties import AppProperties
class AdminLookAndFeel(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
if method == 'GET':
app = self.get_application()
self.values['m'] = self.get_param('m')
if not app:
app = model.Application()
self.values['app'] = app
self.values['theme'] = self.not_none(app.theme)
self.values['max_results'] = self.not_none(app.max_results)
self.values['max_results_sublist'] = self.not_none(app.max_results_sublist)
self.render('templates/module/admin/admin-lookandfeel.html')
elif self.auth():
app = self.get_application()
if not app:
app = model.Application()
logo = self.request.get("logo")
if logo:
app.logo = images.im_feeling_lucky(logo, images.JPEG)
memcache.delete('/images/application/logo')
app.theme = self.get_param("theme")
if self.get_param('max_results'):
app.max_results = int(self.get_param('max_results'))
if self.get_param('max_results_sublist'):
app.max_results_sublist = int(self.get_param('max_results_sublist'))
app.put()
memcache.delete('app')
AppProperties().updateJinjaEnv()
self.redirect('/module/admin.lookandfeel?m='+self.getLocale('Updated')) | [
[
1,
0,
0.3239,
0.0141,
0,
0.66,
0,
200,
0,
1,
0,
0,
200,
0,
0
],
[
1,
0,
0.3521,
0.0141,
0,
0.66,
0.1667,
279,
0,
1,
0,
0,
279,
0,
0
],
[
1,
0,
0.3662,
0.0141,
0,
... | [
"import img",
"from google.appengine.api import images",
"from google.appengine.api import memcache",
"from handlers.module.admin.AdminApplication import *",
"from handlers.AuthenticatedHandler import *",
"from utilities.AppProperties import AppProperties",
"class AdminLookAndFeel(AuthenticatedHandler):... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class AdminCategoryEdit(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
key = self.get_param('key')
self.values['parent_categories'] = list(model.Category.all().filter('parent_category', None).order('title'))
self.values['parent_category'] = None
if method == 'GET':
if key:
# show edit form
category = model.Category.get(key)
self.values['key'] = key
self.values['title'] = category.title
self.values['description'] = category.description
self.values['parent_category'] = str(category.parent_category.key())
self.render('templates/module/admin/admin-category-edit.html')
else:
# show an empty form
self.values['key'] = None
self.values['title'] = "New category"
self.values['description'] = "Description"
self.render('templates/module/admin/admin-category-edit.html')
elif self.auth():
title = self.get_param('title')
desc = self.get_param('description')
if title is None or len(title.strip()) == 0 or desc is None or len(desc.strip()) == 0:
self.values['m'] = "Title and description are mandatory fields"
self.values['key'] = key
self.values['title'] = title
self.values['description'] = desc
self.values['parent_category'] = self.request.get('parent_category')
self.render('templates/module/admin/admin-category-edit.html')
return
if key:
# update category
category = model.Category.get(key)
category.title = self.get_param('title')
category.description = self.get_param('description')
category.url_path = self.to_url_path(category.title)
parent_key = self.request.get('parent_category')
if parent_key:
category.parent_category = model.Category.get(parent_key)
category.put()
self.redirect('/module/admin.categories')
else:
category = model.Category(title=self.get_param('title'),
description=self.get_param('description'),
articles = 0,
communities = 0)
category.url_path = self.to_url_path(category.title)
parent_key = self.request.get('parent_category')
if parent_key:
category.parent_category = model.Category.get(parent_key)
category.put()
self.redirect('/module/admin.categories') | [
[
1,
0,
0.2584,
0.0112,
0,
0.66,
0,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.6404,
0.7303,
0,
0.66,
1,
384,
0,
1,
0,
0,
116,
0,
36
],
[
2,
1,
0.6517,
0.7079,
1,
0.26... | [
"from handlers.AuthenticatedHandler import *",
"class AdminCategoryEdit(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tmethod = self.request.method\n\t\tuser = self.values['user']\n\t\tself.values['tab'] = '/admin'\n\n\t\tif user.rol != 'admin':",
"\tdef execute(self):\n\t\tmethod = self.request.method\n\t... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
# (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com>
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import img
from google.appengine.api import images
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
from utilities.AppProperties import AppProperties
class AdminModules(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
if method == 'GET':
app = self.get_application()
self.values['m'] = self.get_param('m')
if not app:
app = model.Application()
self.values['app'] = app
self.values['appName'] = self.not_none(app.name)
self.values['appSubject'] = self.not_none(app.subject)
self.values['locale'] = self.not_none(app.locale)
self.values['theme'] = self.not_none(app.theme)
self.values['url'] = self.not_none(app.url)
self.values['mail_contact'] = self.not_none(app.mail_contact)
self.values['mail_subject_prefix'] = self.not_none(app.mail_subject_prefix)
self.values['mail_sender'] = self.not_none(app.mail_sender)
self.values['mail_footer'] = self.not_none(app.mail_footer)
self.values['recaptcha_public_key'] = self.not_none(app.recaptcha_public_key)
self.values['recaptcha_private_key']= self.not_none(app.recaptcha_private_key)
self.values['google_adsense'] = self.not_none(app.google_adsense)
self.values['google_adsense_channel']= self.not_none(app.google_adsense_channel)
self.values['google_analytics'] = self.not_none(app.google_analytics)
self.values['max_results'] = self.not_none(app.max_results)
self.values['max_results_sublist'] = self.not_none(app.max_results_sublist)
self.render('templates/module/admin/admin-modules.html')
elif self.auth():
app = self.get_application()
if not app:
app = model.Application()
app.users = model.UserData.all().count()
app.communities = model.Community.all().count()
app.threads = model.Thread.all().filter('parent_thread', None).count()
app.articles = model.Article.all().filter('draft =', False).filter('deletion_date', None).count()
app.name = self.get_param('appName')
app.subject = self.get_param("appSubject")
app.locale = self.get_param("locale")
logo = self.request.get("logo")
if logo:
app.logo = images.im_feeling_lucky(logo, images.JPEG)
memcache.delete('/images/application/logo')
app.theme = self.get_param("theme")
app.url = self.get_param('url')
app.mail_subject_prefix = self.get_param('mail_subject_prefix')
app.mail_contact = self.get_param('mail_contact')
app.mail_sender = self.get_param('mail_sender')
app.mail_footer = self.get_param('mail_footer')
app.recaptcha_public_key = self.get_param('recaptcha_public_key')
app.recaptcha_private_key = self.get_param('recaptcha_private_key')
app.google_adsense = self.get_param('google_adsense')
app.google_adsense_channel = self.get_param('google_adsense_channel')
app.google_analytics = self.get_param('google_analytics')
if self.get_param('max_results'):
app.max_results = int(self.get_param('max_results'))
if self.get_param('max_results_sublist'):
app.max_results_sublist = int(self.get_param('max_results_sublist'))
app.put()
memcache.delete('app')
AppProperties().updateJinjaEnv()
self.redirect('/module/admin.application?m='+self.getLocale('Updated')) | [
[
1,
0,
0.23,
0.01,
0,
0.66,
0,
200,
0,
1,
0,
0,
200,
0,
0
],
[
1,
0,
0.25,
0.01,
0,
0.66,
0.2,
279,
0,
1,
0,
0,
279,
0,
0
],
[
1,
0,
0.26,
0.01,
0,
0.66,
0.4,
... | [
"import img",
"from google.appengine.api import images",
"from google.appengine.api import memcache",
"from handlers.AuthenticatedHandler import *",
"from utilities.AppProperties import AppProperties",
"class AdminModules(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tmethod = self.request.method\n\t... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class CommunityAddRelated(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
if method == 'GET':
self.values['m'] = self.get_param('m')
self.render('templates/module/community/community-add-related.html')
elif self.auth():
fromId = self.request.get('community_from')
toId = self.request.get('community_to')
if fromId is None or len(fromId.strip()) == 0 or not fromId.isdigit():
self.values['m'] = "Enter a valid source community"
self.render('templates/module/community/community-add-related.html')
return
if toId is None or len(toId.strip()) == 0:
self.values['m'] = "Enter a valid target community"
self.render('templates/module/community/community-add-related.html')
return
community_from = model.Community.get_by_id(int(fromId))
community_to = model.Community.get_by_id(int(toId))
related = model.RelatedCommunity.all().filter('community_from', community_from).filter('community_to', community_to).get()
if related:
self.redirect('/module/community.add.related?m=Already_exists')
return
if community_from is None:
self.values['m'] = "Source community not found"
self.render('templates/module/community/community-add-related.html')
return
if community_to is None:
self.values['m'] = "Target community not found"
self.render('templates/module/community/community-add-related.html')
return
self.create_related(community_from, community_to)
self.create_related(community_to, community_from)
self.redirect('/module/community.add.related?m=Updated')
def create_related(self, community_from, community_to):
related = model.RelatedCommunity(community_from = community_from,
community_to = community_to,
community_from_title = community_from.title,
community_from_url_path = community_from.url_path,
community_to_title = community_to.title,
community_to_url_path = community_to.url_path)
related.put() | [
[
1,
0,
0.284,
0.0123,
0,
0.66,
0,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.6543,
0.7037,
0,
0.66,
1,
614,
0,
2,
0,
0,
116,
0,
29
],
[
2,
1,
0.6111,
0.5679,
1,
0.39,... | [
"from handlers.AuthenticatedHandler import *",
"class CommunityAddRelated(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tmethod = self.request.method\n\t\tuser = self.values['user']\n\t\tself.values['tab'] = '/admin'\n\n\t\tif user.rol != 'admin':",
"\tdef execute(self):\n\t\tmethod = self.request.method\n... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
# (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com>
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import img
from google.appengine.api import images
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
from utilities.AppProperties import AppProperties
class AdminMail(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
if method == 'GET':
app = self.get_application()
self.values['m'] = self.get_param('m')
if not app:
app = model.Application()
self.values['app'] = app
self.values['mail_contact'] = self.not_none(app.mail_contact)
self.values['mail_subject_prefix'] = self.not_none(app.mail_subject_prefix)
self.values['mail_sender'] = self.not_none(app.mail_sender)
self.values['mail_footer'] = self.not_none(app.mail_footer)
self.render('templates/module/admin/admin-mail.html')
elif self.auth():
app = self.get_application()
if not app:
app = model.Application()
app.mail_subject_prefix = self.get_param('mail_subject_prefix')
app.mail_contact = self.get_param('mail_contact')
app.mail_sender = self.get_param('mail_sender')
app.mail_footer = self.get_param('mail_footer')
app.put()
memcache.delete('app')
AppProperties().updateJinjaEnv()
self.redirect('/module/admin.mail?m='+self.getLocale('Updated')) | [
[
1,
0,
0.3594,
0.0156,
0,
0.66,
0,
200,
0,
1,
0,
0,
200,
0,
0
],
[
1,
0,
0.3906,
0.0156,
0,
0.66,
0.2,
279,
0,
1,
0,
0,
279,
0,
0
],
[
1,
0,
0.4062,
0.0156,
0,
0.6... | [
"import img",
"from google.appengine.api import images",
"from google.appengine.api import memcache",
"from handlers.AuthenticatedHandler import *",
"from utilities.AppProperties import AppProperties",
"class AdminMail(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tmethod = self.request.method\n\t\tu... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
# (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com>
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import img
from google.appengine.api import images
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
from utilities.AppProperties import AppProperties
class AdminGoogle(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
if method == 'GET':
app = self.get_application()
self.values['m'] = self.get_param('m')
if not app:
app = model.Application()
self.values['app'] = app
self.values['recaptcha_public_key'] = self.not_none(app.recaptcha_public_key)
self.values['recaptcha_private_key']= self.not_none(app.recaptcha_private_key)
self.values['google_adsense'] = self.not_none(app.google_adsense)
self.values['google_adsense_channel']= self.not_none(app.google_adsense_channel)
self.values['google_analytics'] = self.not_none(app.google_analytics)
self.render('templates/module/admin/admin-google.html')
elif self.auth():
app = self.get_application()
if not app:
app = model.Application()
app.recaptcha_public_key = self.get_param('recaptcha_public_key')
app.recaptcha_private_key = self.get_param('recaptcha_private_key')
app.google_adsense = self.get_param('google_adsense')
app.google_adsense_channel = self.get_param('google_adsense_channel')
app.google_analytics = self.get_param('google_analytics')
app.put()
memcache.delete('app')
AppProperties().updateJinjaEnv()
self.redirect('/module/admin.google?m='+self.getLocale('Updated')) | [
[
1,
0,
0.3382,
0.0147,
0,
0.66,
0,
200,
0,
1,
0,
0,
200,
0,
0
],
[
1,
0,
0.3676,
0.0147,
0,
0.66,
0.2,
279,
0,
1,
0,
0,
279,
0,
0
],
[
1,
0,
0.3824,
0.0147,
0,
0.6... | [
"import img",
"from google.appengine.api import images",
"from google.appengine.api import memcache",
"from handlers.AuthenticatedHandler import *",
"from utilities.AppProperties import AppProperties",
"class AdminGoogle(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tmethod = self.request.method\n\t\... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import img
from google.appengine.api import images
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
from utilities.AppProperties import AppProperties
class AdminCache(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
if method == 'POST':
memcache.flush_all()
self.values['m'] = "Cache is clean"
self.getRelevantCacheData()
self.render('templates/module/admin/admin-cache.html')
def getRelevantCacheData(self):
cacheData = memcache.get_stats()
self.values['cdItems'] = cacheData['items']
self.values['cdBytes'] = cacheData['bytes']
self.values['cdOldest'] = cacheData['oldest_item_age'] | [
[
1,
0,
0.4314,
0.0196,
0,
0.66,
0,
200,
0,
1,
0,
0,
200,
0,
0
],
[
1,
0,
0.4706,
0.0196,
0,
0.66,
0.2,
279,
0,
1,
0,
0,
279,
0,
0
],
[
1,
0,
0.4902,
0.0196,
0,
0.6... | [
"import img",
"from google.appengine.api import images",
"from google.appengine.api import memcache",
"from handlers.AuthenticatedHandler import *",
"from utilities.AppProperties import AppProperties",
"class AdminCache(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tmethod = self.request.method\n\t\t... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class Admin(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
self.redirect('/module/admin.application')
| [
[
1,
0,
0.6389,
0.0278,
0,
0.66,
0,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.8333,
0.3056,
0,
0.66,
1,
969,
0,
1,
0,
0,
116,
0,
2
],
[
2,
1,
0.8611,
0.25,
1,
0.61,
... | [
"from handlers.AuthenticatedHandler import *",
"class Admin(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tmethod = self.request.method\n\t\tuser = self.values['user']\n\t\tself.values['tab'] = '/admin'\n\n\t\tif user.rol != 'admin':",
"\tdef execute(self):\n\t\tmethod = self.request.method\n\t\tuser = sel... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class AdminCategories(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
self.add_categories()
self.render('templates/module/admin/admin-categories.html') | [
[
1,
0,
0.6216,
0.027,
0,
0.66,
0,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.8378,
0.3514,
0,
0.66,
1,
986,
0,
1,
0,
0,
116,
0,
3
],
[
2,
1,
0.8649,
0.2973,
1,
0.16,
... | [
"from handlers.AuthenticatedHandler import *",
"class AdminCategories(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tmethod = self.request.method\n\t\tuser = self.values['user']\n\t\tself.values['tab'] = '/admin'\n\n\t\tif user.rol != 'admin':",
"\tdef execute(self):\n\t\tmethod = self.request.method\n\t\t... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class AdminStats(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
self.values['tab'] = '/admin'
if user.rol != 'admin':
self.forbidden()
return
self.render('templates/module/admin/admin-stats.html')
| [
[
1,
0,
0.6389,
0.0278,
0,
0.66,
0,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.8333,
0.3056,
0,
0.66,
1,
24,
0,
1,
0,
0,
116,
0,
2
],
[
2,
1,
0.8611,
0.25,
1,
0.17,
... | [
"from handlers.AuthenticatedHandler import *",
"class AdminStats(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tmethod = self.request.method\n\t\tuser = self.values['user']\n\t\tself.values['tab'] = '/admin'\n\n\t\tif user.rol != 'admin':",
"\tdef execute(self):\n\t\tmethod = self.request.method\n\t\tuser ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import time
import datetime
from google.appengine.ext import db
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
class ArticleEdit(AuthenticatedHandler):
def execute(self):
self.values['tab'] = '/module/article.list'
method = self.request.method
user = self.values['user']
key = self.get_param('key')
x = self.get_param('x')
draft = False
if self.get_param('save_draft'):
draft = True
licenses = [ { 'id': 'copyright', 'lic': '© Todos los derechos reservados' },
{ 'id': 'pd', 'lic': u'Dominio público' },
{ 'id': 'by', 'lic': 'Creative Commons: Reconocimiento' },
{ 'id': 'by-nc', 'lic': 'Creative Commons: Reconocimiento-No comercial' },
{ 'id': 'by-nc-nd', 'lic': 'Creative Commons: Reconocimiento-No comercial-Sin obras derivadas' },
{ 'id': 'by-nc-sa', 'lic': 'Creative Commons: Reconocimiento-No comercial-Compartir bajo la misma licencia' },
{ 'id': 'by-nd', 'lic': 'Creative Commons: Reconocimiento-Sin obras derivadas' },
{ 'id': 'by-sa', 'lic': 'Creative Commons: Reconocimiento-Compartir bajo la misma licencia' }
]
self.values['licenses'] = licenses
if method == 'GET':
if key:
# show edit form
article = model.Article.get(key)
if not article:
self.not_found()
return
if not user.nickname == article.author.nickname and user.rol != 'admin':
self.forbidden()
return
self.values['key'] = key
self.values['title'] = article.title
self.values['lic'] = article.lic
self.values['tags'] = ', '.join(article.tags)
self.values['description'] = article.description
self.values['content'] = article.content
self.values['draft'] = article.draft
self.render('templates/module/article/article-edit.html')
else:
# show an empty form
self.values['title'] = u'Título...'
self.values['lic'] = 'copyright'
self.values['draft'] = True
self.render('templates/module/article/article-edit.html')
elif self.auth():
if x and draft:
# check mandatory fields
if not self.get_param('title') or not self.get_param('tags') or not self.get_param('description') or not self.get_param('content'):
self.render_json({ 'saved': False })
return
if key:
# update article
article = model.Article.get(key)
memcache.delete(str(article.key().id()) + '_html')
if not article:
self.not_found()
return
if not user.nickname == article.author.nickname and user.rol != 'admin':
self.forbidden()
return
lic = self.get_param('lic')
lics = [license['id'] for license in licenses]
if not lic in lics:
lic = 'copyright'
if not article.draft:
self.delete_tags(article.tags)
article.lic = lic
article.tags = self.parse_tags(self.get_param('tags'))
article.description = ' '.join(self.get_param('description').splitlines())
article.content = self.get_param('content')
if article.draft:
# title and url_path can change only if the article hasn't already been published
article.title = self.get_param('title')
article.url_path = '%d/%s' % (article.key().id(), self.to_url_path(article.title))
add_communities = False
if article.draft and not draft:
article.draft = draft
user.articles += 1
user.draft_articles -=1
user.put()
article.creation_date = datetime.datetime.now()
self.add_follower(article=article, nickname=user.nickname)
followers = list(self.get_followers(user=user))
followers.append(user.nickname)
self.create_event(event_type='article.new', followers=followers, user=user, article=article)
app = model.Application.all().get()
if app:
app.articles += 1
app.put()
memcache.delete('app')
add_communities = True
if not article.draft:
self.create_recommendations(article)
if not article.author_nickname:
article.author_nickname = user.nickname
if not article.content_html:
html = model.ArticleHtml(content=article.content)
html.put()
article.content_html = html
else:
html_content = article.content
html_content = self.media_content(html_content)
article.content_html.content = html_content
article.content_html.put()
article.put()
#memcache.delete('index_articles')
#memcache.delete('tag_cloud')
#memcache.delete(str(article.key().id()))
self.delete_articles_cache(str(article.key().id()))
if not draft:
self.update_tags(article.tags)
if x:
self.render_json({ 'saved': True, 'key' : str(article.key()), 'updated' : True, "draft_articles" : str(user.draft_articles) })
else:
if add_communities:
self.redirect('/module/article.add.communities?key=%s' % str(article.key()))
else:
self.redirect('/module/article/%s' % article.url_path)
else:
# new article
today = datetime.date.today()
title = self.get_param('title')
tags = self.parse_tags(self.get_param('tags'))
lic = self.get_param('lic')
lics = [license['id'] for license in licenses]
if not lic in lics:
lic = 'copyright'
article = model.Article(author=user,
author_nickname=user.nickname,
title=title,
description=' '.join(self.get_param('description').splitlines()),
content=self.get_param('content'),
lic=lic,
url_path='empty',
tags=tags,
draft=draft,
article_type='article',
views=0,
responses=0,
rating_count=0,
rating_total=0,
favourites=0)
html_content = article.content
html = model.ArticleHtml(content=self.media_content(html_content))
html.put()
article.content_html = html
article.subscribers = [user.email]
article.put()
self.add_user_subscription(user, 'article', article.key().id())
article.url_path = '%d/%s' % (article.key().id(), self.to_url_path(article.title))
article.put()
#memcache.delete('index_articles')
#memcache.delete('tag_cloud')
#memcache.delete(str(article.key().id()))
self.delete_articles_cache(str(article.key().id()))
if not draft:
self.create_recommendations(article)
user.articles += 1
user.put()
self.update_tags(tags)
self.add_follower(article=article, nickname=user.nickname)
followers = list(self.get_followers(user=user))
followers.append(user.nickname)
self.create_event(event_type='article.new', followers=followers, user=user, article=article)
app = model.Application.all().get()
if app:
app.articles += 1
app.put()
memcache.delete('app')
else:
user.draft_articles += 1
user.put()
if x:
self.render_json({ 'saved': True, 'key' : str(article.key()), "updated" : False, "draft_articles" : str(user.draft_articles) })
else:
if article.draft:
self.redirect('/module/article/%s' % article.url_path)
else:
self.redirect('/module/article.add.communities?key=%s' % str(article.key()))
def create_recommendations(self, article):
self.create_task('article_recommendation', 1, {'article': article.key().id(), 'offset': 0})
def delete_articles_cache(self, article_id):
"""
Deletes cache for 5 first pages of articles list, initial article list in the init page,
tag_cloud and current article
"""
str = '/module/article.list'
keys = [str]
keys = ['%s?' % str]
x = 1
while x < 6 :
keys.append('%s?p=%s&' % (str, x))
x = x+1
keys.append('index_articles')
keys.append('tag_cloud')
keys.append(article_id)
memcache.delete_multi(keys)
| [
[
1,
0,
0.0924,
0.004,
0,
0.66,
0,
654,
0,
1,
0,
0,
654,
0,
0
],
[
1,
0,
0.0964,
0.004,
0,
0.66,
0.2,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.1044,
0.004,
0,
0.66,
... | [
"import time",
"import datetime",
"from google.appengine.ext import db",
"from google.appengine.api import memcache",
"from handlers.AuthenticatedHandler import *",
"class ArticleEdit(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tself.values['tab'] = '/module/article.list'\n\t\tmethod = self.request... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseRest import *
class ArticleVisit(BaseRest):
def get(self):
article_id = self.request.get('id')
memcache.delete(article_id + '_article')
article = model.Article.get_by_id(int(article_id))
article.views += 1
article.put()
memcache.add(str(article.key().id()) + '_article', article, 0)
content = []
self.render_json("{\"views\" : "+str(article.views)+"}")
return | [
[
1,
0,
0.6216,
0.027,
0,
0.66,
0,
250,
0,
1,
0,
0,
250,
0,
0
],
[
3,
0,
0.8378,
0.3514,
0,
0.66,
1,
195,
0,
1,
0,
0,
138,
0,
11
],
[
2,
1,
0.8649,
0.2973,
1,
0.29,... | [
"from handlers.BaseRest import *",
"class ArticleVisit(BaseRest):\n\n\tdef get(self):\n\t\tarticle_id = self.request.get('id')\n\n\t\tmemcache.delete(article_id + '_article')\n\t\tarticle = model.Article.get_by_id(int(article_id))\n\t\tarticle.views += 1",
"\tdef get(self):\n\t\tarticle_id = self.request.get('i... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class ArticleVote(AuthenticatedHandler):
def execute(self):
article = model.Article.get(self.get_param('key'))
if not article or article.draft or article.deletion_date:
self.not_found()
return
if not self.auth():
return
memcache.delete(str(article.key().id()) + '_article')
rating = int(self.get_param('rating'))
if rating < 0:
rating = 0
elif rating > 5:
rating = 5
user = self.values['user']
avg = article.rating_average
if article and article.author.nickname != user.nickname:
vote = model.Vote.gql('WHERE user=:1 and article=:2', user, article).get()
if not vote:
vote = model.Vote(user=user,rating=rating,article=article)
vote.put()
article.rating_count += 1
article.rating_total += rating
article.rating_average = int(article.rating_total / article.rating_count)
article.put()
author = article.author
author.rating_count += 1
author.rating_total += rating
author.rating_average = int(author.rating_total / author.rating_count)
author.put()
avg = article.rating_average
memcache.add(str(article.key().id()) + '_article', article, 0)
if self.get_param('x'):
self.render_json({ 'average': avg, 'votes': article.rating_count })
else:
self.redirect('/module/article/%s' % article.url_path)
| [
[
1,
0,
0.3382,
0.0147,
0,
0.66,
0,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.3529,
0.0147,
0,
0.66,
0.5,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.6912,
0.6324,
0,
0.6... | [
"from google.appengine.ext import db",
"from handlers.AuthenticatedHandler import *",
"class ArticleVote(AuthenticatedHandler):\n\t\n\tdef execute(self):\n\t\tarticle = model.Article.get(self.get_param('key'))\n\t\tif not article or article.draft or article.deletion_date:\n\t\t\tself.not_found()\n\t\t\treturn",... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class ArticleCommentEdit(AuthenticatedHandler):
def execute(self):
self.values['tab'] = '/module/article.list'
method = self.request.method
user = self.values['user']
comment_key = self.get_param('key')
if method == 'GET':
if comment_key:
# show edit form
comment = model.Comment.get(comment_key)
if user.nickname != comment.author_nickname and user.rol != 'admin':
self.forbidden()
return
if comment is None:
self.not_found()
return
self.values['article'] = comment.article
self.values['comment'] = comment
self.values['comment_key'] = comment.key
self.render('templates/module/article/article-comment-edit.html')
return
else:
self.show_error("Comment not found")
return
elif self.auth():
if comment_key:
# update comment
comment = model.Comment.get(comment_key)
if user.nickname != comment.author_nickname and user.rol != 'admin':
self.forbidden()
return
if not comment:
self.not_found()
return
content = self.get_param('content')
if not content:
self.values['article'] = comment.article
self.values['comment'] = comment
self.values['comment_key'] = comment.key
self.values['m'] = "Content is mandatory"
self.render('templates/module/article/article-comment-edit.html')
return
comment.content = content
if user.rol != 'admin':
if comment.editions is None:
comment.editions = 0
comment.editions +=1
comment.last_edition = datetime.datetime.now()
comment.put()
results = 10
app = self.get_application()
if app.max_results_sublist:
results = app.max_results_sublist
page = comment.response_number / results
if (comment.response_number % results) > 0:
page += 1
self.redirect('/module/article/%s?p=%d#comment-%s' % (comment.article.url_path, page, comment.response_number))
else:
self.show_error("Comment not found")
return | [
[
1,
0,
0.2614,
0.0114,
0,
0.66,
0,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.2727,
0.0114,
0,
0.66,
0.5,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.6477,
0.7159,
0,
0.6... | [
"from google.appengine.ext import db",
"from handlers.AuthenticatedHandler import *",
"class ArticleCommentEdit(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tself.values['tab'] = '/module/article.list'\n\t\tmethod = self.request.method\n\t\tuser = self.values['user']\n\t\tcomment_key = self.get_param('key... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import time
import datetime
from google.appengine.ext import db
from google.appengine.api import mail
from handlers.AuthenticatedHandler import *
class ArticleComment(AuthenticatedHandler):
def execute(self):
user = self.values['user']
key = self.get_param('key')
article = model.Article.get(key)
memcache.delete(str(article.key().id()) + '_article')
if not article or article.draft or article.deletion_date:
self.not_found()
return
if not self.auth():
return
content = self.get_param('content')
if not content:
self.show_error("Content is mandatory")
return
preview = self.get_param('preview')
if preview:
comment = model.Comment(article=article,
author=user,
author_nickname=user.nickname,
content=content)
self.values['comment'] = comment
self.values['preview'] = True
self.render('templates/module/article/article-comment-edit.html')
return
if self.check_duplicate(article, user, content):
self.show_error("Duplicated comment")
return
# migration
if not article.subscribers:
com = [c.author.email for c in model.Comment.all().filter('article', article).fetch(1000) ]
com.append(article.author.email)
article.subscribers = list(set(com))
# end migration
comment = model.Comment(article=article,
author=user,
author_nickname=user.nickname,
content=content,
editions = 0,
response_number=article.responses+1)
comment.put()
results = 10
app = self.get_application()
if app.max_results_sublist:
results = app.max_results_sublist
page = comment.response_number / results
if (comment.response_number % results) > 0:
page += 1
comment_url = '/module/article/%s?p=%d#comment-%d' % (article.url_path, page, comment.response_number)
user.comments += 1
user.put()
article.responses += 1
article.put()
followers = list(self.get_followers(user=user))
followers.append(user.nickname)
followers.extend(self.get_followers(article=article))
followers = list(set(followers))
self.create_event(event_type='article.comment',
followers=followers, user=user, article=article, response_number=comment.response_number)
memcache.add(str(article.key().id()) + '_article', article, 0)
subscribers = article.subscribers
if subscribers and user.email in subscribers:
subscribers.remove(user.email)
if subscribers:
subject = self.getLocale("New comment in: '%s'") % self.clean_ascii(article.title)
#Nuevo comentario en el artículo: '%s':\n%s%s\n\nTodos los comentarios en:\n%s/module/article/%s#comments\n\nEliminar suscripción a este artículo:\n%s/module/article.comment.subscribe?key=%s\n
body = self.getLocale("New comment in article: '%s':\n%s%s\n\nAll comments at:\n%s/module/article/%s#comments\n\nUnsuscribe this article:\n%s/module/article.comment.subscribe?key=%s\n") % (self.clean_ascii(article.title), app.url, comment_url, app.url, article.url_path, app.url, str(article.key()))
self.mail(subject=subject, body=body, bcc=subscribers)
subscribe = self.get_param('subscribe')
if subscribe and not user.email in article.subscribers:
article.subscribers.append(user.email)
self.redirect(comment_url)
def check_duplicate(self, article, user, content):
last_comment = model.Comment.all().filter('article', article).filter('author', user).order('-creation_date').get()
if last_comment is not None:
if last_comment.content == content:
return True
return False
| [
[
1,
0,
0.1917,
0.0083,
0,
0.66,
0,
654,
0,
1,
0,
0,
654,
0,
0
],
[
1,
0,
0.2,
0.0083,
0,
0.66,
0.2,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.2167,
0.0083,
0,
0.66,
... | [
"import time",
"import datetime",
"from google.appengine.ext import db",
"from google.appengine.api import mail",
"from handlers.AuthenticatedHandler import *",
"class ArticleComment(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tuser = self.values['user']\n\t\tkey = self.get_param('key')\n\t\tarticl... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class ArticleFavourite(AuthenticatedHandler):
def execute(self):
article = model.Article.get(self.get_param('key'))
user = self.values['user']
if not article or article.draft or article.deletion_date:
self.not_found()
return
if not self.auth():
return
favourite = model.Favourite.gql('WHERE user=:1 AND article=:2', user, article).get()
if not favourite:
favourite = model.Favourite(article=article,
user=user,
article_author_nickname=article.author_nickname,
article_title=article.title,
article_url_path=article.url_path,
user_nickname=user.nickname)
favourite.put()
user.favourites += 1
user.put()
followers = list(self.get_followers(user=user))
followers.append(user.nickname)
followers.extend(self.get_followers(article=article))
followers = list(set(followers))
self.create_event(event_type='article.favourite', followers=followers, user=user, article=article)
if self.get_param('x'):
self.render_json({ 'action': 'added' })
else:
self.redirect('/module/article/%s' % article.url_path)
else:
favourite.delete()
user.favourites -= 1
user.put()
if self.get_param('x'):
self.render_json({ 'action': 'deleted' })
else:
self.redirect('/module/article/%s' % article.url_path)
| [
[
1,
0,
0.3286,
0.0143,
0,
0.66,
0,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.3429,
0.0143,
0,
0.66,
0.5,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.6857,
0.6429,
0,
0.6... | [
"from google.appengine.ext import db",
"from handlers.AuthenticatedHandler import *",
"class ArticleFavourite(AuthenticatedHandler):\n\t\n\tdef execute(self):\n\t\tarticle = model.Article.get(self.get_param('key'))\n\t\tuser = self.values['user']\n\t\tif not article or article.draft or article.deletion_date:\n\... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.BaseHandler import *
class ArticleView(BaseHandler):
def execute(self):
url_path = self.request.path.split('/', 3)[3]
article_id = self.request.path.split('/')[3]
article = self.cache(article_id + '_article', self.get_article)
if not article:
self.not_found()
return
if article.url_path != url_path:
self.redirect('/module/article/%s' % article.url_path, permanent=True)
return
if not article.author_nickname:
article.author_nickname = article.author.nickname
article.put()
user = self.values['user']
if article.deletion_date and (not user or (user.rol != 'admin' and article.author_nickname != user.nickname)):
self.values['article'] = article
self.error(404)
self.render('templates/module/article/article-deleted.html')
return
self.values['tab'] = '/module/article.list'
if article.draft and (not user or not user.nickname == article.author_nickname):
self.not_found()
return
if user and user.nickname != article.author_nickname:
vote = model.Vote.gql('WHERE user=:1 AND article=:2', user, article).get()
if not vote:
self.values['canvote'] = True
if user:
added = model.Favourite.gql('WHERE user=:1 AND article=:2',user,article).get()
if not added:
self.values['canadd'] = True
if user:
if user.email in article.subscribers:
self.values['cansubscribe'] = False
else:
self.values['cansubscribe'] = True
self.values['article'] = article
results = 10
app = self.get_application()
if app.max_results_sublist:
results = app.max_results_sublist
query = model.Comment.all().filter('article =', article)
comments = self.paging(query, results, 'creation_date', article.responses, 'creation_date')
# migration
i = 1
for c in comments:
if not c.author_nickname:
c.author_nickname = c.author.nickname
c.put()
if not c.response_number:
c.response_number = i
c.put()
i += 1
# end migration
self.values['comments'] = comments
self.values['a'] = 'comments'
self.values['keywords'] = ', '.join(article.tags)
communities = model.CommunityArticle.all().filter('article', article).order('community_title')
# communities = self.cache(str(article.key().id()) + '_communities', self.get_communities)
self.values['communities'] = list(communities)
if user and article.author_nickname == user.nickname:
all_communities = list(model.CommunityUser.all().filter('user', user).order('community_title'))
# TODO: this could be improved
for g in communities:
for gr in all_communities:
if gr.community_url_path == g.community_url_path:
all_communities.remove(gr)
if all_communities:
self.values['all_communities'] = all_communities
self.values['content_html'] = self.cache(str(article.key().id()) + '_html', self.to_html)
self.values['related'] = list(model.Recommendation.all().filter('article_from', article).order('-value').fetch(5))
self.render('templates/module/article/article-view.html')
def to_html(self):
article = self.values['article']
if not article.content_html:
html = model.ArticleHtml(content=self.markdown(article.content))
html = model.ArticleHtml(content=self.media_content(article.content))
html.put()
article.content_html = html
article.put()
return article.content_html.content
def get_communities(self):
article = self.values['article']
return model.CommunityArticle.all().filter('article', article).order('community_title')
def get_author(self):
article = self.values['article']
return model.UserData.all().filter('nickname', article.author_nickname).get()
def get_article(self):
article_id = self.request.path.split('/')[3]
return model.Article.get_by_id(int(article_id))
| [
[
1,
0,
0.1655,
0.0072,
0,
0.66,
0,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.1727,
0.0072,
0,
0.66,
0.5,
437,
0,
1,
0,
0,
437,
0,
0
],
[
3,
0,
0.5971,
0.8129,
0,
0.6... | [
"from google.appengine.ext import db",
"from handlers.BaseHandler import *",
"class ArticleView(BaseHandler):\n\n\tdef execute(self):\n\t\turl_path = self.request.path.split('/', 3)[3]\n\t\tarticle_id = self.request.path.split('/')[3]\n\t\tarticle = self.cache(article_id + '_article', self.get_article)\n\t\t\n\... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import datetime
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class ArticleCommentDelete(AuthenticatedHandler):
def execute(self):
user = self.values['user']
if user.rol != 'admin':
self.forbidden()
return
if not self.auth():
return
comment = model.Comment.get(self.get_param('key'))
if not comment:
self.not_found()
return
url = comment.article.url_path
message = self.get_param('message')
#decrement nomber of comments in the User
comment.author.comments -= 1
comment.author.put()
#delete comment
comment.deletion_date = datetime.datetime.now()
comment.deletion_message = message
comment.put()
self.redirect('/module/article/%s' % url)
| [
[
1,
0,
0.4259,
0.0185,
0,
0.66,
0,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.463,
0.0185,
0,
0.66,
0.3333,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.4815,
0.0185,
0,
0... | [
"import datetime",
"from google.appengine.ext import db",
"from handlers.AuthenticatedHandler import *",
"class ArticleCommentDelete(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tuser = self.values['user']\n\t\tif user.rol != 'admin':\n\t\t\tself.forbidden()\n\t\t\treturn",
"\tdef execute(self):\n\t\t... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
class ArticleList(BaseHandler):
def execute(self):
self.values['tab'] = '/module/article.list'
query = model.Article.all().filter('draft =', False).filter('deletion_date', None)
app = self.get_application()
key = '%s?%s' % (self.request.path, self.request.query)
results = 10
if app.max_results:
results = app.max_results
self.values['articles'] = self.paging(query, results, '-creation_date', app.articles, ['-creation_date', '-rating_average', '-responses'], key)
self.add_tag_cloud()
self.render('templates/module/article/article-list.html')
| [
[
1,
0,
0.6216,
0.027,
0,
0.66,
0,
437,
0,
1,
0,
0,
437,
0,
0
],
[
3,
0,
0.8378,
0.3514,
0,
0.66,
1,
338,
0,
1,
0,
0,
94,
0,
7
],
[
2,
1,
0.8649,
0.2973,
1,
0.55,
... | [
"from handlers.BaseHandler import *",
"class ArticleList(BaseHandler):\n\n\tdef execute(self):\n\t\tself.values['tab'] = '/module/article.list'\n\t\tquery = model.Article.all().filter('draft =', False).filter('deletion_date', None)\n\t\tapp = self.get_application()\n\t\tkey = '%s?%s' % (self.request.path, self.re... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class ArticleCommentSubscribe( AuthenticatedHandler ):
def execute(self):
key = self.get_param('key')
article = model.Article.get(key)
memcache.delete(str(article.key().id()) + '_article')
user = self.values['user']
mail = user.email
if not mail in article.subscribers:
if not self.auth():
return
article.subscribers.append(mail)
article.put()
self.add_user_subscription(user, 'article', article.key().id())
memcache.add(str(article.key().id()) + '_article', article, 0)
if self.get_param('x'):
self.render_json({ 'action': 'subscribed' })
else:
self.redirect('/module/article/%s' % (article.url_path, ))
else:
auth = self.get_param('auth')
if not auth:
memcache.add(str(article.key().id()) + '_article', article, 0)
self.values['article'] = article
self.render('templates/module/article/article-comment-subscribe.html')
else:
if not self.auth():
return
article.subscribers.remove(mail)
article.put()
self.remove_user_subscription(user, 'article', article.key().id())
memcache.add(str(article.key().id()) + '_article', article, 0)
if self.get_param('x'):
self.render_json({ 'action': 'unsubscribed' })
else:
self.redirect('/module/article/%s' % (article.url_path, ))
| [
[
1,
0,
0.3594,
0.0156,
0,
0.66,
0,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.375,
0.0156,
0,
0.66,
0.5,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.7031,
0.5781,
0,
0.66... | [
"from google.appengine.ext import db",
"from handlers.AuthenticatedHandler import *",
"class ArticleCommentSubscribe( AuthenticatedHandler ):\n\n\tdef execute(self):\n\t\tkey = self.get_param('key')\n\t\tarticle = model.Article.get(key)\n\t\tmemcache.delete(str(article.key().id()) + '_article')\n\t\tuser = sel... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import datetime
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class ArticleDelete(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
article = model.Article.get(self.get_param('key'))
memcache.delete(str(article.key().id()))
if not article:
self.not_found()
return
if user.rol != 'admin' and user.nickname != article.author.nickname:
self.forbidden()
return
if method == 'GET':
self.values['article'] = article
self.render('templates/module/article/article-delete.html')
elif self.auth():
# mark as deleted
article.deletion_message = self.get_param('message')
article.deletion_date = datetime.datetime.now()
article.deletion_user = user
article.put()
# decrement tag counters
self.delete_tags(article.tags)
# decrement author counters
if article.draft:
article.author.draft_articles -= 1
else:
article.author.articles -=1
article.author.rating_total -= article.rating_total
article.author.rating_count -= article.rating_count
if article.author.rating_count > 0:
article.author.rating_average = int(article.author.rating_total / article.author.rating_count)
else:
article.author.rating_average = 0
article.author.put()
# decrement community counters and delete relationships
gi = model.CommunityArticle.all().filter('article =', article)
for g in gi:
g.community.articles -= 1
if g.community.activity:
g.community.activity -= 15
g.community
g.community.put()
g.delete()
# decrement favourites and delete relationships
fv = model.Favourite.all().filter('article =', article)
for f in fv:
f.user.favourites -= 1
f.user.put()
f.delete()
rc = model.Recommendation.all().filter('article_from', article)
for r in rc:
r.delete()
rc = model.Recommendation.all().filter('article_to', article)
for r in rc:
r.delete()
# decrement votes and delete relationships
# vt = model.Vote.all().filter('article =', article)
# for v in vt:
# v.delete()
# comments?
memcache.delete('index_articles')
memcache.delete('tag_cloud')
app = model.Application.all().get()
if app:
app.articles -= 1
app.put()
memcache.delete('app')
self.redirect('/module/article/%s' % article.url_path)
| [
[
1,
0,
0.2091,
0.0091,
0,
0.66,
0,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.2273,
0.0091,
0,
0.66,
0.3333,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.2364,
0.0091,
0,
... | [
"import datetime",
"from google.appengine.ext import db",
"from handlers.AuthenticatedHandler import *",
"class ArticleDelete(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tmethod = self.request.method\n\t\tuser = self.values['user']\n\t\tarticle = model.Article.get(self.get_param('key'))\n\t\tmemcache.d... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class ArticleAddCommunities(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
key = self.get_param('key')
article = model.Article.get(key)
if not article or article.draft or article.deletion_date:
self.not_found()
return
if not user.nickname == article.author.nickname:
self.forbidden()
return
if method == 'GET':
self.values['key'] = key
self.values['article'] = article
communities = list(model.CommunityUser.all().filter('user', user).order('community_title'))
self.values['communities'] = communities
if not communities:
self.redirect('/module/article/%s' % article.url_path)
return
self.render('templates/module/article/article-add-communities.html')
elif self.auth():
arguments = self.request.arguments()
for gu in model.CommunityUser.all().filter('user', user).order('community_title'):
community = gu.community
if self.request.get('community-%d' % community.key().id()):
gi = model.CommunityArticle.all().filter('community', community).filter('article', article).count(1)
if not gi:
community.articles += 1
if community.activity:
community.activity += 15
community.put()
gi = model.CommunityArticle(community=community,
article=article,
article_author_nickname = article.author_nickname,
article_title = article.title,
article_url_path = article.url_path,
community_title = community.title,
community_url_path = community.url_path)
gi.put()
followers = list(self.get_followers(community=community))
self.create_event(event_type='community.addarticle', followers=followers, user=user, community=community, article=article)
self.redirect('/module/article/%s' % article.url_path) | [
[
1,
0,
0.3239,
0.0141,
0,
0.66,
0,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.6761,
0.662,
0,
0.66,
1,
753,
0,
1,
0,
0,
116,
0,
29
],
[
2,
1,
0.6901,
0.6338,
1,
0.88,... | [
"from handlers.AuthenticatedHandler import *",
"class ArticleAddCommunities(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tmethod = self.request.method\n\t\tuser = self.values['user']\n\t\tkey = self.get_param('key')\n\t\tarticle = model.Article.get(key)\n\t\tif not article or article.draft or article.deleti... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import logging
from google.appengine.api import mail
from handlers.AuthenticatedHandler import *
from google.appengine.runtime import apiproxy_errors
class CommunityNewArticle(AuthenticatedHandler):
def execute(self):
article = model.Article.get(self.get_param('article'))
community = model.Community.get(self.get_param('community'))
if not community or not article or article.draft or article.deletion_date:
self.not_found()
return
if not self.auth():
return
user = self.values['user']
gu = self.joined(community)
if gu and not article.draft:
gi = model.CommunityArticle.gql('WHERE community=:1 and article=:2', community, article).get()
if not gi and user.nickname == article.author.nickname:
gi = model.CommunityArticle(article=article,
community=community,
article_author_nickname=article.author_nickname,
article_title=article.title,
article_url_path=article.url_path,
community_title=community.title,
community_url_path=community.url_path)
gi.put()
community.articles += 1
if community.activity:
community.activity += 15
community.put()
followers = list(self.get_followers(community=community))
self.create_event(event_type='community.addarticle', followers=followers, user=user, community=community, article=article)
subscribers = community.subscribers
if subscribers and user.email in subscribers:
subscribers.remove(user.email)
if subscribers:
app = self.get_application()
subject = self.getLocale("New article: '%s'") % self.clean_ascii(article.title) # u"Nuevo articulo: '%s'"
body = self.getLocale("New article at community %s.\nArticle title: %s\nRead more at:\n%s/module/article/%s\n") % (self.clean_ascii(community.title), self.clean_ascii(article.title), app.url, article.url_path)
self.mail(subject=subject, body=body, bcc=community.subscribers)
self.redirect('/module/article/%s' % article.url_path)
| [
[
1,
0,
0.3151,
0.0137,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.3288,
0.0137,
0,
0.66,
0.25,
279,
0,
1,
0,
0,
279,
0,
0
],
[
1,
0,
0.3425,
0.0137,
0,
0.... | [
"import logging",
"from google.appengine.api import mail",
"from handlers.AuthenticatedHandler import *",
"from google.appengine.runtime import apiproxy_errors",
"class CommunityNewArticle(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tarticle = model.Article.get(self.get_param('article'))\n\t\tcommuni... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.BaseHandler import *
class CommunityUserList(BaseHandler):
def execute(self):
self.values['tab'] = '/module/community.list'
url_path = self.request.path.split('/', 3)[3]
community = model.Community.gql('WHERE url_path=:1', url_path).get()
if not community:
self.not_found()
return
self.values['community'] = community
self.values['joined'] = self.joined(community)
query = model.CommunityUser.all().filter('community', community)
self.values['users'] = self.paging(query, 27, '-creation_date', community.members, ['-creation_date'])
self.render('templates/module/community/community-user-list.html') | [
[
1,
0,
0.575,
0.025,
0,
0.66,
0,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.6,
0.025,
0,
0.66,
0.5,
437,
0,
1,
0,
0,
437,
0,
0
],
[
3,
0,
0.825,
0.375,
0,
0.66,
1... | [
"from google.appengine.ext import db",
"from handlers.BaseHandler import *",
"class CommunityUserList(BaseHandler):\n\n\tdef execute(self):\n\t\tself.values['tab'] = '/module/community.list'\n\t\turl_path = self.request.path.split('/', 3)[3]\n\t\tcommunity = model.Community.gql('WHERE url_path=:1', url_path).ge... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class CommunityThreadEdit(AuthenticatedHandler):
def execute(self):
self.values['tab'] = '/module/community.list'
method = self.request.method
user = self.values['user']
key = self.get_param('key')
if method == 'GET':
if key:
# show edit form
thread = model.Thread.get(key)
if user.nickname!= thread.author_nickname and user.rol != 'admin':
self.forbidden()
return
if thread is None:
self.not_found()
return
#TODO Check if it's possible
if thread.parent_thread is None:
self.values['is_parent_thread'] = True
self.values['thread'] = thread
self.render('templates/module/community/community-thread-edit.html')
return
else:
self.show_error("Thread not found")
return
elif self.auth():
if key:
# update comment
thread = model.Thread.get(key)
if user.nickname!= thread.author_nickname and user.rol != 'admin':
self.forbidden()
return
if thread is None:
self.not_found()
return
if user.rol != 'admin':
if thread.editions is None:
thread.editions = 0
thread.editions +=1
thread.last_edition = datetime.datetime.now()
if thread.parent_thread is None:
if thread.responses <= 5:
thread.title = self.get_param('title')
for comment in model.Thread.all().filter('parent_thread', thread):
comment.title = thread.title
comment.put()
thread.content = self.get_param('content')
thread.put()
if thread.parent_thread is None:
memcache.delete(str(thread.key().id()) + '_thread')
memcache.add(str(thread.key().id()) + '_thread', thread, 0)
self.redirect('/module/community.forum/%s' % (thread.url_path))
else:
results = 20
app = self.get_application()
if app.max_results_sublist:
results = app.max_results_sublist
page = thread.response_number / results
if (thread.response_number % results) > 0:
page += 1
if page != 1:
response_url = '/module/community.forum/%s?p=%d' % (thread.url_path, page)
else:
response_url = '/module/community.forum/%s?' % (thread.url_path)
memcache.delete(response_url)
response_url = response_url + '#comment-%d' % (thread.response_number)
self.redirect(response_url)
else:
self.show_error("Comment not found")
return | [
[
1,
0,
0.2347,
0.0102,
0,
0.66,
0,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.2449,
0.0102,
0,
0.66,
0.5,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.6327,
0.7449,
0,
0.6... | [
"from google.appengine.ext import db",
"from handlers.AuthenticatedHandler import *",
"class CommunityThreadEdit(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tself.values['tab'] = '/module/community.list'\n\t\tmethod = self.request.method\n\t\tuser = self.values['user']\n\t\tkey = self.get_param('key')",
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
class CommunityList(BaseHandler):
def execute(self):
self.values['tab'] = '/module/community.list'
query = model.Community.all()
key = '%s?%s' % (self.request.path, self.request.query)
cat = self.get_param('cat')
app = self.get_application()
if cat:
category = model.Category.all().filter('url_path', cat).get()
self.values['category'] = category
self.values['cat'] = cat
query = query.filter('category', category)
max = category.communities
else:
max = app.communities
results = 10
if app.max_results:
results = app.max_results
communities = self.paging(query, results, '-members', max, ['-creation_date', '-members', '-articles'], key)
self.values['communities'] = communities
# denormalization
for g in communities:
if not g.owner_nickname:
g.owner_nickname = g.owner.nickname
g.put()
self.add_categories()
self.add_tag_cloud()
self.render('templates/module/community/community-list.html')
| [
[
1,
0,
0.4259,
0.0185,
0,
0.66,
0,
437,
0,
1,
0,
0,
437,
0,
0
],
[
3,
0,
0.7315,
0.5556,
0,
0.66,
1,
979,
0,
1,
0,
0,
94,
0,
12
],
[
2,
1,
0.75,
0.5185,
1,
0.2,
... | [
"from handlers.BaseHandler import *",
"class CommunityList(BaseHandler):\n\n\tdef execute(self):\n\t\tself.values['tab'] = '/module/community.list'\n\t\tquery = model.Community.all()\n\t\tkey = '%s?%s' % (self.request.path, self.request.query)\n\t\t\n\t\tcat = self.get_param('cat')",
"\tdef execute(self):\n\t\t... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import img
from google.appengine.api import images
from google.appengine.ext import db
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
class CommunityEdit(AuthenticatedHandler):
def execute(self):
self.values['tab'] = '/module/community.list'
method = self.request.method
user = self.values['user']
key = self.get_param('key')
if method == 'GET':
if key:
# show edit form
community = model.Community.get(key)
if user.nickname != community.owner.nickname and user.rol != 'admin':
self.forbidden()
return
self.values['key'] = key
self.values['title'] = community.title
self.values['description'] = community.description
if community.all_users is not None:
self.values['all_users'] = community.all_users
else:
self.values['all_users'] = True
if community.category:
self.values['category'] = community.category
self.add_categories()
self.render('templates/module/community/community-edit.html')
else:
# show an empty form
self.values['title'] = "New community..."
self.values['all_users'] = True
self.add_categories()
self.render('templates/module/community/community-edit.html')
elif self.auth():
if key:
# update community
community = model.Community.get(key)
if user.nickname != community.owner.nickname and user.rol != 'admin':
self.forbidden()
return
# community title is not editable since many-to-many relationships are denormalizated
# community.title = self.get_param('title')
community.description = self.get_param('description')
image = self.request.get("img")
if image:
image = images.im_feeling_lucky(image, images.JPEG)
community.avatar = img.resize(image, 128, 128)
community.thumbnail = img.resize(image, 48, 48)
if not community.image_version:
community.image_version = 1
else:
memcache.delete('/images/community/avatar/%s/%d' % (community.key().id(), community.image_version))
memcache.delete('/images/community/thumbnail/%s/%d' % (community.key().id(), community.image_version))
community.image_version += 1
memcache.delete('/images/community/avatar/%s' % community.key().id())
memcache.delete('/images/community/thumbnail/%s' % community.key().id())
if self.get_param('all_users'):
community.all_users = True
else:
community.all_users = False
category = model.Category.get(self.request.get('category'))
prev_category = community.category
community.category = category
community.put()
if prev_category:
prev_category.communities -= 1
prev_category.put()
category.communities += 1
category.put()
memcache.delete('index_communities')
self.redirect('/module/community/%s' % (community.url_path, ))
else:
# new community
title = self.get_param('title')
url_path = '-'
all_users = False
if self.get_param('all_users'):
all_users = True
community = model.Community(owner=user,
owner_nickname=user.nickname,
title=title,
description=self.get_param('description'),
url_path=url_path,
members=1,
all_users = all_users,
articles=0,
threads=0,
responses=0,
subscribers=[user.email],
activity=1)
category = model.Category.get(self.request.get('category'))
community.category = category
image = self.request.get("img")
if image:
image = images.im_feeling_lucky(image, images.JPEG)
community.avatar = img.resize(image, 128, 128)
community.thumbnail = img.resize(image, 48, 48)
community.image_version = 1
community.put()
self.add_user_subscription(user, 'community', community.key().id())
community.url_path = '%d/%s' % (community.key().id(), self.to_url_path(community.title))
community.put()
category.communities += 1
category.put()
user.communities += 1
user.put()
app = model.Application.all().get()
if app:
app.communities += 1
app.put()
memcache.delete('app')
community_user = model.CommunityUser(user=user,
community=community,
user_nickname=user.nickname,
community_title=community.title,
community_url_path=community.url_path)
community_user.put()
memcache.delete('index_communities')
followers = list(self.get_followers(user=user))
followers.append(user.nickname)
self.create_event(event_type='community.new', followers=followers, user=user, community=community)
self.add_follower(community=community, nickname=user.nickname)
# TODO: update a user counter to know how many communities is owner of?
self.redirect('/module/community/%s' % (community.url_path, )) | [
[
1,
0,
0.1386,
0.006,
0,
0.66,
0,
200,
0,
1,
0,
0,
200,
0,
0
],
[
1,
0,
0.1506,
0.006,
0,
0.66,
0.2,
279,
0,
1,
0,
0,
279,
0,
0
],
[
1,
0,
0.1566,
0.006,
0,
0.66,
... | [
"import img",
"from google.appengine.api import images",
"from google.appengine.ext import db",
"from google.appengine.api import memcache",
"from handlers.AuthenticatedHandler import *",
"class CommunityEdit(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tself.values['tab'] = '/module/community.list'... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import datetime
from google.appengine.runtime import apiproxy_errors
from google.appengine.ext import db
from google.appengine.api import mail
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
class CommunityForumReply(AuthenticatedHandler):
def execute(self):
method = self.request.method
if method == "GET" or not self.auth():
return
user = self.values['user']
key = self.get_param('key')
thread = model.Thread.get(key)
memcache.delete(str(thread.key().id()) + '_thread')
if not thread:
self.not_found()
return
community = thread.community
if community.all_users is not None and not self.can_write(community):
self.forbidden()
return
content = self.get_param('content')
preview = self.get_param('preview')
if preview:
response = model.Thread(community=community,
author=user,
author_nickname=user.nickname,
title=thread.title,
content=content,
parent_thread=thread,
responses=0)
self.values['thread'] = response
self.values['preview'] = True
self.render('templates/module/community/community-thread-edit.html')
return
if self.check_duplicate(community, user, thread, content):
self.show_error("Duplicated reply")
return
response = model.Thread(community=community,
community_title=community.title,
community_url_path=community.url_path,
author=user,
author_nickname=user.nickname,
title=thread.title,
url_path=thread.url_path,
content=content,
parent_thread=thread,
response_number=thread.responses+1,
responses=0,
editions=0)
response.put()
results = 20
app = self.get_application()
if app.max_results_sublist:
results = app.max_results_sublist
page = response.response_number / results
if (response.response_number % results) == 1:
#delete previous page from the cache
if page != 1:
previous_url = '/module/community.forum/%s?p=%d' % (thread.url_path, page)
else:
previous_url = '/module/community.forum/%s?' % (thread.url_path)
memcache.delete(previous_url)
if (response.response_number % results) > 0:
page += 1
if page != 1:
response_url = '/module/community.forum/%s?p=%d' % (thread.url_path, page)
else:
response_url = '/module/community.forum/%s?' % (thread.url_path)
memcache.delete(response_url)
response_url = response_url + '#comment-%d' % (response.response_number)
self.create_community_subscribers(community)
community.responses = community.responses + 1
community.put()
followers = list(self.get_followers(user=user))
followers.append(user.nickname)
followers.extend(self.get_followers(thread=thread))
followers = list(set(followers))
self.create_event(event_type='thread.reply', followers=followers,
user=user, thread=thread, community=community, response_number=response.response_number)
subscribers = thread.subscribers
email_removed = False
if subscribers and user.email in subscribers:
email_removed = True
subscribers.remove(user.email)
if subscribers:
subject = self.getLocale("New reply to: '%s'") % self.clean_ascii(thread.title) # "Nueva respuesta en: '%s'"
body = self.getLocale("New reply to %s.\n%s%s\n\nAll replies:\n%s/module/community.forum/%s\n\nRemove this subscription:\n%s/module/community.forum.subscribe?key=%s") % (self.clean_ascii(thread.title), app.url, response_url, app.url, thread.url_path, app.url, str(thread.key()))
self.mail(subject=subject, body=body, bcc=thread.subscribers)
subscribe = self.get_param('subscribe')
if email_removed:
thread.subscribers.append(user.email)
if subscribe and not user.email in thread.subscribers:
thread.subscribers.append(user.email)
self.add_user_subscription(user, 'thread', thread.key().id())
thread.responses += 1
thread.last_response_date = datetime.datetime.now()
thread.put()
memcache.add(str(thread.key().id()) + '_thread', thread, 0)
community = thread.community
if community.activity:
community.activity += 2
community.put()
memcache.delete('index_threads')
self.redirect(response_url)
def check_duplicate(self, community, user, parent_thread, content):
last_thread = model.Thread.all().filter('community', community).filter('parent_thread', parent_thread).filter('author', user).order('-creation_date').get()
if last_thread is not None:
if last_thread.content == content:
return True
return False
| [
[
1,
0,
0.1554,
0.0068,
0,
0.66,
0,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.1689,
0.0068,
0,
0.66,
0.1667,
155,
0,
1,
0,
0,
155,
0,
0
],
[
1,
0,
0.1757,
0.0068,
0,
... | [
"import datetime",
"from google.appengine.runtime import apiproxy_errors",
"from google.appengine.ext import db",
"from google.appengine.api import mail",
"from google.appengine.api import memcache",
"from handlers.AuthenticatedHandler import *",
"class CommunityForumReply(AuthenticatedHandler):\n\n\tde... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class CommunityUserUnjoin(AuthenticatedHandler):
def execute(self):
user = self.values['user']
community = model.Community.get(self.get_param('community'))
if not community:
self.not_found()
return
if not self.auth():
return
redirect = self.get_param('redirect')
gu = model.CommunityUser.gql('WHERE community=:1 and user=:2', community, user).get()
if gu and user != community.owner:
self.create_community_subscribers(community)
gu.delete()
if user.email in community.subscribers:
community.subscribers.remove(user.email)
community.members -= 1
if community.activity:
community.activity -= 1
community.put()
self.remove_user_subscription(user, 'community', community.key().id())
self.remove_follower(community=community, nickname=user.nickname)
user.communities -= 1
user.put()
self.redirect(redirect)
| [
[
1,
0,
0.4259,
0.0185,
0,
0.66,
0,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.7315,
0.5556,
0,
0.66,
1,
707,
0,
1,
0,
0,
116,
0,
17
],
[
2,
1,
0.75,
0.5185,
1,
0.48,
... | [
"from handlers.AuthenticatedHandler import *",
"class CommunityUserUnjoin(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tuser = self.values['user']\n\t\tcommunity = model.Community.get(self.get_param('community'))\n\t\tif not community:\n\t\t\tself.not_found()\n\t\t\treturn",
"\tdef execute(self):\n\t\tuse... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class CommunityUserJoin(AuthenticatedHandler):
def execute(self):
user = self.values['user']
community = model.Community.get(self.get_param('community'))
if not community:
self.not_found()
return
if not self.auth():
return
redirect = self.get_param('redirect')
gu = self.joined(community)
if gu == 'False':
self.create_community_subscribers(community)
gu = model.CommunityUser(user=user,
community=community,
user_nickname=user.nickname,
community_title=community.title,
community_url_path=community.url_path)
gu.put()
community.subscribers.append(user.email)
community.members += 1
if community.activity:
community.activity += 1
community.put()
self.add_follower(community=community, nickname=user.nickname)
self.add_user_subscription(user, 'community', community.key().id())
user.communities += 1
user.put()
self.redirect(redirect)
| [
[
1,
0,
0.377,
0.0164,
0,
0.66,
0,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.7049,
0.6066,
0,
0.66,
1,
108,
0,
1,
0,
0,
116,
0,
17
],
[
2,
1,
0.7213,
0.5738,
1,
0.64,... | [
"from handlers.AuthenticatedHandler import *",
"class CommunityUserJoin(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tuser = self.values['user']\n\t\tcommunity = model.Community.get(self.get_param('community'))\n\t\tif not community:\n\t\t\tself.not_found()\n\t\t\treturn",
"\tdef execute(self):\n\t\tuser ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class CommunityMove(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
if user.rol != 'admin':
self.forbidden()
return
if method == 'GET':
action = self.get_param('action')
key = self.get_param('key_orig')
if key:
community_orig = model.Community.get(key)
self.values['key_orig'] = community_orig.key
self.render('templates/module/community/community-move.html')
return
elif self.auth():
action = action = self.get_param('action')
if not action:
self.render('templates/module/community/community-move.html')
return
key_orig = self.get_param('key_orig')
if key_orig:
community_orig = model.Community.get(key_orig)
key_dest = self.get_param('key_dest')
if key_dest:
community_dest = model.Community.get(key_dest)
mesagge = ''
if not community_orig:
message = self.getLocale("Source community not exists")
self.values['message'] = message
self.render('templates/module/community/community-move.html')
return
elif not community_dest:
message = self.getLocale("Taget community not exists")
self.values['message'] = message
self.render('templates/module/community/community-move.html')
return
elif action == 'mu':
#move users
message = self.move_users(community_orig, community_dest)
elif action == 'mt':
#move threads
message = self.move_threads(community_orig, community_dest)
memcache.delete('index_threads')
elif action == 'mi':
#move articles
message = self.move_articles(community_orig, community_dest)
elif action == 'delete':
message = self.delete_community(community_orig)
memcache.delete('index_communities')
if action != 'delete':
self.values['key_orig'] = community_orig.key
self.values['key_dest'] = community_dest.key
self.values['message'] = message
self.render('templates/module/community/community-move.html')
return
def move_articles(self, community_orig, community_dest):
community_articles = model.CommunityArticle.all().filter('community', community_orig).fetch(10)
counter = 0
for community_article in community_articles:
article_dest = model.CommunityArticle.all().filter('community', community_dest).filter('article', community_article.article).get()
if article_dest:
community_article.delete()
else:
community_article.community = community_dest
community_article.community_title = community_dest.title
community_article.community_url_path = community_dest.url_path
community_article.put()
community_dest.articles += 1
if community_dest.activity:
community_dest.activity += 15
community_dest.put()
counter +=1
community_orig.articles -= 1
if community_dest.activity:
community_dest.activity -= 15
community_orig.put()
return self.getLocale("%s articles moved. Source community contains %s more.") % (counter, community_orig.articles)
def move_threads(self, community_orig, community_dest):
counter = 0
for community_thread in model.Thread.all().filter('community', community_orig).filter('parent_thread', None).fetch(1):
community_thread.community = community_dest
community_thread.community_url_path = community_dest.url_path
community_thread.community_title = community_dest.title
responses = model.Thread.all().filter('parent_thread', community_thread)
if responses:
for response in responses:
response.community = community_dest
response.community_url_path = community_dest.url_path
response.community_title = community_dest.title
response.put()
counter +=1
community_thread.put()
community_orig.threads -= 1
community_orig.comments -= community_thread.comments
value = 5 + (2 * thread.responses)
if community_orig.activity:
community_dest.activity -= value
community_orig.put()
community_dest.threads += 1
community_dest.comments += community_thread.comments
if community_dest.activity:
community_dest.activity += value
community_dest.put()
return self.getLocale("Moved thread with %s replies. %s threads remain.") % (counter, community_orig.threads)
def move_users(self, community_orig, community_dest):
community_users = model.CommunityUser.all().filter('community', community_orig).fetch(10)
counter = 0
for community_user in community_users:
user_dest = model.CommunityUser.all().filter('community', community_dest).filter('user', community_user.user).get()
if user_dest:
community_user.user.communities -= 1
community_user.user.put()
self.remove_user_subscription(community_user.user, 'community', community_orig.key().id())
community_user.delete()
else:
community_user.community = community_dest
community_dest.members += 1
community_dest.subscribers.append(community_user.user.email)
self.add_follower(community=community_dest, nickname=community_user.user.nickname)
self.add_user_subscription(community_user.user, 'community', community_dest.key().id())
if community_dest.activity:
community_dest.activity += 1
community_dest.put()
counter += 1
community_user.community_title = community_dest.title
community_user.community_url = community_dest.url_path
community_user.put()
community_orig.members -= 1
if community_orig.activity:
community_orig.activity -= 1
community_orig.put()
return self.getLocale("Moved %s users. Source community contains %s more.") % (counter, community_orig.members)
def delete_community(self, community_orig):
community_orig.delete()
app = model.Application.all().get()
if app:
app.communities -= 1
app.put()
memcache.delete('app')
return self.getLocale("Deleted community. %s communities remain.") % (app.communities)
| [
[
1,
0,
0.1292,
0.0056,
0,
0.66,
0,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.1348,
0.0056,
0,
0.66,
0.5,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.573,
0.8596,
0,
0.66... | [
"from google.appengine.ext import db",
"from handlers.AuthenticatedHandler import *",
"class CommunityMove(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tmethod = self.request.method\n\t\tuser = self.values['user']\n\t\tif user.rol != 'admin':\n\t\t\tself.forbidden()\n\t\t\treturn",
"\tdef execute(self):... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import logging
import datetime
from google.appengine.runtime import apiproxy_errors
from google.appengine.ext import db
from google.appengine.api import mail
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
class CommunityForumEdit(AuthenticatedHandler):
def execute(self):
method = self.request.method
if method == "GET" or not self.auth():
return
user = self.values['user']
key = self.get_param('key')
community = model.Community.get(key)
if not community:
self.not_found()
return
if community.all_users is not None and not self.can_write(community):
self.forbidden()
return
title = self.get_param('title')
url_path = ''
content = self.get_param('content')
preview = self.get_param('preview')
if preview:
thread = model.Thread(community=community,
community_url_path=community.url_path,
author=user,
author_nickname = user.nickname,
title=title,
content=content,
responses=0)
self.values['thread'] = thread
self.values['preview'] = True
self.values['is_parent_thread'] = True
self.render('templates/module/community/community-thread-edit.html')
return
if self.check_duplicate(community, user, content, title):
self.show_error("Duplicated thread")
return
thread = model.Thread(community=community,
community_title=community.title,
community_url_path=community.url_path,
author=user,
author_nickname=user.nickname,
title=title,
url_path=url_path,
content=content,
last_response_date = datetime.datetime.now(),
responses=0,
editions=0,
views=0)
user.threads += 1
user.put()
self.create_community_subscribers(community)
app = model.Application.all().get()
if app:
if not app.threads:
app.threads = 0
app.threads += 1
app.put()
memcache.delete('app')
thread.put()
self.add_follower(thread=thread, nickname=user.nickname)
thread.url_path = ('%d/%s/%s') % (thread.key().id(), self.to_url_path(community.title), self.to_url_path(title))
subscribe = self.get_param('subscribe')
if subscribe:
thread.subscribers.append(user.email)
self.add_user_subscription(user, 'thread', thread.key().id())
thread.put()
memcache.add(str(thread.key().id()) + '_thread', thread, 0)
community.threads += 1
if community.activity:
community.activity += 5
community.put()
followers = list(self.get_followers(community=community))
followers.extend(self.get_followers(user=user))
if not user.nickname in followers:
followers.append(user.nickname)
followers = list(set(followers))
self.create_event(event_type='thread.new', followers=followers, user=user, thread=thread, community=community)
subscribers = community.subscribers
if subscribers and user.email in subscribers:
subscribers.remove(user.email)
if subscribers:
app = self.get_application()
subject = self.getLocale("New subject: '%s'") % self.clean_ascii(thread.title)
body = self.getLocale("New subject by community %s.\nSubject title: %s\nFollow forum at:\n%s/module/community.forum/%s") % (self.clean_ascii(community.title), self.clean_ascii(thread.title), app.url, thread.url_path)
self.mail(subject=subject, body=body, bcc=community.subscribers)
memcache.delete('index_threads')
self.redirect('/module/community.forum/%s' % thread.url_path)
def check_duplicate(self, community, user, content, title):
last_thread = model.Thread.all().filter('community', community).filter('parent_thread', None).filter('author', user).order('-creation_date').get()
if last_thread is not None:
if last_thread.title == title and last_thread.content == content:
return True
return False
| [
[
1,
0,
0.1655,
0.0072,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.1727,
0.0072,
0,
0.66,
0.1429,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.1871,
0.0072,
0,
... | [
"import logging",
"import datetime",
"from google.appengine.runtime import apiproxy_errors",
"from google.appengine.ext import db",
"from google.appengine.api import mail",
"from google.appengine.api import memcache",
"from handlers.AuthenticatedHandler import *",
"class CommunityForumEdit(Authenticat... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.BaseHandler import *
class CommunityArticleList(BaseHandler):
def execute(self):
self.values['tab'] = '/module/community.list'
url_path = self.request.path.split('/', 3)[3]
community = model.Community.gql('WHERE url_path=:1', url_path).get()
if not community:
self.not_found()
return
self.values['community'] = community
self.values['joined'] = self.joined(community)
query = model.CommunityArticle.all().filter('community', community)
self.values['articles'] = self.paging(query, 10, '-creation_date', community.articles, ['-creation_date'])
self.render('templates/module/community/community-article-list.html') | [
[
1,
0,
0.575,
0.025,
0,
0.66,
0,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.6,
0.025,
0,
0.66,
0.5,
437,
0,
1,
0,
0,
437,
0,
0
],
[
3,
0,
0.825,
0.375,
0,
0.66,
1... | [
"from google.appengine.ext import db",
"from handlers.BaseHandler import *",
"class CommunityArticleList(BaseHandler):\n\n\tdef execute(self):\n\t\tself.values['tab'] = '/module/community.list'\n\t\turl_path = self.request.path.split('/', 3)[3]\n\t\tcommunity = model.Community.gql('WHERE url_path=:1', url_path)... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.BaseHandler import *
class CommunityView(BaseHandler):
def execute(self):
self.values['tab'] = '/module/community.list'
url_path = self.request.path.split('/', 3)[3]
community = model.Community.gql('WHERE url_path=:1', url_path).get()
if not community:
community = model.Community.gql('WHERE old_url_path=:1', url_path).get()
if community:
self.redirect('/module/community/%s' % community.url_path, permanent=True)
return
self.not_found()
return
self.values['community'] = community
self.values['joined'] = self.joined(community)
self.values['articles'] = list(model.CommunityArticle.all().filter('community', community).order('-creation_date').fetch(5))
self.values['threads'] = list(model.Thread.all().filter('community', community).filter('parent_thread', None).order('-last_response_date').fetch(5))
self.values['users'] = list(model.CommunityUser.all().filter('community', community).order('-creation_date').fetch(27))
self.values['related'] = list(model.RelatedCommunity.all().filter('community_from', community).order('-creation_date').fetch(10))
self.render('templates/module/community/community-view.html') | [
[
1,
0,
0.5,
0.0217,
0,
0.66,
0,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.5217,
0.0217,
0,
0.66,
0.5,
437,
0,
1,
0,
0,
437,
0,
0
],
[
3,
0,
0.7826,
0.4565,
0,
0.66,
... | [
"from google.appengine.ext import db",
"from handlers.BaseHandler import *",
"class CommunityView(BaseHandler):\n\n\tdef execute(self):\n\t\tself.values['tab'] = '/module/community.list'\n\t\turl_path = self.request.path.split('/', 3)[3]\n\t\tcommunity = model.Community.gql('WHERE url_path=:1', url_path).get()\... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.AuthenticatedHandler import *
class CommunityArticleDelete(AuthenticatedHandler):
def execute(self):
article = model.Article.get(self.get_param('article'))
community = model.Community.get(self.get_param('community'))
if not article or not community:
self.not_found()
return
if not self.auth():
return
gi = model.CommunityArticle.gql('WHERE community=:1 and article=:2', community, article).get()
if self.values['user'].nickname == article.author.nickname:
gi.delete()
community.articles -= 1
if community.activity:
community.activity -= 15
community.put()
self.redirect('/module/article/%s' % article.url_path)
| [
[
1,
0,
0.5227,
0.0227,
0,
0.66,
0,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.7841,
0.4545,
0,
0.66,
1,
855,
0,
1,
0,
0,
116,
0,
11
],
[
2,
1,
0.8068,
0.4091,
1,
0.4,... | [
"from handlers.AuthenticatedHandler import *",
"class CommunityArticleDelete(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tarticle = model.Article.get(self.get_param('article'))\n\t\tcommunity = model.Community.get(self.get_param('community'))\n\t\tif not article or not community:\n\t\t\tself.not_found()\n\... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from google.appengine.api import memcache
from handlers.AuthenticatedHandler import *
class CommunityDelete(AuthenticatedHandler):
def execute(self):
user = self.values['user']
if user.rol != 'admin':
self.forbidden()
return
if not self.auth():
return
community=model.Community.get(self.get_param('key'))
db.delete(community.communityuser_set)
db.delete(community.communityarticle_set)
db.delete(community.thread_set)
community.delete()
app = app = model.Application.all().get()
if app:
app.communities -=1
app.put()
memcache.delete('app')
# TODO: some other memcache value should be removed? most active communities?
self.redirect('/')
| [
[
1,
0,
0.4615,
0.0192,
0,
0.66,
0,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.4808,
0.0192,
0,
0.66,
0.3333,
279,
0,
1,
0,
0,
279,
0,
0
],
[
1,
0,
0.5,
0.0192,
0,
0.6... | [
"from google.appengine.ext import db",
"from google.appengine.api import memcache",
"from handlers.AuthenticatedHandler import *",
"class CommunityDelete(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tuser = self.values['user']\n\t\t\n\t\tif user.rol != 'admin':\n\t\t\tself.forbidden()\n\t\t\treturn",
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseRest import *
class CommunityForumVisit(BaseRest):
def get(self):
thread_id = self.request.get('id')
memcache.delete(thread_id + '_thread')
thread = model.Thread.get_by_id(int(thread_id))
thread.views += 1
thread.put()
memcache.add(str(thread.key().id()) + '_thread', thread, 0)
content = []
self.render_json({'views' : thread.views})
return | [
[
1,
0,
0.6389,
0.0278,
0,
0.66,
0,
250,
0,
1,
0,
0,
250,
0,
0
],
[
3,
0,
0.8472,
0.3333,
0,
0.66,
1,
858,
0,
1,
0,
0,
138,
0,
10
],
[
2,
1,
0.875,
0.2778,
1,
0.85,... | [
"from handlers.BaseRest import *",
"class CommunityForumVisit(BaseRest):\n\n\tdef get(self):\n\t\tthread_id = self.request.get('id')\n\t\tmemcache.delete(thread_id + '_thread')\n\t\tthread = model.Thread.get_by_id(int(thread_id))\n\t\tthread.views += 1\n\t\tthread.put()",
"\tdef get(self):\n\t\tthread_id = self... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class CommunityForumView(BaseHandler):
def execute(self):
self.values['tab'] = '/module/community.list'
user = self.values['user']
url_path = self.request.path.split('/', 3)[3]
thread_id = self.request.path.split('/')[3]
thread = self.cache(thread_id + '_thread', self.get_thread)
#thread = model.Thread.all().filter('url_path', url_path).filter('parent_thread', None).get()
if not thread:
# TODO: try with the id in the url_path and redirect
self.not_found()
return
if thread.deletion_date:
self.not_found()
return
# migration. supposed to be finished
if len(thread.url_path.split('/')) == 2:
thread.url_path = '%d/%s' % (thread.key().id(), thread.url_path)
thread.parent_thread = None
thread.put()
self.redirect('/module/community.forum/%s' % thread.url_path)
return
# end migration
'''if thread.views is None:
thread.views = 0;
thread.views += 1
thread.put()'''
community = thread.community
self.values['community'] = community
self.values['joined'] = self.joined(community)
self.values['thread'] = thread
query = model.Thread.all().filter('parent_thread', thread)
results = 20
app = self.get_application()
if app.max_results_sublist:
results = app.max_results_sublist
key = '%s?%s' % (self.request.path, self.request.query)
responses = self.paging(query, results, 'creation_date', thread.responses, ['creation_date'], key=key, timeout=0)
#responses = self.cache(url_path, self.get_responses)
# migration
if not thread.author_nickname:
thread.author_nickname = thread.author.nickname
thread.put()
i = 1
for t in responses:
if not t.response_number:
t.response_number = i
t.put()
i += 1
# end migration
self.values['responses'] = responses
if community.all_users:
self.values['can_write'] = True
else:
self.values['can_write'] = self.can_write(community)
if user:
if user.email in thread.subscribers:
self.values['cansubscribe'] = False
else:
self.values['cansubscribe'] = True
self.values['a'] = 'comments'
self.render('templates/module/community/community-forum-view.html')
def get_thread(self):
url_path = self.request.path.split('/', 3)[3]
return model.Thread.all().filter('url_path', url_path).filter('parent_thread', None).get()
| [
[
1,
0,
0.2323,
0.0101,
0,
0.66,
0,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.2424,
0.0101,
0,
0.66,
0.5,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.6212,
0.7273,
0,
0.6... | [
"from google.appengine.ext import db",
"from handlers.AuthenticatedHandler import *",
"class CommunityForumView(BaseHandler):\n\n\tdef execute(self):\n\t\tself.values['tab'] = '/module/community.list'\n\t\tuser = self.values['user']\n\t\turl_path = self.request.path.split('/', 3)[3]\n\t\tthread_id = self.reques... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class CommunityForumSubscribe( AuthenticatedHandler ):
def execute(self):
key = self.get_param('key')#TODO if key is empty app crashed
thread = model.Thread.get(key)
memcache.delete(str(thread.key().id()) + '_thread')
user = self.values['user']
mail = user.email
if not mail in thread.subscribers:
if not self.auth():
return
thread.subscribers.append(user.email)
thread.put()
self.add_user_subscription(user, 'thread', thread.key().id())
memcache.add(str(thread.key().id()) + '_thread', thread, 0)
if self.get_param('x'):
self.render_json({ 'action': 'subscribed' })
else:
self.redirect('/module/community.forum/%s' % thread.url_path)
else:
auth = self.get_param('auth')
if not auth:
self.values['thread'] = thread
self.render('templates/module/community/community-forum-subscribe.html')
else:
if not self.auth():
return
thread.subscribers.remove(user.email)
thread.put()
self.remove_user_subscription(user, 'thread', thread.key().id())
if self.get_param('x'):
self.render_json({ 'action': 'unsubscribed' })
else:
self.redirect('/module/community.forum/%s' % thread.url_path)
| [
[
1,
0,
0.3607,
0.0164,
0,
0.66,
0,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.377,
0.0164,
0,
0.66,
0.5,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.7049,
0.5738,
0,
0.66... | [
"from google.appengine.ext import db",
"from handlers.AuthenticatedHandler import *",
"class CommunityForumSubscribe( AuthenticatedHandler ):\n\n\tdef execute(self):\n\t\tkey = self.get_param('key')#TODO if key is empty app crashed\n\t\tthread = model.Thread.get(key)\n\t\tmemcache.delete(str(thread.key().id()) ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import datetime
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class CommunityForumDelete(AuthenticatedHandler):
def execute(self):
user = self.values['user']
if user.rol != 'admin':
self.forbidden()
return
if not self.auth():
return
thread = model.Thread.get(self.get_param('key'))
url = '/module/community.forum.list/' + thread.community.url_path
if not thread:
self.not_found()
return
if thread.parent_thread is not None:
message = self.get_param('message')
#decrement number of childs in the parent thread
thread.parent_thread.put()
#Delete child thread
thread.deletion_date = datetime.datetime.now()
thread.deletion_message = message
thread.put()
else:
#decrement threads in the community
community = thread.community
if community.activity:
value = 5 + (2 * thread.responses)
community.activity -= value
community.threads -=1
community.put()
#decrement thread in the app
app = model.Application().all().get()
app.threads -= 1
app.put()
memcache.delete('app')
#delete comments in this thread
childs = model.Thread.all().filter('parent_thread', thread)
db.delete(childs)
memcache.delete('index_threads')
thread.delete()
memcache.delete(str(thread.key().id()) + '_thread')
self.redirect(url)
| [
[
1,
0,
0.3194,
0.0139,
0,
0.66,
0,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.3472,
0.0139,
0,
0.66,
0.3333,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.3611,
0.0139,
0,
... | [
"import datetime",
"from google.appengine.ext import db",
"from handlers.AuthenticatedHandler import *",
"class CommunityForumDelete(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tuser = self.values['user']\n\t\tif user.rol != 'admin':\n\t\t\tself.forbidden()\n\t\t\treturn",
"\tdef execute(self):\n\t\t... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.BaseHandler import *
class CommunityForumList(BaseHandler):
def execute(self):
self.values['tab'] = '/module/community.list'
url_path = self.request.path.split('/', 3)[3]
community = model.Community.gql('WHERE url_path=:1', url_path).get()
if not community:
self.not_found()
return
self.values['community'] = community
self.values['joined'] = self.joined(community)
if community.all_users is None or community.all_users:
self.values['can_write'] = True
else:
self.values['can_write'] = self.can_write(community)
query = model.Thread.all().filter('community', community).filter('parent_thread', None)
threads = self.paging(query, 20, '-last_response_date', community.threads, ['-last_response_date'])
self.values['threads'] = threads
self.render('templates/module/community/community-forum-list.html') | [
[
1,
0,
0.5,
0.0227,
0,
0.66,
0,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.5227,
0.0227,
0,
0.66,
0.5,
437,
0,
1,
0,
0,
437,
0,
0
],
[
3,
0,
0.7841,
0.4545,
0,
0.66,
... | [
"from google.appengine.ext import db",
"from handlers.BaseHandler import *",
"class CommunityForumList(BaseHandler):\n\n\tdef execute(self):\n\t\tself.values['tab'] = '/module/community.list'\n\t\turl_path = self.request.path.split('/', 3)[3]\n\t\tcommunity = model.Community.gql('WHERE url_path=:1', url_path).g... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from handlers.AuthenticatedHandler import *
class CommunityForumMove(AuthenticatedHandler):
def execute(self):
method = self.request.method
user = self.values['user']
if user.rol != 'admin':
self.forbidden()
return
if method == 'GET':
thread_key = self.get_param('thread_key')
thread = model.Thread.get(thread_key)
if thread is None:
self.not_found()
return
self.values['thread_key'] = thread.key
self.render('templates/module/community/community-forum-move.html')
return
elif self.auth():
thread_key = self.get_param('thread_key')
community_key = self.get_param('community_key')
thread = model.Thread.get(thread_key)
community = model.Community.get(community_key)
if community is None or thread is None:
self.values['thread_key'] = thread.key
self.values['message'] = "Community not exists."
self.render('templates/module/community/community-forum-move.html')
return
if community.title == thread.community.title:
self.values['thread_key'] = thread.key
self.values['message'] = "Source and target community are the same one."
self.render('templates/module/community/community-forum-move.html')
return
#decrement threads in previous community
community_orig = thread.community
community_orig.threads -= 1
community_orig.responses= thread.responses
value = 5 + (2 * thread.responses)
if community_orig.activity:
community_orig.activity -= value
#update comments
responses = model.Thread.all().filter('parent_thread', thread)
for response in responses:
response.community = community
response.community_title = community.title
response.community_url_path = community.url_path
response.put()
#change gorup in thread and desnormalizated fields
thread.community = community
thread.community_title = community.title
thread.community_url_path = community.url_path
#increment threads in actual community
community.threads += 1
community.responses += thread.responses
if community.activity:
community.activity += value
#save fields
community_orig.put()
thread.put()
community.put()
self.redirect('/module/community.forum/%s' % (thread.url_path))
return
| [
[
1,
0,
0.2347,
0.0102,
0,
0.66,
0,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.2449,
0.0102,
0,
0.66,
0.5,
548,
0,
1,
0,
0,
548,
0,
0
],
[
3,
0,
0.6276,
0.7347,
0,
0.6... | [
"from google.appengine.ext import db",
"from handlers.AuthenticatedHandler import *",
"class CommunityForumMove(AuthenticatedHandler):\n\n\tdef execute(self):\n\t\tmethod = self.request.method\n\t\tuser = self.values['user']\n\t\tif user.rol != 'admin':\n\t\t\tself.forbidden()\n\t\t\treturn",
"\tdef execute(s... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import memcache
from google.appengine.ext.webapp import template
from handlers.BaseHandler import *
from utilities.AppProperties import AppProperties
# Params
UPDATER_VERSION = "0.8"
def update():
app = model.Application.all().get()
if app is None:
initializeDb()
#self.response.out.write('App installed. Created user administrator. nickname="admin", password="1234". Please change the password.')
return
elif not app.session_seed:
import sha, random
app.session_seed = sha.new(str(random.random())).hexdigest()
app.put()
#self.response.out.write('Seed installed')
version = app.version
if version is None or version != UPDATER_VERSION:
update07to08()
#self.response.out.write ('updated to version 0.8')
# elif app.version == '0.8':
# update08to09()
# elif app.version == '0.9':
# update09to10()
return
def initializeDb():
app = model.Application.all().get()
if app is None:
app = model.Application()
app.name = 'vikuit-example'
app.subject = 'Social portal: lightweight and easy to install'
app.recaptcha_public_key = '6LdORAMAAAAAAL42zaVvAyYeoOowf4V85ETg0_h-'
app.recaptcha_private_key = '6LdORAMAAAAAAGS9WvIBg5d7kwOBNaNpqwKXllMQ'
app.theme = 'blackbook'
app.users = 0
app.communities = 0
app.articles = 0
app.threads = 0
app.url = "http://localhost:8080"
app.mail_subject_prefix = "[Vikuit]"
app.mail_sender = "admin.example@vikuit.com"
app.mail_footer = ""
app.max_results = 20
app.max_results_sublist = 20
import sha, random
app.session_seed = sha.new(str(random.random())).hexdigest()
app.version = UPDATER_VERSION
app.put()
user = model.UserData(nickname='admin',
email='admin.example@vikuit.com',
password='1:c07cbf8821d47575a471c1606a56b79e5f6e6a68',
language='en',
articles=0,
draft_articles=0,
messages=0,
draft_messages=0,
comments=0,
rating_count=0,
rating_total=0,
rating_average=0,
threads=0,
responses=0,
communities=0,
favourites=0,
public=False,
contacts=0,
rol='admin')
user.put()
parent_category = model.Category(title='General',
description='General category description',
articles = 0,
communities = 0)
parent_category.put()
category = model.Category(title='News',
description='News description',
articles = 0,
communities = 0)
category.parent_category = parent_category
category.put()
post = model.Mblog(author=user,
author_nickname=user.nickname,
content='Welcome to Vikuit!!',
responses=0)
post.put()
# update from 0.7 to 0.8 release
def update07to08():
app = model.Application.all().get()
app.theme = 'blackbook'
app.version = '0.8'
app.put()
memcache.delete('app')
AppProperties().updateJinjaEnv()
return
# update from 0.8 to 0.9 release
def update08to09():
app = model.Application.all().get()
app.version = '0.9'
app.put()
# update from 0.9 to 01 release
def update09to10():
app = model.Application.all().get()
app.version = '1.0'
app.put()
| [
[
1,
0,
0.1513,
0.0066,
0,
0.66,
0,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.1579,
0.0066,
0,
0.66,
0.0909,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.1645,
0.0066,
0,
... | [
"from google.appengine.ext import db",
"from google.appengine.ext import webapp",
"from google.appengine.api import memcache",
"from google.appengine.ext.webapp import template",
"from handlers.BaseHandler import *",
"from utilities.AppProperties import AppProperties",
"UPDATER_VERSION = \"0.8\"",
"de... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
# (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com>
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
import model
import logging
from google.appengine.api import memcache
from google.appengine.ext import webapp
class ImageDisplayer(webapp.RequestHandler):
def get(self):
cached = memcache.get(self.request.path)
params = self.request.path.split('/')
if params[2] == 'user':
user = model.UserData.gql('WHERE nickname=:1', params[4]).get()
self.display_image(user, params, cached, 'user128_1.png', 'user48_1.png')
elif params[2] == 'community':
community = model.Community.get_by_id(int(params[4]))
self.display_image(community, params, cached, 'community128.png', 'community48.png')
elif params[2] == 'gallery':
query = model.Image.gql('WHERE url_path=:1', '%s/%s' % (params[4], params[5]) )
image = query.get()
self.display_image(image, params, cached, 'unknown128.png', 'unknown48.png', False)
elif params[2] == 'application':
app = model.Application.all().get()
image = app.logo
self.display_image(image, params, cached, 'logo.gif', 'logo.gif', False)
else:
self.error(404)
return
def display_image(self, obj, params, cached, default_avatar, default_thumbnail, not_gallery=True):
if obj is None:
if not_gallery:
self.error(404)
else:
self.redirect('/static/images/%s' % default_thumbnail)
return
image = None
if cached:
image = self.write_image(cached)
else:
if params[3] == 'avatar':
image = obj.avatar
if not image:
self.redirect('/static/images/%s' % default_avatar)
return
elif params[3] == 'thumbnail':
image = obj.thumbnail
if not image:
self.redirect('/static/images/%s' % default_thumbnail)
return
elif params[3] == 'logo':
image = obj
if not image:
self.redirect('/static/images/%s' % default_thumbnail)
return
if not_gallery and (len(params) == 5 or not obj.image_version or int(params[5]) != obj.image_version):
if not obj.image_version:
obj.image_version = 1
obj.put()
newparams = params[:5]
newparams.append(str(obj.image_version))
self.redirect('/'.join(newparams))
return
# self.response.headers['Content-Type'] = 'text/plain'
# self.response.out.write('/'.join(params))
else:
if not cached:
memcache.add(self.request.path, image)
self.write_image(image)
def write_image(self, image):
self.response.headers['Content-Type'] = 'image/jpg'
self.response.headers['Cache-Control'] = 'public, max-age=31536000'
self.response.out.write(image)
def showImage(self, image, default):
if image:
self.write_image(image)
memcache.add(self.request.path, image)
else:
self.redirect('/static/images/%s' % default) | [
[
1,
0,
0.2243,
0.0093,
0,
0.66,
0,
722,
0,
1,
0,
0,
722,
0,
0
],
[
1,
0,
0.2336,
0.0093,
0,
0.66,
0.25,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.2523,
0.0093,
0,
0.... | [
"import model",
"import logging",
"from google.appengine.api import memcache",
"from google.appengine.ext import webapp",
"class ImageDisplayer(webapp.RequestHandler):\n\n\tdef get(self):\n\t\tcached = memcache.get(self.request.path)\n\t\t\n\t\tparams = self.request.path.split('/')\n\t\tif params[2] == 'use... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Alberto Gimeno <gimenete at gmail dot com>
#
# This file is part of "debug_mode_on".
#
# "debug_mode_on" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "debug_mode_on" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>.
#
import model
import simplejson
from google.appengine.ext import webapp
class TaskQueue(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain;charset=utf-8'
task = model.Task.all().order('-priority').get()
if not task:
self.response.out.write('No pending tasks')
return
data = simplejson.loads(task.data)
data = self.__class__.__dict__[task.task_type].__call__(self, data)
if data is None:
self.response.out.write('Task finished %s %s' % (task.task_type, task.data))
task.delete()
else:
task.data = simplejson.dumps(data)
task.put()
self.response.out.write('Task executed but not finished %s %s' % (task.task_type, task.data))
def delete_recommendations(self, data):
offset = data['offset']
recs = model.Recommendation.all().fetch(1, offset)
if len(recs) == 0:
return None
next = recs[0]
article_to = next.article_to
article_from = next.article_from
if article_from.draft or article_to.draft or article_from.deletion_date is not None or article_to.deletion_date is not None:
next.delete()
else:
data['offset'] += 1
return data
def update_recommendations(self, data):
offset = data['offset']
recs = model.Recommendation.all().fetch(1, offset)
if len(recs) == 0:
return None
next = recs[0]
article_to = next.article_to
article_from = next.article_from
self.calculate_recommendation(article_from, article_to)
data['offset'] += 1
return data
def begin_recommendations(self, data):
offset = data['offset']
articles = model.Article.all().filter('draft', False).filter('deletion_date', None).order('creation_date').fetch(1, offset)
print 'articles: %d' % len(articles)
if len(articles) == 0:
return None
next = articles[0]
data['offset'] += 1
t = model.Task(task_type='article_recommendation', priority=0, data=simplejson.dumps({'article': next.key().id(), 'offset': 0}))
t.put()
return data
def article_recommendation(self, data):
article = model.Article.get_by_id(data['article'])
if article.draft or article.deletion_date is not None:
return None
offset = data['offset']
articles = model.Article.all().filter('draft', False).filter('deletion_date', None).order('creation_date').fetch(1, offset)
if not articles:
return None
next = articles[0]
data['offset'] += 1
self.calculate_recommendation(next, article)
return data
def calculate_recommendation(self, next, article):
def distance(v1, v2):
all = []
all.extend(v1)
all.extend(v2)
return float(len(all) - len(set(all)))
def create_recommendation(article_from, article_to, value):
return model.Recommendation(article_from=article_from,
article_to=article_to,
value=value,
article_from_title=article_from.title,
article_to_title=article_to.title,
article_from_author_nickname=article_from.author_nickname,
article_to_author_nickname=article_to.author_nickname,
article_from_url_path=article_from.url_path,
article_to_url_path=article_to.url_path)
if next.key().id() == article.key().id():
return
r1 = model.Recommendation.all().filter('article_from', article).filter('article_to', next).get()
r2 = model.Recommendation.all().filter('article_from', next).filter('article_to', article).get()
diff = distance(article.tags, next.tags)
if diff > 0:
if not r1:
r1 = create_recommendation(article, next, diff)
else:
r1.value = diff
if not r2:
r2 = create_recommendation(next, article, diff)
else:
r2.value = diff
r1.put()
r2.put()
else:
if r1:
r1.delete()
if r2:
r2.delete()
| [
[
1,
0,
0.1465,
0.0064,
0,
0.66,
0,
722,
0,
1,
0,
0,
722,
0,
0
],
[
1,
0,
0.1529,
0.0064,
0,
0.66,
0.3333,
386,
0,
1,
0,
0,
386,
0,
0
],
[
1,
0,
0.1656,
0.0064,
0,
... | [
"import model",
"import simplejson",
"from google.appengine.ext import webapp",
"class TaskQueue(webapp.RequestHandler):\n\n\tdef get(self):\n\t\tself.response.headers['Content-Type'] = 'text/plain;charset=utf-8'\n\t\t\n\t\ttask = model.Task.all().order('-priority').get()\n\t\t\n\t\tif not task:",
"\tdef ge... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
class Dispatcher(BaseHandler):
def execute(self):
referer = self.request.path.split('/', 1)[1]
# if referer.startswith('module'):
# referer = self.request.path.split('/',2)[2]
self.add_tag_cloud()
self.values['tab'] = self.request.path
self.render('templates/%s.html' % referer) | [
[
1,
0,
0.697,
0.0303,
0,
0.66,
0,
437,
0,
1,
0,
0,
437,
0,
0
],
[
3,
0,
0.8788,
0.2727,
0,
0.66,
1,
958,
0,
1,
0,
0,
94,
0,
3
],
[
2,
1,
0.9091,
0.2121,
1,
0.19,
... | [
"from handlers.BaseHandler import *",
"class Dispatcher(BaseHandler):\n\n\tdef execute(self):\n\t\treferer = self.request.path.split('/', 1)[1]\n#\t\tif referer.startswith('module'):\n#\t\t\treferer = self.request.path.split('/',2)[2]\n\t\tself.add_tag_cloud()\n\t\tself.values['tab'] = self.request.path",
"\tde... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
class AuthenticatedHandler(BaseHandler):
def pre_execute(self):
user = self.get_current_user()
#user = self.values['user']
if not user:
self.redirect(self.values['login'])
return
self.execute() | [
[
1,
0,
0.697,
0.0303,
0,
0.66,
0,
437,
0,
1,
0,
0,
437,
0,
0
],
[
3,
0,
0.8788,
0.2727,
0,
0.66,
1,
116,
0,
1,
0,
0,
94,
0,
3
],
[
2,
1,
0.9091,
0.2121,
1,
0.38,
... | [
"from handlers.BaseHandler import *",
"class AuthenticatedHandler(BaseHandler):\n\n\tdef pre_execute(self):\n\t\tuser = self.get_current_user()\n\t\t#user = self.values['user']\n\t\tif not user:\n\t\t\tself.redirect(self.values['login'])\n\t\t\treturn",
"\tdef pre_execute(self):\n\t\tuser = self.get_current_use... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Alberto Gimeno <gimenete at gmail dot com>
#
# This file is part of "debug_mode_on".
#
# "debug_mode_on" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "debug_mode_on" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>.
#
from handlers.BaseHandler import *
class Static(BaseHandler):
def execute(self):
template = self.request.path.split('/', 2)[2]
self.render('templates/static/%s' % template) | [
[
1,
0,
0.7931,
0.0345,
0,
0.66,
0,
437,
0,
1,
0,
0,
437,
0,
0
],
[
3,
0,
0.931,
0.1724,
0,
0.66,
1,
794,
0,
1,
0,
0,
94,
0,
2
],
[
2,
1,
0.9655,
0.1034,
1,
0.32,
... | [
"from handlers.BaseHandler import *",
"class Static(BaseHandler):\n\n\tdef execute(self):\n\t\ttemplate = self.request.path.split('/', 2)[2]\n\t\tself.render('templates/static/%s' % template)",
"\tdef execute(self):\n\t\ttemplate = self.request.path.split('/', 2)[2]\n\t\tself.render('templates/static/%s' % temp... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Copyright 2008 Alberto Gimeno <gimenete at gmail dot com>
# (C) Copyright 2008 Ignacio Andreu <plunchete at gmail dot com>
# (C) Copyright 2008 Néstor Salceda <nestor.salceda at gmail dot com>
#
# This file is part of "debug_mode_on".
#
# "debug_mode_on" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "debug_mode_on" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "debug_mode_on". If not, see <http://www.gnu.org/licenses/>.
#
from handlers.BaseHandler import *
class Search(BaseHandler):
def execute(self):
q = self.get_param('q')
typ = self.get_param('t')
if typ == 'articles':
query = model.Article.all().filter('draft', False).filter('deletion_date', None).search(q)
self.values['articles'] = self.paging(query, 10)
self.add_tag_cloud()
elif typ == 'forums':
query = model.Thread.all().search(q)
threads = self.paging(query, 10)
# migration
for t in threads:
if not t.url_path:
t.url_path = t.parent_thread.url_path
t.put()
# end migration
self.values['threads'] = threads
else:
query = model.Community.all().search(q)
self.values['communities'] = self.paging(query, 10)
self.values['q'] = q
self.values['t'] = typ
self.render('templates/search.html')
| [
[
1,
0,
0.4717,
0.0189,
0,
0.66,
0,
437,
0,
1,
0,
0,
437,
0,
0
],
[
3,
0,
0.7547,
0.5094,
0,
0.66,
1,
123,
0,
1,
0,
0,
94,
0,
16
],
[
2,
1,
0.7736,
0.4717,
1,
0.34,... | [
"from handlers.BaseHandler import *",
"class Search(BaseHandler):\n\n\tdef execute(self):\n\t\tq = self.get_param('q')\n\t\ttyp = self.get_param('t')\n\n\t\tif typ == 'articles':\n\t\t\tquery = model.Article.all().filter('draft', False).filter('deletion_date', None).search(q)",
"\tdef execute(self):\n\t\tq = se... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.MainPage import *
### MODULES ###
# Admin
from handlers.module.admin.Admin import *
from handlers.module.admin.AdminCategories import *
from handlers.module.admin.AdminCategoryEdit import *
from handlers.module.admin.AdminApplication import *
from handlers.module.admin.CommunityAddRelated import *
from handlers.module.admin.AdminUsers import *
from handlers.module.admin.AdminModules import *
from handlers.module.admin.AdminLookAndFeel import *
from handlers.module.admin.AdminGoogle import *
from handlers.module.admin.AdminMail import *
from handlers.module.admin.AdminCache import *
from handlers.module.admin.AdminStats import *
# Articles
from handlers.module.article.ArticleList import *
from handlers.module.article.ArticleEdit import *
from handlers.module.article.ArticleView import *
from handlers.module.article.ArticleVote import *
from handlers.module.article.ArticleDelete import *
from handlers.module.article.ArticleComment import *
from handlers.module.article.ArticleFavourite import *
from handlers.module.article.ArticleCommentSubscribe import *
from handlers.module.article.ArticleCommentDelete import *
from handlers.module.article.ArticleAddCommunities import *
from handlers.module.article.ArticleCommentEdit import *
from handlers.module.article.ArticleVisit import *
# Communities
from handlers.module.community.CommunityList import *
from handlers.module.community.CommunityEdit import *
from handlers.module.community.CommunityView import *
from handlers.module.community.CommunityMove import *
from handlers.module.community.CommunityDelete import *
# community forums
from handlers.module.community.CommunityForumList import *
from handlers.module.community.CommunityForumEdit import *
from handlers.module.community.CommunityForumView import *
from handlers.module.community.CommunityForumReply import *
from handlers.module.community.CommunityForumSubscribe import *
from handlers.module.community.CommunityForumDelete import *
from handlers.module.community.CommunityThreadEdit import *
from handlers.module.community.CommunityForumMove import *
from handlers.module.community.CommunityForumVisit import *
# community articles
from handlers.module.community.CommunityArticleList import *
from handlers.module.community.CommunityNewArticle import *
from handlers.module.community.CommunityArticleDelete import *
# community users
from handlers.module.community.CommunityUserList import *
from handlers.module.community.CommunityUserUnjoin import *
from handlers.module.community.CommunityUserJoin import *
# Users
from handlers.module.user.UserList import *
from handlers.module.user.UserView import *
from handlers.module.user.UserEdit import *
from handlers.module.user.UserArticles import *
from handlers.module.user.UserLogin import *
from handlers.module.user.UserCommunities import *
from handlers.module.user.UserLogout import *
from handlers.module.user.UserRegister import *
from handlers.module.user.UserChangePassword import *
from handlers.module.user.UserForgotPassword import *
from handlers.module.user.UserResetPassword import *
from handlers.module.user.UserDrafts import *
from handlers.module.user.UserContact import *
from handlers.module.user.UserFavourites import *
from handlers.module.user.UserContacts import *
from handlers.module.user.UserPromote import *
from handlers.module.user.UserEvents import *
from handlers.module.user.UserForums import *
# Blogging
from handlers.module.mblog.MBlogEdit import *
# Messages
from handlers.module.message.MessageEdit import *
from handlers.module.message.MessageSent import *
from handlers.module.message.MessageInbox import *
from handlers.module.message.MessageRead import *
from handlers.module.message.MessageDelete import *
### Common handlers / Other Handlers ###
# forums
from handlers.ForumList import *
#search
from handlers.SearchResult import *
# inviting contacts
from handlers.Invite import *
# feed RSS
from handlers.Feed import *
# images
from handlers.ImageDisplayer import *
from handlers.editor.ImageBrowser import *
from handlers.editor.ImageUploader import *
#Queue
from handlers.MailQueue import *
from handlers.TaskQueue import *
from handlers.Tag import *
from handlers.Search import *
from handlers.Dispatcher import *
from handlers.Initialization import *
from handlers.NotFound import *
from handlers.BaseRest import *
from handlers.Static import *
| [
[
1,
0,
0.1716,
0.0075,
0,
0.66,
0,
49,
0,
1,
0,
0,
49,
0,
0
],
[
1,
0,
0.209,
0.0075,
0,
0.66,
0.0119,
188,
0,
1,
0,
0,
188,
0,
0
],
[
1,
0,
0.2164,
0.0075,
0,
0.6... | [
"from handlers.MainPage import *",
"from handlers.module.admin.Admin import *",
"from handlers.module.admin.AdminCategories import *",
"from handlers.module.admin.AdminCategoryEdit import *",
"from handlers.module.admin.AdminApplication import *",
"from handlers.module.admin.CommunityAddRelated import *",... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com>
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from handlers.BaseHandler import *
class Initialization(BaseHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
app = model.Application.all().get()
if app is None:
populateDB()
self.response.out.write('App installed. Created user administrator. nickname="admin", password="1234". Please change the password.')
return
elif not app.session_seed:
import sha, random
app.session_seed = sha.new(str(random.random())).hexdigest()
app.put()
self.response.out.write('Seed installed')
return
p = int(self.request.get('p'))
key = self.request.get('key')
action = self.request.get('action')
if key:
community = model.Community.get(key)
if not community:
self.response.out.write('community not found')
return
offset = (p-1)*10
if action == 'gi':
i = self.community_articles(community, offset)
elif action == 'gu':
i = self.community_users(community, offset)
elif action == 'th':
i = self.threads(offset)
elif action == 'cc':
i = self.contacts(offset)
elif action == 'fv':
i = self.favourites(offset)
elif action == 'sg':
i = self.show_communities(offset)
return
elif action == 'ut':
i = self.update_threads(offset)
elif action == 'uis':
i = self.update_article_subscription(p-1)
self.response.out.write('Processed from %d to %d. %d updated. Action %s' % (p-1, i[0], i[1], action))
return
elif action == 'ugs':
i = self.update_community_subscription(community, offset)
elif action == 'uts':
i = self.update_thread_subscription(p-1)
self.response.out.write('Processed from %d to %d. %d updated. Action %s' % (p-1, i[0], i[1], action))
return
elif action == 'ugc':
i = self.update_community_counters(p-1)
self.response.out.write('Processed from %d to %d. %d updated. Action %s' % (p-1, i[0], i[1], action))
return
elif action == 'adus':
i = self.add_date_user_subscription(offset)
elif action == 'afg':
i = self.add_follower_community(offset)
elif action == 'afu':
i = self.add_follower_user(offset)
elif action == 'afi':
i = self.add_follower_article(offset)
elif action == 'aft':
i = self.add_follower_thread(offset)
else:
self.response.out.write('unknown action -%s-' % action)
return
self.response.out.write('Processed from %d to %d. %d updated. Action %s' % (offset, i[0], i[1], action))
def community_articles(self, community, offset):
i = offset
p = 0
for gi in model.CommunityArticle.all().filter('community', community).order('-creation_date').fetch(10, offset):
if not gi.community_title:
article = gi.article
community = gi.community
gi.article_author_nickname = article.author_nickname
gi.article_title = article.title
gi.article_url_path = article.url_path
gi.community_title = community.title
gi.community_url_path = community.url_path
gi.put()
p += 1
i+=1
return (i, p)
def community_users(self, community, offset):
i = offset
p = 0
for gu in model.CommunityUser.all().filter('community', community).order('-creation_date').fetch(10, offset):
if not gu.community_title:
user = gu.user
community = gu.community
gu.user_nickname = gu.user.nickname
gu.community_title = community.title
gu.community_url_path = community.url_path
gu.put()
p += 1
i+=1
return (i, p)
def threads(self, offset):
i = offset
p = 0
for th in model.Thread.all().order('-creation_date').fetch(10, offset):
if not th.community_title:
community = th.community
th.community_title = community.title
th.community_url_path = community.url_path
if not th.url_path:
th.url_path = th.parent_thread.url_path
th.put()
p += 1
i+=1
return (i, p)
def contacts(self, offset):
i = offset
p = 0
for cc in model.Contact.all().order('-creation_date').fetch(10, offset):
if not cc.user_from_nickname:
cc.user_from_nickname = cc.user_from.nickname
cc.user_to_nickname = cc.user_to.nickname
cc.put()
p += 1
i+=1
return (i, p)
def favourites(self, offset):
i = offset
p = 0
for fv in model.Favourite.all().order('-creation_date').fetch(10, offset):
if not fv.user_nickname:
article = fv.article
fv.article_author_nickname = article.author_nickname
fv.article_title = article.title
fv.article_url_path = article.url_path
fv.user_nickname = fv.user.nickname
fv.put()
p += 1
i+=1
return (i, p)
def show_communities(self, offset):
for g in model.Community.all().order('-creation_date').fetch(10, offset):
self.response.out.write("('%s', '%s', %d),\n" % (g.title, str(g.key()), g.members))
def update_threads(self, offset):
i = offset
p = 0
for th in model.Thread.all().filter('parent_thread', None).order('-creation_date').fetch(10, offset):
if th.views is None:
th.views = 0
th.put()
p += 1
i+=1
return (i, p)
def update_article_subscription(self, offset):
i = offset
p = 0
for article in model.Article.all().order('-creation_date').fetch(1, offset):
if article.subscribers:
for subscriber in article.subscribers:
user = model.UserData.all().filter('email', subscriber).get()
if not model.UserSubscription.all().filter('user', user).filter('subscription_type', 'article').filter('subscription_id', article.key().id()).get():
self.add_user_subscription(user, 'article', article.key().id())
p += 1
i+=1
return (i, p)
def update_community_subscription(self, community, offset):
i = offset
p = 0
for community_user in model.CommunityUser.all().filter('community', community).order('-creation_date').fetch(10, offset):
if not model.UserSubscription.all().filter('user', community_user.user).filter('subscription_type', 'community').filter('subscription_id', community.key().id()).get():
self.add_user_subscription(community_user.user, 'community', community.key().id())
p += 1
i += 1
return (i, p)
def update_thread_subscription(self, offset):
i = offset
p = 0
for thread in model.Thread.all().filter('parent_thread', None).order('-creation_date').fetch(1, offset):
if thread.subscribers:
for subscriber in thread.subscribers:
user = model.UserData.all().filter('email', subscriber).get()
if not model.UserSubscription.all().filter('user', user).filter('subscription_type', 'thread').filter('subscription_id', thread.key().id()).get():
self.add_user_subscription(user, 'thread', thread.key().id())
p += 1
i+=1
return (i, p)
def update_community_counters(self, offset):
i = offset
p = 0
for community in model.Community.all().order('-creation_date').fetch(1, offset):
users = model.CommunityUser.all().filter('community', community).count()
articles = model.CommunityArticle.all().filter('community', community).count()
community_threads = model.Thread.all().filter('community', community).filter('parent_thread', None)
threads = community_threads.count()
comments = 0
for thread in community_threads:
comments += model.Thread.all().filter('community', community).filter('parent_thread', thread).count()
if community.members != users or community.articles != articles or community.threads != threads or community.responses != comments:
community.members = users
community.articles = articles
community.threads = threads
community.responses = comments
p += 1
if not community.activity:
community.activity = 0
community.activity = (community.members * 1) + (community.threads * 5) + (community.articles * 15) + (community.responses * 2)
community.put()
i += 1
return (i, p)
def add_date_user_subscription(self, offset):
i = offset
p = 0
for user_subscription in model.UserSubscription.all().fetch(10, offset):
if user_subscription.creation_date is None:
user_subscription.creation_date = datetime.datetime.now()
user_subscription.put()
p += 1
i += 1
return (i, p)
def add_follower_community(self, offset):
i = offset
p = 0
for community_user in model.CommunityUser.all().fetch(10, offset):
if community_user.user_nickname is None:
self.desnormalizate_community_user(community_user)
self.add_follower(community=community_user, nickname=community_user.user_nickname)
p +=1
i += 1
return(i,p)
def add_follower_user(self, offset):
i = offset
p = 0
for cc in model.Contact.all().fetch(10, offset):
if cc.user_from_nickname is None:
self.desnormalizate_user_contact(cc)
self.add_follower(user=cc.user_to, nickname=cc.user_from_nickname)
p += 1
i += 1
return(i,p)
def add_follower_article(self, offset):
i = offset
p = 0
for article in model.Article.all().filter('deletion_date', None).filter('draft', False).fetch(10, offset):
self.add_follower(article=article, nickname=article.author_nickname)
p += 1
i += 1
return(i,p)
def add_follower_thread(self, offset):
i = offset
p = 0
for t in model.Thread.all().filter('parent_thread', None).fetch(10, offset):
self.add_follower(thread=t, nickname=t.author_nickname)
p += 1
i += 1
return(i, p)
def desnormalizate_community_user(self, gu):
user = gu.user
community = gu.community
gu.user_nickname = gu.user.nickname
gu.community_title = community.title
gu.community_url_path = community.url_path
gu.put()
def desnormalizate_user_contact(self, cc):
cc.user_from_nickname = cc.user_from.nickname
cc.user_to_nickname = cc.user_to.nickname
cc.put()
def populateDB():
app = model.Application.all().get()
if app is None:
app = model.Application()
app.name = 'vikuit-example'
app.subject = 'Social portal: lightweight and easy to install'
app.recaptcha_public_key = '6LdORAMAAAAAAL42zaVvAyYeoOowf4V85ETg0_h-'
app.recaptcha_private_key = '6LdORAMAAAAAAGS9WvIBg5d7kwOBNaNpqwKXllMQ'
app.theme = 'blackbook'
app.users = 0
app.communities = 0
app.articles = 0
app.threads = 0
app.url = "http://localhost:8080"
app.mail_subject_prefix = "[Vikuit]"
app.mail_sender = "admin.example@vikuit.com"
app.mail_footer = ""
app.max_results = 20
app.max_results_sublist = 20
import sha, random
app.session_seed = sha.new(str(random.random())).hexdigest()
app.put()
user = model.UserData(nickname='admin',
email='admin.example@vikuit.com',
password='1:c07cbf8821d47575a471c1606a56b79e5f6e6a68',
language='en',
articles=0,
draft_articles=0,
messages=0,
draft_messages=0,
comments=0,
rating_count=0,
rating_total=0,
rating_average=0,
threads=0,
responses=0,
communities=0,
favourites=0,
public=False,
contacts=0,
rol='admin')
user.put()
parent_category = model.Category(title='General',
description='General category description',
articles = 0,
communities = 0)
parent_category.put()
category = model.Category(title='News',
description='News description',
articles = 0,
communities = 0)
category.parent_category = parent_category
category.put()
post = model.Mblog(author=user,
author_nickname=user.nickname,
content='Welcome to Vikuit!!',
responses=0)
post.put()
| [
[
1,
0,
0.0632,
0.0026,
0,
0.66,
0,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.0658,
0.0026,
0,
0.66,
0.2,
167,
0,
1,
0,
0,
167,
0,
0
],
[
1,
0,
0.0684,
0.0026,
0,
0.6... | [
"from google.appengine.ext import db",
"from google.appengine.ext import webapp",
"from google.appengine.ext.webapp import template",
"from handlers.BaseHandler import *",
"class Initialization(BaseHandler):\n\n\tdef get(self):\n\t\tself.response.headers['Content-Type'] = 'text/plain'\n\t\t\n\t\tapp = model... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# (C) Copyright 2011 Jose Carrasco <jose.carrasco[a]vikuit.com>
# (C) Copyright 2011 Jose Blanco <jose.blanco[a]vikuit.com>
#
# This file is part of "vikuit".
#
# "vikuit" is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# "vikuit" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with "vikuit". If not, see <http://www.gnu.org/licenses/>.
##
from handlers.BaseHandler import *
class MainPage(BaseHandler):
def execute(self):
self.values['tab'] = '/'
# memcache.delete('index_articles')
# memcache.delete('index_communities')
# memcache.delete('index_threads')
self.values['articles'] = self.cache('index_articles', self.get_articles)
# self.values['communities'] = self.cache('index_communities', self.get_communities)
self.values['threads'] = self.cache('index_threads', self.get_threads)
self.add_tag_cloud()
# self.add_categories()
self.render('templates/index.html')
def get_articles(self):
return model.Article.all().filter('draft', False).filter('deletion_date', None).order('-creation_date').fetch(5)
# return self.render_chunk('templates/index-articles.html', {'articles': articles})
def get_communities(self):
return model.Community.all().order('-members').fetch(5)
# return self.render_chunk('templates/index-communities.html', {'communities': communities})
def get_threads(self):
return model.Thread.all().filter('parent_thread', None).order('-last_response_date').fetch(5)
# return self.render_chunk('templates/index-threads.html', {'threads': threads})
| [
[
1,
0,
0.48,
0.02,
0,
0.66,
0,
437,
0,
1,
0,
0,
437,
0,
0
],
[
3,
0,
0.75,
0.48,
0,
0.66,
1,
516,
0,
4,
0,
0,
94,
0,
16
],
[
2,
1,
0.66,
0.22,
1,
0.62,
0,
... | [
"from handlers.BaseHandler import *",
"class MainPage(BaseHandler):\n\n\tdef execute(self):\n\t\tself.values['tab'] = '/'\n\t\t# memcache.delete('index_articles')\n\t\t# memcache.delete('index_communities')\n\t\t# memcache.delete('index_threads')\n\t\tself.values['articles'] = self.cache('index_articles', self.ge... |
# -*- coding: utf-8 -*-
"""
jinja2.runtime
~~~~~~~~~~~~~~
Runtime helpers.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD.
"""
import sys
from itertools import chain, imap
from jinja2.nodes import EvalContext, _context_function_types
from jinja2.utils import Markup, partial, soft_unicode, escape, missing, \
concat, internalcode, next, object_type_repr
from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \
TemplateNotFound
# these variables are exported to the template runtime
__all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',
'TemplateRuntimeError', 'missing', 'concat', 'escape',
'markup_join', 'unicode_join', 'to_string', 'identity',
'TemplateNotFound']
#: the name of the function that is used to convert something into
#: a string. 2to3 will adopt that automatically and the generated
#: code can take advantage of it.
to_string = unicode
#: the identity function. Useful for certain things in the environment
identity = lambda x: x
def markup_join(seq):
"""Concatenation that escapes if necessary and converts to unicode."""
buf = []
iterator = imap(soft_unicode, seq)
for arg in iterator:
buf.append(arg)
if hasattr(arg, '__html__'):
return Markup(u'').join(chain(buf, iterator))
return concat(buf)
def unicode_join(seq):
"""Simple args to unicode conversion and concatenation."""
return concat(imap(unicode, seq))
def new_context(environment, template_name, blocks, vars=None,
shared=None, globals=None, locals=None):
"""Internal helper to for context creation."""
if vars is None:
vars = {}
if shared:
parent = vars
else:
parent = dict(globals or (), **vars)
if locals:
# if the parent is shared a copy should be created because
# we don't want to modify the dict passed
if shared:
parent = dict(parent)
for key, value in locals.iteritems():
if key[:2] == 'l_' and value is not missing:
parent[key[2:]] = value
return Context(environment, parent, template_name, blocks)
class TemplateReference(object):
"""The `self` in templates."""
def __init__(self, context):
self.__context = context
def __getitem__(self, name):
blocks = self.__context.blocks[name]
wrap = self.__context.eval_ctx.autoescape and \
Markup or (lambda x: x)
return BlockReference(name, self.__context, blocks, 0)
def __repr__(self):
return '<%s %r>' % (
self.__class__.__name__,
self.__context.name
)
class Context(object):
"""The template context holds the variables of a template. It stores the
values passed to the template and also the names the template exports.
Creating instances is neither supported nor useful as it's created
automatically at various stages of the template evaluation and should not
be created by hand.
The context is immutable. Modifications on :attr:`parent` **must not**
happen and modifications on :attr:`vars` are allowed from generated
template code only. Template filters and global functions marked as
:func:`contextfunction`\s get the active context passed as first argument
and are allowed to access the context read-only.
The template context supports read only dict operations (`get`,
`keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,
`__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`
method that doesn't fail with a `KeyError` but returns an
:class:`Undefined` object for missing variables.
"""
__slots__ = ('parent', 'vars', 'environment', 'eval_ctx', 'exported_vars',
'name', 'blocks', '__weakref__')
def __init__(self, environment, parent, name, blocks):
self.parent = parent
self.vars = {}
self.environment = environment
self.eval_ctx = EvalContext(self.environment, name)
self.exported_vars = set()
self.name = name
# create the initial mapping of blocks. Whenever template inheritance
# takes place the runtime will update this mapping with the new blocks
# from the template.
self.blocks = dict((k, [v]) for k, v in blocks.iteritems())
def super(self, name, current):
"""Render a parent block."""
try:
blocks = self.blocks[name]
index = blocks.index(current) + 1
blocks[index]
except LookupError:
return self.environment.undefined('there is no parent block '
'called %r.' % name,
name='super')
return BlockReference(name, self, blocks, index)
def get(self, key, default=None):
"""Returns an item from the template context, if it doesn't exist
`default` is returned.
"""
try:
return self[key]
except KeyError:
return default
def resolve(self, key):
"""Looks up a variable like `__getitem__` or `get` but returns an
:class:`Undefined` object with the name of the name looked up.
"""
if key in self.vars:
return self.vars[key]
if key in self.parent:
return self.parent[key]
return self.environment.undefined(name=key)
def get_exported(self):
"""Get a new dict with the exported variables."""
return dict((k, self.vars[k]) for k in self.exported_vars)
def get_all(self):
"""Return a copy of the complete context as dict including the
exported variables.
"""
return dict(self.parent, **self.vars)
@internalcode
def call(__self, __obj, *args, **kwargs):
"""Call the callable with the arguments and keyword arguments
provided but inject the active context or environment as first
argument if the callable is a :func:`contextfunction` or
:func:`environmentfunction`.
"""
if __debug__:
__traceback_hide__ = True
if isinstance(__obj, _context_function_types):
if getattr(__obj, 'contextfunction', 0):
args = (__self,) + args
elif getattr(__obj, 'evalcontextfunction', 0):
args = (__self.eval_ctx,) + args
elif getattr(__obj, 'environmentfunction', 0):
args = (__self.environment,) + args
try:
return __obj(*args, **kwargs)
except StopIteration:
return __self.environment.undefined('value was undefined because '
'a callable raised a '
'StopIteration exception')
def derived(self, locals=None):
"""Internal helper function to create a derived context."""
context = new_context(self.environment, self.name, {},
self.parent, True, None, locals)
context.eval_ctx = self.eval_ctx
context.blocks.update((k, list(v)) for k, v in self.blocks.iteritems())
return context
def _all(meth):
proxy = lambda self: getattr(self.get_all(), meth)()
proxy.__doc__ = getattr(dict, meth).__doc__
proxy.__name__ = meth
return proxy
keys = _all('keys')
values = _all('values')
items = _all('items')
# not available on python 3
if hasattr(dict, 'iterkeys'):
iterkeys = _all('iterkeys')
itervalues = _all('itervalues')
iteritems = _all('iteritems')
del _all
def __contains__(self, name):
return name in self.vars or name in self.parent
def __getitem__(self, key):
"""Lookup a variable or raise `KeyError` if the variable is
undefined.
"""
item = self.resolve(key)
if isinstance(item, Undefined):
raise KeyError(key)
return item
def __repr__(self):
return '<%s %s of %r>' % (
self.__class__.__name__,
repr(self.get_all()),
self.name
)
# register the context as mapping if possible
try:
from collections import Mapping
Mapping.register(Context)
except ImportError:
pass
class BlockReference(object):
"""One block on a template reference."""
def __init__(self, name, context, stack, depth):
self.name = name
self._context = context
self._stack = stack
self._depth = depth
@property
def super(self):
"""Super the block."""
if self._depth + 1 >= len(self._stack):
return self._context.environment. \
undefined('there is no parent block called %r.' %
self.name, name='super')
return BlockReference(self.name, self._context, self._stack,
self._depth + 1)
@internalcode
def __call__(self):
rv = concat(self._stack[self._depth](self._context))
if self._context.eval_ctx.autoescape:
rv = Markup(rv)
return rv
class LoopContext(object):
"""A loop context for dynamic iteration."""
def __init__(self, iterable, recurse=None):
self._iterator = iter(iterable)
self._recurse = recurse
self.index0 = -1
# try to get the length of the iterable early. This must be done
# here because there are some broken iterators around where there
# __len__ is the number of iterations left (i'm looking at your
# listreverseiterator!).
try:
self._length = len(iterable)
except (TypeError, AttributeError):
self._length = None
def cycle(self, *args):
"""Cycles among the arguments with the current loop index."""
if not args:
raise TypeError('no items for cycling given')
return args[self.index0 % len(args)]
first = property(lambda x: x.index0 == 0)
last = property(lambda x: x.index0 + 1 == x.length)
index = property(lambda x: x.index0 + 1)
revindex = property(lambda x: x.length - x.index0)
revindex0 = property(lambda x: x.length - x.index)
def __len__(self):
return self.length
def __iter__(self):
return LoopContextIterator(self)
@internalcode
def loop(self, iterable):
if self._recurse is None:
raise TypeError('Tried to call non recursive loop. Maybe you '
"forgot the 'recursive' modifier.")
return self._recurse(iterable, self._recurse)
# a nifty trick to enhance the error message if someone tried to call
# the the loop without or with too many arguments.
__call__ = loop
del loop
@property
def length(self):
if self._length is None:
# if was not possible to get the length of the iterator when
# the loop context was created (ie: iterating over a generator)
# we have to convert the iterable into a sequence and use the
# length of that.
iterable = tuple(self._iterator)
self._iterator = iter(iterable)
self._length = len(iterable) + self.index0 + 1
return self._length
def __repr__(self):
return '<%s %r/%r>' % (
self.__class__.__name__,
self.index,
self.length
)
class LoopContextIterator(object):
"""The iterator for a loop context."""
__slots__ = ('context',)
def __init__(self, context):
self.context = context
def __iter__(self):
return self
def next(self):
ctx = self.context
ctx.index0 += 1
return next(ctx._iterator), ctx
class Macro(object):
"""Wraps a macro function."""
def __init__(self, environment, func, name, arguments, defaults,
catch_kwargs, catch_varargs, caller):
self._environment = environment
self._func = func
self._argument_count = len(arguments)
self.name = name
self.arguments = arguments
self.defaults = defaults
self.catch_kwargs = catch_kwargs
self.catch_varargs = catch_varargs
self.caller = caller
@internalcode
def __call__(self, *args, **kwargs):
# try to consume the positional arguments
arguments = list(args[:self._argument_count])
off = len(arguments)
# if the number of arguments consumed is not the number of
# arguments expected we start filling in keyword arguments
# and defaults.
if off != self._argument_count:
for idx, name in enumerate(self.arguments[len(arguments):]):
try:
value = kwargs.pop(name)
except KeyError:
try:
value = self.defaults[idx - self._argument_count + off]
except IndexError:
value = self._environment.undefined(
'parameter %r was not provided' % name, name=name)
arguments.append(value)
# it's important that the order of these arguments does not change
# if not also changed in the compiler's `function_scoping` method.
# the order is caller, keyword arguments, positional arguments!
if self.caller:
caller = kwargs.pop('caller', None)
if caller is None:
caller = self._environment.undefined('No caller defined',
name='caller')
arguments.append(caller)
if self.catch_kwargs:
arguments.append(kwargs)
elif kwargs:
raise TypeError('macro %r takes no keyword argument %r' %
(self.name, next(iter(kwargs))))
if self.catch_varargs:
arguments.append(args[self._argument_count:])
elif len(args) > self._argument_count:
raise TypeError('macro %r takes not more than %d argument(s)' %
(self.name, len(self.arguments)))
return self._func(*arguments)
def __repr__(self):
return '<%s %s>' % (
self.__class__.__name__,
self.name is None and 'anonymous' or repr(self.name)
)
class Undefined(object):
"""The default undefined type. This undefined type can be printed and
iterated over, but every other access will raise an :exc:`UndefinedError`:
>>> foo = Undefined(name='foo')
>>> str(foo)
''
>>> not foo
True
>>> foo + 42
Traceback (most recent call last):
...
UndefinedError: 'foo' is undefined
"""
__slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name',
'_undefined_exception')
def __init__(self, hint=None, obj=missing, name=None, exc=UndefinedError):
self._undefined_hint = hint
self._undefined_obj = obj
self._undefined_name = name
self._undefined_exception = exc
@internalcode
def _fail_with_undefined_error(self, *args, **kwargs):
"""Regular callback function for undefined objects that raises an
`UndefinedError` on call.
"""
if self._undefined_hint is None:
if self._undefined_obj is missing:
hint = '%r is undefined' % self._undefined_name
elif not isinstance(self._undefined_name, basestring):
hint = '%s has no element %r' % (
object_type_repr(self._undefined_obj),
self._undefined_name
)
else:
hint = '%r has no attribute %r' % (
object_type_repr(self._undefined_obj),
self._undefined_name
)
else:
hint = self._undefined_hint
raise self._undefined_exception(hint)
__add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
__truediv__ = __rtruediv__ = __floordiv__ = __rfloordiv__ = \
__mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
__getattr__ = __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = \
__int__ = __float__ = __complex__ = __pow__ = __rpow__ = \
_fail_with_undefined_error
def __str__(self):
return unicode(self).encode('utf-8')
# unicode goes after __str__ because we configured 2to3 to rename
# __unicode__ to __str__. because the 2to3 tree is not designed to
# remove nodes from it, we leave the above __str__ around and let
# it override at runtime.
def __unicode__(self):
return u''
def __len__(self):
return 0
def __iter__(self):
if 0:
yield None
def __nonzero__(self):
return False
def __repr__(self):
return 'Undefined'
class DebugUndefined(Undefined):
"""An undefined that returns the debug info when printed.
>>> foo = DebugUndefined(name='foo')
>>> str(foo)
'{{ foo }}'
>>> not foo
True
>>> foo + 42
Traceback (most recent call last):
...
UndefinedError: 'foo' is undefined
"""
__slots__ = ()
def __unicode__(self):
if self._undefined_hint is None:
if self._undefined_obj is missing:
return u'{{ %s }}' % self._undefined_name
return '{{ no such element: %s[%r] }}' % (
object_type_repr(self._undefined_obj),
self._undefined_name
)
return u'{{ undefined value printed: %s }}' % self._undefined_hint
class StrictUndefined(Undefined):
"""An undefined that barks on print and iteration as well as boolean
tests and all kinds of comparisons. In other words: you can do nothing
with it except checking if it's defined using the `defined` test.
>>> foo = StrictUndefined(name='foo')
>>> str(foo)
Traceback (most recent call last):
...
UndefinedError: 'foo' is undefined
>>> not foo
Traceback (most recent call last):
...
UndefinedError: 'foo' is undefined
>>> foo + 42
Traceback (most recent call last):
...
UndefinedError: 'foo' is undefined
"""
__slots__ = ()
__iter__ = __unicode__ = __str__ = __len__ = __nonzero__ = __eq__ = \
__ne__ = __bool__ = Undefined._fail_with_undefined_error
# remove remaining slots attributes, after the metaclass did the magic they
# are unneeded and irritating as they contain wrong data for the subclasses.
del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__
| [
[
8,
0,
0.011,
0.0165,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0202,
0.0018,
0,
0.66,
0.0476,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0221,
0.0018,
0,
0.66,... | [
"\"\"\"\n jinja2.runtime\n ~~~~~~~~~~~~~~\n\n Runtime helpers.\n\n :copyright: (c) 2010 by the Jinja Team.\n :license: BSD.",
"import sys",
"from itertools import chain, imap",
"from jinja2.nodes import EvalContext, _context_function_types",
"from jinja2.utils import Markup, partial, soft_uni... |
# -*- coding: utf-8 -*-
"""
jinja2.nodes
~~~~~~~~~~~~
This module implements additional nodes derived from the ast base node.
It also provides some node tree helper functions like `in_lineno` and
`get_nodes` used by the parser and translator in order to normalize
python and jinja nodes.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import operator
from itertools import chain, izip
from collections import deque
from jinja2.utils import Markup, MethodType, FunctionType
#: the types we support for context functions
_context_function_types = (FunctionType, MethodType)
_binop_to_func = {
'*': operator.mul,
'/': operator.truediv,
'//': operator.floordiv,
'**': operator.pow,
'%': operator.mod,
'+': operator.add,
'-': operator.sub
}
_uaop_to_func = {
'not': operator.not_,
'+': operator.pos,
'-': operator.neg
}
_cmpop_to_func = {
'eq': operator.eq,
'ne': operator.ne,
'gt': operator.gt,
'gteq': operator.ge,
'lt': operator.lt,
'lteq': operator.le,
'in': lambda a, b: a in b,
'notin': lambda a, b: a not in b
}
class Impossible(Exception):
"""Raised if the node could not perform a requested action."""
class NodeType(type):
"""A metaclass for nodes that handles the field and attribute
inheritance. fields and attributes from the parent class are
automatically forwarded to the child."""
def __new__(cls, name, bases, d):
for attr in 'fields', 'attributes':
storage = []
storage.extend(getattr(bases[0], attr, ()))
storage.extend(d.get(attr, ()))
assert len(bases) == 1, 'multiple inheritance not allowed'
assert len(storage) == len(set(storage)), 'layout conflict'
d[attr] = tuple(storage)
d.setdefault('abstract', False)
return type.__new__(cls, name, bases, d)
class EvalContext(object):
"""Holds evaluation time information. Custom attributes can be attached
to it in extensions.
"""
def __init__(self, environment, template_name=None):
if callable(environment.autoescape):
self.autoescape = environment.autoescape(template_name)
else:
self.autoescape = environment.autoescape
self.volatile = False
def save(self):
return self.__dict__.copy()
def revert(self, old):
self.__dict__.clear()
self.__dict__.update(old)
def get_eval_context(node, ctx):
if ctx is None:
if node.environment is None:
raise RuntimeError('if no eval context is passed, the '
'node must have an attached '
'environment.')
return EvalContext(node.environment)
return ctx
class Node(object):
"""Baseclass for all Jinja2 nodes. There are a number of nodes available
of different types. There are three major types:
- :class:`Stmt`: statements
- :class:`Expr`: expressions
- :class:`Helper`: helper nodes
- :class:`Template`: the outermost wrapper node
All nodes have fields and attributes. Fields may be other nodes, lists,
or arbitrary values. Fields are passed to the constructor as regular
positional arguments, attributes as keyword arguments. Each node has
two attributes: `lineno` (the line number of the node) and `environment`.
The `environment` attribute is set at the end of the parsing process for
all nodes automatically.
"""
__metaclass__ = NodeType
fields = ()
attributes = ('lineno', 'environment')
abstract = True
def __init__(self, *fields, **attributes):
if self.abstract:
raise TypeError('abstract nodes are not instanciable')
if fields:
if len(fields) != len(self.fields):
if not self.fields:
raise TypeError('%r takes 0 arguments' %
self.__class__.__name__)
raise TypeError('%r takes 0 or %d argument%s' % (
self.__class__.__name__,
len(self.fields),
len(self.fields) != 1 and 's' or ''
))
for name, arg in izip(self.fields, fields):
setattr(self, name, arg)
for attr in self.attributes:
setattr(self, attr, attributes.pop(attr, None))
if attributes:
raise TypeError('unknown attribute %r' %
iter(attributes).next())
def iter_fields(self, exclude=None, only=None):
"""This method iterates over all fields that are defined and yields
``(key, value)`` tuples. Per default all fields are returned, but
it's possible to limit that to some fields by providing the `only`
parameter or to exclude some using the `exclude` parameter. Both
should be sets or tuples of field names.
"""
for name in self.fields:
if (exclude is only is None) or \
(exclude is not None and name not in exclude) or \
(only is not None and name in only):
try:
yield name, getattr(self, name)
except AttributeError:
pass
def iter_child_nodes(self, exclude=None, only=None):
"""Iterates over all direct child nodes of the node. This iterates
over all fields and yields the values of they are nodes. If the value
of a field is a list all the nodes in that list are returned.
"""
for field, item in self.iter_fields(exclude, only):
if isinstance(item, list):
for n in item:
if isinstance(n, Node):
yield n
elif isinstance(item, Node):
yield item
def find(self, node_type):
"""Find the first node of a given type. If no such node exists the
return value is `None`.
"""
for result in self.find_all(node_type):
return result
def find_all(self, node_type):
"""Find all the nodes of a given type. If the type is a tuple,
the check is performed for any of the tuple items.
"""
for child in self.iter_child_nodes():
if isinstance(child, node_type):
yield child
for result in child.find_all(node_type):
yield result
def set_ctx(self, ctx):
"""Reset the context of a node and all child nodes. Per default the
parser will all generate nodes that have a 'load' context as it's the
most common one. This method is used in the parser to set assignment
targets and other nodes to a store context.
"""
todo = deque([self])
while todo:
node = todo.popleft()
if 'ctx' in node.fields:
node.ctx = ctx
todo.extend(node.iter_child_nodes())
return self
def set_lineno(self, lineno, override=False):
"""Set the line numbers of the node and children."""
todo = deque([self])
while todo:
node = todo.popleft()
if 'lineno' in node.attributes:
if node.lineno is None or override:
node.lineno = lineno
todo.extend(node.iter_child_nodes())
return self
def set_environment(self, environment):
"""Set the environment for all nodes."""
todo = deque([self])
while todo:
node = todo.popleft()
node.environment = environment
todo.extend(node.iter_child_nodes())
return self
def __eq__(self, other):
return type(self) is type(other) and \
tuple(self.iter_fields()) == tuple(other.iter_fields())
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return '%s(%s)' % (
self.__class__.__name__,
', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
arg in self.fields)
)
class Stmt(Node):
"""Base node for all statements."""
abstract = True
class Helper(Node):
"""Nodes that exist in a specific context only."""
abstract = True
class Template(Node):
"""Node that represents a template. This must be the outermost node that
is passed to the compiler.
"""
fields = ('body',)
class Output(Stmt):
"""A node that holds multiple expressions which are then printed out.
This is used both for the `print` statement and the regular template data.
"""
fields = ('nodes',)
class Extends(Stmt):
"""Represents an extends statement."""
fields = ('template',)
class For(Stmt):
"""The for loop. `target` is the target for the iteration (usually a
:class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
of nodes that are used as loop-body, and `else_` a list of nodes for the
`else` block. If no else node exists it has to be an empty list.
For filtered nodes an expression can be stored as `test`, otherwise `None`.
"""
fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')
class If(Stmt):
"""If `test` is true, `body` is rendered, else `else_`."""
fields = ('test', 'body', 'else_')
class Macro(Stmt):
"""A macro definition. `name` is the name of the macro, `args` a list of
arguments and `defaults` a list of defaults if there are any. `body` is
a list of nodes for the macro body.
"""
fields = ('name', 'args', 'defaults', 'body')
class CallBlock(Stmt):
"""Like a macro without a name but a call instead. `call` is called with
the unnamed macro as `caller` argument this node holds.
"""
fields = ('call', 'args', 'defaults', 'body')
class FilterBlock(Stmt):
"""Node for filter sections."""
fields = ('body', 'filter')
class Block(Stmt):
"""A node that represents a block."""
fields = ('name', 'body', 'scoped')
class Include(Stmt):
"""A node that represents the include tag."""
fields = ('template', 'with_context', 'ignore_missing')
class Import(Stmt):
"""A node that represents the import tag."""
fields = ('template', 'target', 'with_context')
class FromImport(Stmt):
"""A node that represents the from import tag. It's important to not
pass unsafe names to the name attribute. The compiler translates the
attribute lookups directly into getattr calls and does *not* use the
subscript callback of the interface. As exported variables may not
start with double underscores (which the parser asserts) this is not a
problem for regular Jinja code, but if this node is used in an extension
extra care must be taken.
The list of names may contain tuples if aliases are wanted.
"""
fields = ('template', 'names', 'with_context')
class ExprStmt(Stmt):
"""A statement that evaluates an expression and discards the result."""
fields = ('node',)
class Assign(Stmt):
"""Assigns an expression to a target."""
fields = ('target', 'node')
class Expr(Node):
"""Baseclass for all expressions."""
abstract = True
def as_const(self, eval_ctx=None):
"""Return the value of the expression as constant or raise
:exc:`Impossible` if this was not possible.
An :class:`EvalContext` can be provided, if none is given
a default context is created which requires the nodes to have
an attached environment.
.. versionchanged:: 2.4
the `eval_ctx` parameter was added.
"""
raise Impossible()
def can_assign(self):
"""Check if it's possible to assign something to this node."""
return False
class BinExpr(Expr):
"""Baseclass for all binary expressions."""
fields = ('left', 'right')
operator = None
abstract = True
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
f = _binop_to_func[self.operator]
try:
return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
except:
raise Impossible()
class UnaryExpr(Expr):
"""Baseclass for all unary expressions."""
fields = ('node',)
operator = None
abstract = True
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
f = _uaop_to_func[self.operator]
try:
return f(self.node.as_const(eval_ctx))
except:
raise Impossible()
class Name(Expr):
"""Looks up a name or stores a value in a name.
The `ctx` of the node can be one of the following values:
- `store`: store a value in the name
- `load`: load that name
- `param`: like `store` but if the name was defined as function parameter.
"""
fields = ('name', 'ctx')
def can_assign(self):
return self.name not in ('true', 'false', 'none',
'True', 'False', 'None')
class Literal(Expr):
"""Baseclass for literals."""
abstract = True
class Const(Literal):
"""All constant values. The parser will return this node for simple
constants such as ``42`` or ``"foo"`` but it can be used to store more
complex values such as lists too. Only constants with a safe
representation (objects where ``eval(repr(x)) == x`` is true).
"""
fields = ('value',)
def as_const(self, eval_ctx=None):
return self.value
@classmethod
def from_untrusted(cls, value, lineno=None, environment=None):
"""Return a const object if the value is representable as
constant value in the generated code, otherwise it will raise
an `Impossible` exception.
"""
from compiler import has_safe_repr
if not has_safe_repr(value):
raise Impossible()
return cls(value, lineno=lineno, environment=environment)
class TemplateData(Literal):
"""A constant template string."""
fields = ('data',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if eval_ctx.volatile:
raise Impossible()
if eval_ctx.autoescape:
return Markup(self.data)
return self.data
class Tuple(Literal):
"""For loop unpacking and some other things like multiple arguments
for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
is used for loading the names or storing.
"""
fields = ('items', 'ctx')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return tuple(x.as_const(eval_ctx) for x in self.items)
def can_assign(self):
for item in self.items:
if not item.can_assign():
return False
return True
class List(Literal):
"""Any list literal such as ``[1, 2, 3]``"""
fields = ('items',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return [x.as_const(eval_ctx) for x in self.items]
class Dict(Literal):
"""Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
:class:`Pair` nodes.
"""
fields = ('items',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return dict(x.as_const(eval_ctx) for x in self.items)
class Pair(Helper):
"""A key, value pair for dicts."""
fields = ('key', 'value')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
class Keyword(Helper):
"""A key, value pair for keyword arguments where key is a string."""
fields = ('key', 'value')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return self.key, self.value.as_const(eval_ctx)
class CondExpr(Expr):
"""A conditional expression (inline if expression). (``{{
foo if bar else baz }}``)
"""
fields = ('test', 'expr1', 'expr2')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if self.test.as_const(eval_ctx):
return self.expr1.as_const(eval_ctx)
# if we evaluate to an undefined object, we better do that at runtime
if self.expr2 is None:
raise Impossible()
return self.expr2.as_const(eval_ctx)
class Filter(Expr):
"""This node applies a filter on an expression. `name` is the name of
the filter, the rest of the fields are the same as for :class:`Call`.
If the `node` of a filter is `None` the contents of the last buffer are
filtered. Buffers are created by macros and filter blocks.
"""
fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if eval_ctx.volatile or self.node is None:
raise Impossible()
# we have to be careful here because we call filter_ below.
# if this variable would be called filter, 2to3 would wrap the
# call in a list beause it is assuming we are talking about the
# builtin filter function here which no longer returns a list in
# python 3. because of that, do not rename filter_ to filter!
filter_ = self.environment.filters.get(self.name)
if filter_ is None or getattr(filter_, 'contextfilter', False):
raise Impossible()
obj = self.node.as_const(eval_ctx)
args = [x.as_const(eval_ctx) for x in self.args]
if getattr(filter_, 'evalcontextfilter', False):
args.insert(0, eval_ctx)
elif getattr(filter_, 'environmentfilter', False):
args.insert(0, self.environment)
kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
if self.dyn_args is not None:
try:
args.extend(self.dyn_args.as_const(eval_ctx))
except:
raise Impossible()
if self.dyn_kwargs is not None:
try:
kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
except:
raise Impossible()
try:
return filter_(obj, *args, **kwargs)
except:
raise Impossible()
class Test(Expr):
"""Applies a test on an expression. `name` is the name of the test, the
rest of the fields are the same as for :class:`Call`.
"""
fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
class Call(Expr):
"""Calls an expression. `args` is a list of arguments, `kwargs` a list
of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
and `dyn_kwargs` has to be either `None` or a node that is used as
node for dynamic positional (``*args``) or keyword (``**kwargs``)
arguments.
"""
fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if eval_ctx.volatile:
raise Impossible()
obj = self.node.as_const(eval_ctx)
# don't evaluate context functions
args = [x.as_const(eval_ctx) for x in self.args]
if isinstance(obj, _context_function_types):
if getattr(obj, 'contextfunction', False):
raise Impossible()
elif getattr(obj, 'evalcontextfunction', False):
args.insert(0, eval_ctx)
elif getattr(obj, 'environmentfunction', False):
args.insert(0, self.environment)
kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
if self.dyn_args is not None:
try:
args.extend(self.dyn_args.as_const(eval_ctx))
except:
raise Impossible()
if self.dyn_kwargs is not None:
try:
kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
except:
raise Impossible()
try:
return obj(*args, **kwargs)
except:
raise Impossible()
class Getitem(Expr):
"""Get an attribute or item from an expression and prefer the item."""
fields = ('node', 'arg', 'ctx')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if self.ctx != 'load':
raise Impossible()
try:
return self.environment.getitem(self.node.as_const(eval_ctx),
self.arg.as_const(eval_ctx))
except:
raise Impossible()
def can_assign(self):
return False
class Getattr(Expr):
"""Get an attribute or item from an expression that is a ascii-only
bytestring and prefer the attribute.
"""
fields = ('node', 'attr', 'ctx')
def as_const(self, eval_ctx=None):
if self.ctx != 'load':
raise Impossible()
try:
eval_ctx = get_eval_context(self, eval_ctx)
return self.environment.getattr(self.node.as_const(eval_ctx),
self.attr)
except:
raise Impossible()
def can_assign(self):
return False
class Slice(Expr):
"""Represents a slice object. This must only be used as argument for
:class:`Subscript`.
"""
fields = ('start', 'stop', 'step')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
def const(obj):
if obj is None:
return None
return obj.as_const(eval_ctx)
return slice(const(self.start), const(self.stop), const(self.step))
class Concat(Expr):
"""Concatenates the list of expressions provided after converting them to
unicode.
"""
fields = ('nodes',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return ''.join(unicode(x.as_const(eval_ctx)) for x in self.nodes)
class Compare(Expr):
"""Compares an expression with some other expressions. `ops` must be a
list of :class:`Operand`\s.
"""
fields = ('expr', 'ops')
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
result = value = self.expr.as_const(eval_ctx)
try:
for op in self.ops:
new_value = op.expr.as_const(eval_ctx)
result = _cmpop_to_func[op.op](value, new_value)
value = new_value
except:
raise Impossible()
return result
class Operand(Helper):
"""Holds an operator and an expression."""
fields = ('op', 'expr')
if __debug__:
Operand.__doc__ += '\nThe following operators are available: ' + \
', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
set(_uaop_to_func) | set(_cmpop_to_func)))
class Mul(BinExpr):
"""Multiplies the left with the right node."""
operator = '*'
class Div(BinExpr):
"""Divides the left by the right node."""
operator = '/'
class FloorDiv(BinExpr):
"""Divides the left by the right node and truncates conver the
result into an integer by truncating.
"""
operator = '//'
class Add(BinExpr):
"""Add the left to the right node."""
operator = '+'
class Sub(BinExpr):
"""Substract the right from the left node."""
operator = '-'
class Mod(BinExpr):
"""Left modulo right."""
operator = '%'
class Pow(BinExpr):
"""Left to the power of right."""
operator = '**'
class And(BinExpr):
"""Short circuited AND."""
operator = 'and'
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
class Or(BinExpr):
"""Short circuited OR."""
operator = 'or'
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
class Not(UnaryExpr):
"""Negate the expression."""
operator = 'not'
class Neg(UnaryExpr):
"""Make the expression negative."""
operator = '-'
class Pos(UnaryExpr):
"""Make the expression positive (noop for most expressions)"""
operator = '+'
# Helpers for extensions
class EnvironmentAttribute(Expr):
"""Loads an attribute from the environment object. This is useful for
extensions that want to call a callback stored on the environment.
"""
fields = ('name',)
class ExtensionAttribute(Expr):
"""Returns the attribute of an extension bound to the environment.
The identifier is the identifier of the :class:`Extension`.
This node is usually constructed by calling the
:meth:`~jinja2.ext.Extension.attr` method on an extension.
"""
fields = ('identifier', 'name')
class ImportedName(Expr):
"""If created with an import name the import name is returned on node
access. For example ``ImportedName('cgi.escape')`` returns the `escape`
function from the cgi module on evaluation. Imports are optimized by the
compiler so there is no need to assign them to local variables.
"""
fields = ('importname',)
class InternalName(Expr):
"""An internal name in the compiler. You cannot create these nodes
yourself but the parser provides a
:meth:`~jinja2.parser.Parser.free_identifier` method that creates
a new identifier for you. This identifier is not available from the
template and is not threated specially by the compiler.
"""
fields = ('name',)
def __init__(self):
raise TypeError('Can\'t create internal names. Use the '
'`free_identifier` method on a parser.')
class MarkSafe(Expr):
"""Mark the wrapped expression as safe (wrap it as `Markup`)."""
fields = ('expr',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
return Markup(self.expr.as_const(eval_ctx))
class MarkSafeIfAutoescape(Expr):
"""Mark the wrapped expression as safe (wrap it as `Markup`) but
only if autoescaping is active.
.. versionadded:: 2.5
"""
fields = ('expr',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if eval_ctx.volatile:
raise Impossible()
expr = self.expr.as_const(eval_ctx)
if eval_ctx.autoescape:
return Markup(expr)
return expr
class ContextReference(Expr):
"""Returns the current template context. It can be used like a
:class:`Name` node, with a ``'load'`` ctx and will return the
current :class:`~jinja2.runtime.Context` object.
Here an example that assigns the current template name to a
variable named `foo`::
Assign(Name('foo', ctx='store'),
Getattr(ContextReference(), 'name'))
"""
class Continue(Stmt):
"""Continue a loop."""
class Break(Stmt):
"""Break a loop."""
class Scope(Stmt):
"""An artificial scope."""
fields = ('body',)
class EvalContextModifier(Stmt):
"""Modifies the eval context. For each option that should be modified,
a :class:`Keyword` has to be added to the :attr:`options` list.
Example to change the `autoescape` setting::
EvalContextModifier(options=[Keyword('autoescape', Const(True))])
"""
fields = ('options',)
class ScopedEvalContextModifier(EvalContextModifier):
"""Modifies the eval context and reverts it later. Works exactly like
:class:`EvalContextModifier` but will only modify the
:class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.
"""
fields = ('body',)
# make sure nobody creates custom nodes
def _failing_new(*args, **kwargs):
raise TypeError('can\'t create custom node types')
NodeType.__new__ = staticmethod(_failing_new); del _failing_new
| [
[
8,
0,
0.0089,
0.0144,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0166,
0.0011,
0,
0.66,
0.0128,
616,
0,
1,
0,
0,
616,
0,
0
],
[
1,
0,
0.0178,
0.0011,
0,
0.66... | [
"\"\"\"\n jinja2.nodes\n ~~~~~~~~~~~~\n\n This module implements additional nodes derived from the ast base node.\n\n It also provides some node tree helper functions like `in_lineno` and\n `get_nodes` used by the parser and translator in order to normalize",
"import operator",
"from itertools im... |
# -*- coding: utf-8 -*-
"""
jinja2.compiler
~~~~~~~~~~~~~~~
Compiles nodes into python code.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
from cStringIO import StringIO
from itertools import chain
from copy import deepcopy
from jinja2 import nodes
from jinja2.nodes import EvalContext
from jinja2.visitor import NodeVisitor, NodeTransformer
from jinja2.exceptions import TemplateAssertionError
from jinja2.utils import Markup, concat, escape, is_python_keyword, next
operators = {
'eq': '==',
'ne': '!=',
'gt': '>',
'gteq': '>=',
'lt': '<',
'lteq': '<=',
'in': 'in',
'notin': 'not in'
}
try:
exec '(0 if 0 else 0)'
except SyntaxError:
have_condexpr = False
else:
have_condexpr = True
# what method to iterate over items do we want to use for dict iteration
# in generated code? on 2.x let's go with iteritems, on 3.x with items
if hasattr(dict, 'iteritems'):
dict_item_iter = 'iteritems'
else:
dict_item_iter = 'items'
# does if 0: dummy(x) get us x into the scope?
def unoptimize_before_dead_code():
x = 42
def f():
if 0: dummy(x)
return f
unoptimize_before_dead_code = bool(unoptimize_before_dead_code().func_closure)
def generate(node, environment, name, filename, stream=None,
defer_init=False):
"""Generate the python source for a node tree."""
if not isinstance(node, nodes.Template):
raise TypeError('Can\'t compile non template nodes')
generator = CodeGenerator(environment, name, filename, stream, defer_init)
generator.visit(node)
if stream is None:
return generator.stream.getvalue()
def has_safe_repr(value):
"""Does the node have a safe representation?"""
if value is None or value is NotImplemented or value is Ellipsis:
return True
if isinstance(value, (bool, int, long, float, complex, basestring,
xrange, Markup)):
return True
if isinstance(value, (tuple, list, set, frozenset)):
for item in value:
if not has_safe_repr(item):
return False
return True
elif isinstance(value, dict):
for key, value in value.iteritems():
if not has_safe_repr(key):
return False
if not has_safe_repr(value):
return False
return True
return False
def find_undeclared(nodes, names):
"""Check if the names passed are accessed undeclared. The return value
is a set of all the undeclared names from the sequence of names found.
"""
visitor = UndeclaredNameVisitor(names)
try:
for node in nodes:
visitor.visit(node)
except VisitorExit:
pass
return visitor.undeclared
class Identifiers(object):
"""Tracks the status of identifiers in frames."""
def __init__(self):
# variables that are known to be declared (probably from outer
# frames or because they are special for the frame)
self.declared = set()
# undeclared variables from outer scopes
self.outer_undeclared = set()
# names that are accessed without being explicitly declared by
# this one or any of the outer scopes. Names can appear both in
# declared and undeclared.
self.undeclared = set()
# names that are declared locally
self.declared_locally = set()
# names that are declared by parameters
self.declared_parameter = set()
def add_special(self, name):
"""Register a special name like `loop`."""
self.undeclared.discard(name)
self.declared.add(name)
def is_declared(self, name, local_only=False):
"""Check if a name is declared in this or an outer scope."""
if name in self.declared_locally or name in self.declared_parameter:
return True
if local_only:
return False
return name in self.declared
def copy(self):
return deepcopy(self)
class Frame(object):
"""Holds compile time information for us."""
def __init__(self, eval_ctx, parent=None):
self.eval_ctx = eval_ctx
self.identifiers = Identifiers()
# a toplevel frame is the root + soft frames such as if conditions.
self.toplevel = False
# the root frame is basically just the outermost frame, so no if
# conditions. This information is used to optimize inheritance
# situations.
self.rootlevel = False
# in some dynamic inheritance situations the compiler needs to add
# write tests around output statements.
self.require_output_check = parent and parent.require_output_check
# inside some tags we are using a buffer rather than yield statements.
# this for example affects {% filter %} or {% macro %}. If a frame
# is buffered this variable points to the name of the list used as
# buffer.
self.buffer = None
# the name of the block we're in, otherwise None.
self.block = parent and parent.block or None
# a set of actually assigned names
self.assigned_names = set()
# the parent of this frame
self.parent = parent
if parent is not None:
self.identifiers.declared.update(
parent.identifiers.declared |
parent.identifiers.declared_parameter |
parent.assigned_names
)
self.identifiers.outer_undeclared.update(
parent.identifiers.undeclared -
self.identifiers.declared
)
self.buffer = parent.buffer
def copy(self):
"""Create a copy of the current one."""
rv = object.__new__(self.__class__)
rv.__dict__.update(self.__dict__)
rv.identifiers = object.__new__(self.identifiers.__class__)
rv.identifiers.__dict__.update(self.identifiers.__dict__)
return rv
def inspect(self, nodes, hard_scope=False):
"""Walk the node and check for identifiers. If the scope is hard (eg:
enforce on a python level) overrides from outer scopes are tracked
differently.
"""
visitor = FrameIdentifierVisitor(self.identifiers, hard_scope)
for node in nodes:
visitor.visit(node)
def find_shadowed(self, extra=()):
"""Find all the shadowed names. extra is an iterable of variables
that may be defined with `add_special` which may occour scoped.
"""
i = self.identifiers
return (i.declared | i.outer_undeclared) & \
(i.declared_locally | i.declared_parameter) | \
set(x for x in extra if i.is_declared(x))
def inner(self):
"""Return an inner frame."""
return Frame(self.eval_ctx, self)
def soft(self):
"""Return a soft frame. A soft frame may not be modified as
standalone thing as it shares the resources with the frame it
was created of, but it's not a rootlevel frame any longer.
"""
rv = self.copy()
rv.rootlevel = False
return rv
__copy__ = copy
class VisitorExit(RuntimeError):
"""Exception used by the `UndeclaredNameVisitor` to signal a stop."""
class DependencyFinderVisitor(NodeVisitor):
"""A visitor that collects filter and test calls."""
def __init__(self):
self.filters = set()
self.tests = set()
def visit_Filter(self, node):
self.generic_visit(node)
self.filters.add(node.name)
def visit_Test(self, node):
self.generic_visit(node)
self.tests.add(node.name)
def visit_Block(self, node):
"""Stop visiting at blocks."""
class UndeclaredNameVisitor(NodeVisitor):
"""A visitor that checks if a name is accessed without being
declared. This is different from the frame visitor as it will
not stop at closure frames.
"""
def __init__(self, names):
self.names = set(names)
self.undeclared = set()
def visit_Name(self, node):
if node.ctx == 'load' and node.name in self.names:
self.undeclared.add(node.name)
if self.undeclared == self.names:
raise VisitorExit()
else:
self.names.discard(node.name)
def visit_Block(self, node):
"""Stop visiting a blocks."""
class FrameIdentifierVisitor(NodeVisitor):
"""A visitor for `Frame.inspect`."""
def __init__(self, identifiers, hard_scope):
self.identifiers = identifiers
self.hard_scope = hard_scope
def visit_Name(self, node):
"""All assignments to names go through this function."""
if node.ctx == 'store':
self.identifiers.declared_locally.add(node.name)
elif node.ctx == 'param':
self.identifiers.declared_parameter.add(node.name)
elif node.ctx == 'load' and not \
self.identifiers.is_declared(node.name, self.hard_scope):
self.identifiers.undeclared.add(node.name)
def visit_If(self, node):
self.visit(node.test)
real_identifiers = self.identifiers
old_names = real_identifiers.declared_locally | \
real_identifiers.declared_parameter
def inner_visit(nodes):
if not nodes:
return set()
self.identifiers = real_identifiers.copy()
for subnode in nodes:
self.visit(subnode)
rv = self.identifiers.declared_locally - old_names
# we have to remember the undeclared variables of this branch
# because we will have to pull them.
real_identifiers.undeclared.update(self.identifiers.undeclared)
self.identifiers = real_identifiers
return rv
body = inner_visit(node.body)
else_ = inner_visit(node.else_ or ())
# the differences between the two branches are also pulled as
# undeclared variables
real_identifiers.undeclared.update(body.symmetric_difference(else_) -
real_identifiers.declared)
# remember those that are declared.
real_identifiers.declared_locally.update(body | else_)
def visit_Macro(self, node):
self.identifiers.declared_locally.add(node.name)
def visit_Import(self, node):
self.generic_visit(node)
self.identifiers.declared_locally.add(node.target)
def visit_FromImport(self, node):
self.generic_visit(node)
for name in node.names:
if isinstance(name, tuple):
self.identifiers.declared_locally.add(name[1])
else:
self.identifiers.declared_locally.add(name)
def visit_Assign(self, node):
"""Visit assignments in the correct order."""
self.visit(node.node)
self.visit(node.target)
def visit_For(self, node):
"""Visiting stops at for blocks. However the block sequence
is visited as part of the outer scope.
"""
self.visit(node.iter)
def visit_CallBlock(self, node):
self.visit(node.call)
def visit_FilterBlock(self, node):
self.visit(node.filter)
def visit_Scope(self, node):
"""Stop visiting at scopes."""
def visit_Block(self, node):
"""Stop visiting at blocks."""
class CompilerExit(Exception):
"""Raised if the compiler encountered a situation where it just
doesn't make sense to further process the code. Any block that
raises such an exception is not further processed.
"""
class CodeGenerator(NodeVisitor):
def __init__(self, environment, name, filename, stream=None,
defer_init=False):
if stream is None:
stream = StringIO()
self.environment = environment
self.name = name
self.filename = filename
self.stream = stream
self.created_block_context = False
self.defer_init = defer_init
# aliases for imports
self.import_aliases = {}
# a registry for all blocks. Because blocks are moved out
# into the global python scope they are registered here
self.blocks = {}
# the number of extends statements so far
self.extends_so_far = 0
# some templates have a rootlevel extends. In this case we
# can safely assume that we're a child template and do some
# more optimizations.
self.has_known_extends = False
# the current line number
self.code_lineno = 1
# registry of all filters and tests (global, not block local)
self.tests = {}
self.filters = {}
# the debug information
self.debug_info = []
self._write_debug_info = None
# the number of new lines before the next write()
self._new_lines = 0
# the line number of the last written statement
self._last_line = 0
# true if nothing was written so far.
self._first_write = True
# used by the `temporary_identifier` method to get new
# unique, temporary identifier
self._last_identifier = 0
# the current indentation
self._indentation = 0
# -- Various compilation helpers
def fail(self, msg, lineno):
"""Fail with a :exc:`TemplateAssertionError`."""
raise TemplateAssertionError(msg, lineno, self.name, self.filename)
def temporary_identifier(self):
"""Get a new unique identifier."""
self._last_identifier += 1
return 't_%d' % self._last_identifier
def buffer(self, frame):
"""Enable buffering for the frame from that point onwards."""
frame.buffer = self.temporary_identifier()
self.writeline('%s = []' % frame.buffer)
def return_buffer_contents(self, frame):
"""Return the buffer contents of the frame."""
if frame.eval_ctx.volatile:
self.writeline('if context.eval_ctx.autoescape:')
self.indent()
self.writeline('return Markup(concat(%s))' % frame.buffer)
self.outdent()
self.writeline('else:')
self.indent()
self.writeline('return concat(%s)' % frame.buffer)
self.outdent()
elif frame.eval_ctx.autoescape:
self.writeline('return Markup(concat(%s))' % frame.buffer)
else:
self.writeline('return concat(%s)' % frame.buffer)
def indent(self):
"""Indent by one."""
self._indentation += 1
def outdent(self, step=1):
"""Outdent by step."""
self._indentation -= step
def start_write(self, frame, node=None):
"""Yield or write into the frame buffer."""
if frame.buffer is None:
self.writeline('yield ', node)
else:
self.writeline('%s.append(' % frame.buffer, node)
def end_write(self, frame):
"""End the writing process started by `start_write`."""
if frame.buffer is not None:
self.write(')')
def simple_write(self, s, frame, node=None):
"""Simple shortcut for start_write + write + end_write."""
self.start_write(frame, node)
self.write(s)
self.end_write(frame)
def blockvisit(self, nodes, frame):
"""Visit a list of nodes as block in a frame. If the current frame
is no buffer a dummy ``if 0: yield None`` is written automatically
unless the force_generator parameter is set to False.
"""
if frame.buffer is None:
self.writeline('if 0: yield None')
else:
self.writeline('pass')
try:
for node in nodes:
self.visit(node, frame)
except CompilerExit:
pass
def write(self, x):
"""Write a string into the output stream."""
if self._new_lines:
if not self._first_write:
self.stream.write('\n' * self._new_lines)
self.code_lineno += self._new_lines
if self._write_debug_info is not None:
self.debug_info.append((self._write_debug_info,
self.code_lineno))
self._write_debug_info = None
self._first_write = False
self.stream.write(' ' * self._indentation)
self._new_lines = 0
self.stream.write(x)
def writeline(self, x, node=None, extra=0):
"""Combination of newline and write."""
self.newline(node, extra)
self.write(x)
def newline(self, node=None, extra=0):
"""Add one or more newlines before the next write."""
self._new_lines = max(self._new_lines, 1 + extra)
if node is not None and node.lineno != self._last_line:
self._write_debug_info = node.lineno
self._last_line = node.lineno
def signature(self, node, frame, extra_kwargs=None):
"""Writes a function call to the stream for the current node.
A leading comma is added automatically. The extra keyword
arguments may not include python keywords otherwise a syntax
error could occour. The extra keyword arguments should be given
as python dict.
"""
# if any of the given keyword arguments is a python keyword
# we have to make sure that no invalid call is created.
kwarg_workaround = False
for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()):
if is_python_keyword(kwarg):
kwarg_workaround = True
break
for arg in node.args:
self.write(', ')
self.visit(arg, frame)
if not kwarg_workaround:
for kwarg in node.kwargs:
self.write(', ')
self.visit(kwarg, frame)
if extra_kwargs is not None:
for key, value in extra_kwargs.iteritems():
self.write(', %s=%s' % (key, value))
if node.dyn_args:
self.write(', *')
self.visit(node.dyn_args, frame)
if kwarg_workaround:
if node.dyn_kwargs is not None:
self.write(', **dict({')
else:
self.write(', **{')
for kwarg in node.kwargs:
self.write('%r: ' % kwarg.key)
self.visit(kwarg.value, frame)
self.write(', ')
if extra_kwargs is not None:
for key, value in extra_kwargs.iteritems():
self.write('%r: %s, ' % (key, value))
if node.dyn_kwargs is not None:
self.write('}, **')
self.visit(node.dyn_kwargs, frame)
self.write(')')
else:
self.write('}')
elif node.dyn_kwargs is not None:
self.write(', **')
self.visit(node.dyn_kwargs, frame)
def pull_locals(self, frame):
"""Pull all the references identifiers into the local scope."""
for name in frame.identifiers.undeclared:
self.writeline('l_%s = context.resolve(%r)' % (name, name))
def pull_dependencies(self, nodes):
"""Pull all the dependencies."""
visitor = DependencyFinderVisitor()
for node in nodes:
visitor.visit(node)
for dependency in 'filters', 'tests':
mapping = getattr(self, dependency)
for name in getattr(visitor, dependency):
if name not in mapping:
mapping[name] = self.temporary_identifier()
self.writeline('%s = environment.%s[%r]' %
(mapping[name], dependency, name))
def unoptimize_scope(self, frame):
"""Disable Python optimizations for the frame."""
# XXX: this is not that nice but it has no real overhead. It
# mainly works because python finds the locals before dead code
# is removed. If that breaks we have to add a dummy function
# that just accepts the arguments and does nothing.
if frame.identifiers.declared:
self.writeline('%sdummy(%s)' % (
unoptimize_before_dead_code and 'if 0: ' or '',
', '.join('l_' + name for name in frame.identifiers.declared)
))
def push_scope(self, frame, extra_vars=()):
"""This function returns all the shadowed variables in a dict
in the form name: alias and will write the required assignments
into the current scope. No indentation takes place.
This also predefines locally declared variables from the loop
body because under some circumstances it may be the case that
`extra_vars` is passed to `Frame.find_shadowed`.
"""
aliases = {}
for name in frame.find_shadowed(extra_vars):
aliases[name] = ident = self.temporary_identifier()
self.writeline('%s = l_%s' % (ident, name))
to_declare = set()
for name in frame.identifiers.declared_locally:
if name not in aliases:
to_declare.add('l_' + name)
if to_declare:
self.writeline(' = '.join(to_declare) + ' = missing')
return aliases
def pop_scope(self, aliases, frame):
"""Restore all aliases and delete unused variables."""
for name, alias in aliases.iteritems():
self.writeline('l_%s = %s' % (name, alias))
to_delete = set()
for name in frame.identifiers.declared_locally:
if name not in aliases:
to_delete.add('l_' + name)
if to_delete:
# we cannot use the del statement here because enclosed
# scopes can trigger a SyntaxError:
# a = 42; b = lambda: a; del a
self.writeline(' = '.join(to_delete) + ' = missing')
def function_scoping(self, node, frame, children=None,
find_special=True):
"""In Jinja a few statements require the help of anonymous
functions. Those are currently macros and call blocks and in
the future also recursive loops. As there is currently
technical limitation that doesn't allow reading and writing a
variable in a scope where the initial value is coming from an
outer scope, this function tries to fall back with a common
error message. Additionally the frame passed is modified so
that the argumetns are collected and callers are looked up.
This will return the modified frame.
"""
# we have to iterate twice over it, make sure that works
if children is None:
children = node.iter_child_nodes()
children = list(children)
func_frame = frame.inner()
func_frame.inspect(children, hard_scope=True)
# variables that are undeclared (accessed before declaration) and
# declared locally *and* part of an outside scope raise a template
# assertion error. Reason: we can't generate reasonable code from
# it without aliasing all the variables.
# this could be fixed in Python 3 where we have the nonlocal
# keyword or if we switch to bytecode generation
overriden_closure_vars = (
func_frame.identifiers.undeclared &
func_frame.identifiers.declared &
(func_frame.identifiers.declared_locally |
func_frame.identifiers.declared_parameter)
)
if overriden_closure_vars:
self.fail('It\'s not possible to set and access variables '
'derived from an outer scope! (affects: %s)' %
', '.join(sorted(overriden_closure_vars)), node.lineno)
# remove variables from a closure from the frame's undeclared
# identifiers.
func_frame.identifiers.undeclared -= (
func_frame.identifiers.undeclared &
func_frame.identifiers.declared
)
# no special variables for this scope, abort early
if not find_special:
return func_frame
func_frame.accesses_kwargs = False
func_frame.accesses_varargs = False
func_frame.accesses_caller = False
func_frame.arguments = args = ['l_' + x.name for x in node.args]
undeclared = find_undeclared(children, ('caller', 'kwargs', 'varargs'))
if 'caller' in undeclared:
func_frame.accesses_caller = True
func_frame.identifiers.add_special('caller')
args.append('l_caller')
if 'kwargs' in undeclared:
func_frame.accesses_kwargs = True
func_frame.identifiers.add_special('kwargs')
args.append('l_kwargs')
if 'varargs' in undeclared:
func_frame.accesses_varargs = True
func_frame.identifiers.add_special('varargs')
args.append('l_varargs')
return func_frame
def macro_body(self, node, frame, children=None):
"""Dump the function def of a macro or call block."""
frame = self.function_scoping(node, frame, children)
# macros are delayed, they never require output checks
frame.require_output_check = False
args = frame.arguments
# XXX: this is an ugly fix for the loop nesting bug
# (tests.test_old_bugs.test_loop_call_bug). This works around
# a identifier nesting problem we have in general. It's just more
# likely to happen in loops which is why we work around it. The
# real solution would be "nonlocal" all the identifiers that are
# leaking into a new python frame and might be used both unassigned
# and assigned.
if 'loop' in frame.identifiers.declared:
args = args + ['l_loop=l_loop']
self.writeline('def macro(%s):' % ', '.join(args), node)
self.indent()
self.buffer(frame)
self.pull_locals(frame)
self.blockvisit(node.body, frame)
self.return_buffer_contents(frame)
self.outdent()
return frame
def macro_def(self, node, frame):
"""Dump the macro definition for the def created by macro_body."""
arg_tuple = ', '.join(repr(x.name) for x in node.args)
name = getattr(node, 'name', None)
if len(node.args) == 1:
arg_tuple += ','
self.write('Macro(environment, macro, %r, (%s), (' %
(name, arg_tuple))
for arg in node.defaults:
self.visit(arg, frame)
self.write(', ')
self.write('), %r, %r, %r)' % (
bool(frame.accesses_kwargs),
bool(frame.accesses_varargs),
bool(frame.accesses_caller)
))
def position(self, node):
"""Return a human readable position for the node."""
rv = 'line %d' % node.lineno
if self.name is not None:
rv += ' in ' + repr(self.name)
return rv
# -- Statement Visitors
def visit_Template(self, node, frame=None):
assert frame is None, 'no root frame allowed'
eval_ctx = EvalContext(self.environment, self.name)
from jinja2.runtime import __all__ as exported
self.writeline('from __future__ import division')
self.writeline('from jinja2.runtime import ' + ', '.join(exported))
if not unoptimize_before_dead_code:
self.writeline('dummy = lambda *x: None')
# if we want a deferred initialization we cannot move the
# environment into a local name
envenv = not self.defer_init and ', environment=environment' or ''
# do we have an extends tag at all? If not, we can save some
# overhead by just not processing any inheritance code.
have_extends = node.find(nodes.Extends) is not None
# find all blocks
for block in node.find_all(nodes.Block):
if block.name in self.blocks:
self.fail('block %r defined twice' % block.name, block.lineno)
self.blocks[block.name] = block
# find all imports and import them
for import_ in node.find_all(nodes.ImportedName):
if import_.importname not in self.import_aliases:
imp = import_.importname
self.import_aliases[imp] = alias = self.temporary_identifier()
if '.' in imp:
module, obj = imp.rsplit('.', 1)
self.writeline('from %s import %s as %s' %
(module, obj, alias))
else:
self.writeline('import %s as %s' % (imp, alias))
# add the load name
self.writeline('name = %r' % self.name)
# generate the root render function.
self.writeline('def root(context%s):' % envenv, extra=1)
# process the root
frame = Frame(eval_ctx)
frame.inspect(node.body)
frame.toplevel = frame.rootlevel = True
frame.require_output_check = have_extends and not self.has_known_extends
self.indent()
if have_extends:
self.writeline('parent_template = None')
if 'self' in find_undeclared(node.body, ('self',)):
frame.identifiers.add_special('self')
self.writeline('l_self = TemplateReference(context)')
self.pull_locals(frame)
self.pull_dependencies(node.body)
self.blockvisit(node.body, frame)
self.outdent()
# make sure that the parent root is called.
if have_extends:
if not self.has_known_extends:
self.indent()
self.writeline('if parent_template is not None:')
self.indent()
self.writeline('for event in parent_template.'
'root_render_func(context):')
self.indent()
self.writeline('yield event')
self.outdent(2 + (not self.has_known_extends))
# at this point we now have the blocks collected and can visit them too.
for name, block in self.blocks.iteritems():
block_frame = Frame(eval_ctx)
block_frame.inspect(block.body)
block_frame.block = name
self.writeline('def block_%s(context%s):' % (name, envenv),
block, 1)
self.indent()
undeclared = find_undeclared(block.body, ('self', 'super'))
if 'self' in undeclared:
block_frame.identifiers.add_special('self')
self.writeline('l_self = TemplateReference(context)')
if 'super' in undeclared:
block_frame.identifiers.add_special('super')
self.writeline('l_super = context.super(%r, '
'block_%s)' % (name, name))
self.pull_locals(block_frame)
self.pull_dependencies(block.body)
self.blockvisit(block.body, block_frame)
self.outdent()
self.writeline('blocks = {%s}' % ', '.join('%r: block_%s' % (x, x)
for x in self.blocks),
extra=1)
# add a function that returns the debug info
self.writeline('debug_info = %r' % '&'.join('%s=%s' % x for x
in self.debug_info))
def visit_Block(self, node, frame):
"""Call a block and register it for the template."""
level = 1
if frame.toplevel:
# if we know that we are a child template, there is no need to
# check if we are one
if self.has_known_extends:
return
if self.extends_so_far > 0:
self.writeline('if parent_template is None:')
self.indent()
level += 1
context = node.scoped and 'context.derived(locals())' or 'context'
self.writeline('for event in context.blocks[%r][0](%s):' % (
node.name, context), node)
self.indent()
self.simple_write('event', frame)
self.outdent(level)
def visit_Extends(self, node, frame):
"""Calls the extender."""
if not frame.toplevel:
self.fail('cannot use extend from a non top-level scope',
node.lineno)
# if the number of extends statements in general is zero so
# far, we don't have to add a check if something extended
# the template before this one.
if self.extends_so_far > 0:
# if we have a known extends we just add a template runtime
# error into the generated code. We could catch that at compile
# time too, but i welcome it not to confuse users by throwing the
# same error at different times just "because we can".
if not self.has_known_extends:
self.writeline('if parent_template is not None:')
self.indent()
self.writeline('raise TemplateRuntimeError(%r)' %
'extended multiple times')
self.outdent()
# if we have a known extends already we don't need that code here
# as we know that the template execution will end here.
if self.has_known_extends:
raise CompilerExit()
self.writeline('parent_template = environment.get_template(', node)
self.visit(node.template, frame)
self.write(', %r)' % self.name)
self.writeline('for name, parent_block in parent_template.'
'blocks.%s():' % dict_item_iter)
self.indent()
self.writeline('context.blocks.setdefault(name, []).'
'append(parent_block)')
self.outdent()
# if this extends statement was in the root level we can take
# advantage of that information and simplify the generated code
# in the top level from this point onwards
if frame.rootlevel:
self.has_known_extends = True
# and now we have one more
self.extends_so_far += 1
def visit_Include(self, node, frame):
"""Handles includes."""
if node.with_context:
self.unoptimize_scope(frame)
if node.ignore_missing:
self.writeline('try:')
self.indent()
func_name = 'get_or_select_template'
if isinstance(node.template, nodes.Const):
if isinstance(node.template.value, basestring):
func_name = 'get_template'
elif isinstance(node.template.value, (tuple, list)):
func_name = 'select_template'
elif isinstance(node.template, (nodes.Tuple, nodes.List)):
func_name = 'select_template'
self.writeline('template = environment.%s(' % func_name, node)
self.visit(node.template, frame)
self.write(', %r)' % self.name)
if node.ignore_missing:
self.outdent()
self.writeline('except TemplateNotFound:')
self.indent()
self.writeline('pass')
self.outdent()
self.writeline('else:')
self.indent()
if node.with_context:
self.writeline('for event in template.root_render_func('
'template.new_context(context.parent, True, '
'locals())):')
else:
self.writeline('for event in template.module._body_stream:')
self.indent()
self.simple_write('event', frame)
self.outdent()
if node.ignore_missing:
self.outdent()
def visit_Import(self, node, frame):
"""Visit regular imports."""
if node.with_context:
self.unoptimize_scope(frame)
self.writeline('l_%s = ' % node.target, node)
if frame.toplevel:
self.write('context.vars[%r] = ' % node.target)
self.write('environment.get_template(')
self.visit(node.template, frame)
self.write(', %r).' % self.name)
if node.with_context:
self.write('make_module(context.parent, True, locals())')
else:
self.write('module')
if frame.toplevel and not node.target.startswith('_'):
self.writeline('context.exported_vars.discard(%r)' % node.target)
frame.assigned_names.add(node.target)
def visit_FromImport(self, node, frame):
"""Visit named imports."""
self.newline(node)
self.write('included_template = environment.get_template(')
self.visit(node.template, frame)
self.write(', %r).' % self.name)
if node.with_context:
self.write('make_module(context.parent, True)')
else:
self.write('module')
var_names = []
discarded_names = []
for name in node.names:
if isinstance(name, tuple):
name, alias = name
else:
alias = name
self.writeline('l_%s = getattr(included_template, '
'%r, missing)' % (alias, name))
self.writeline('if l_%s is missing:' % alias)
self.indent()
self.writeline('l_%s = environment.undefined(%r %% '
'included_template.__name__, '
'name=%r)' %
(alias, 'the template %%r (imported on %s) does '
'not export the requested name %s' % (
self.position(node),
repr(name)
), name))
self.outdent()
if frame.toplevel:
var_names.append(alias)
if not alias.startswith('_'):
discarded_names.append(alias)
frame.assigned_names.add(alias)
if var_names:
if len(var_names) == 1:
name = var_names[0]
self.writeline('context.vars[%r] = l_%s' % (name, name))
else:
self.writeline('context.vars.update({%s})' % ', '.join(
'%r: l_%s' % (name, name) for name in var_names
))
if discarded_names:
if len(discarded_names) == 1:
self.writeline('context.exported_vars.discard(%r)' %
discarded_names[0])
else:
self.writeline('context.exported_vars.difference_'
'update((%s))' % ', '.join(map(repr, discarded_names)))
def visit_For(self, node, frame):
# when calculating the nodes for the inner frame we have to exclude
# the iterator contents from it
children = node.iter_child_nodes(exclude=('iter',))
if node.recursive:
loop_frame = self.function_scoping(node, frame, children,
find_special=False)
else:
loop_frame = frame.inner()
loop_frame.inspect(children)
# try to figure out if we have an extended loop. An extended loop
# is necessary if the loop is in recursive mode if the special loop
# variable is accessed in the body.
extended_loop = node.recursive or 'loop' in \
find_undeclared(node.iter_child_nodes(
only=('body',)), ('loop',))
# if we don't have an recursive loop we have to find the shadowed
# variables at that point. Because loops can be nested but the loop
# variable is a special one we have to enforce aliasing for it.
if not node.recursive:
aliases = self.push_scope(loop_frame, ('loop',))
# otherwise we set up a buffer and add a function def
else:
self.writeline('def loop(reciter, loop_render_func):', node)
self.indent()
self.buffer(loop_frame)
aliases = {}
# make sure the loop variable is a special one and raise a template
# assertion error if a loop tries to write to loop
if extended_loop:
loop_frame.identifiers.add_special('loop')
for name in node.find_all(nodes.Name):
if name.ctx == 'store' and name.name == 'loop':
self.fail('Can\'t assign to special loop variable '
'in for-loop target', name.lineno)
self.pull_locals(loop_frame)
if node.else_:
iteration_indicator = self.temporary_identifier()
self.writeline('%s = 1' % iteration_indicator)
# Create a fake parent loop if the else or test section of a
# loop is accessing the special loop variable and no parent loop
# exists.
if 'loop' not in aliases and 'loop' in find_undeclared(
node.iter_child_nodes(only=('else_', 'test')), ('loop',)):
self.writeline("l_loop = environment.undefined(%r, name='loop')" %
("'loop' is undefined. the filter section of a loop as well "
"as the else block doesn't have access to the special 'loop'"
" variable of the current loop. Because there is no parent "
"loop it's undefined. Happened in loop on %s" %
self.position(node)))
self.writeline('for ', node)
self.visit(node.target, loop_frame)
self.write(extended_loop and ', l_loop in LoopContext(' or ' in ')
# if we have an extened loop and a node test, we filter in the
# "outer frame".
if extended_loop and node.test is not None:
self.write('(')
self.visit(node.target, loop_frame)
self.write(' for ')
self.visit(node.target, loop_frame)
self.write(' in ')
if node.recursive:
self.write('reciter')
else:
self.visit(node.iter, loop_frame)
self.write(' if (')
test_frame = loop_frame.copy()
self.visit(node.test, test_frame)
self.write('))')
elif node.recursive:
self.write('reciter')
else:
self.visit(node.iter, loop_frame)
if node.recursive:
self.write(', recurse=loop_render_func):')
else:
self.write(extended_loop and '):' or ':')
# tests in not extended loops become a continue
if not extended_loop and node.test is not None:
self.indent()
self.writeline('if not ')
self.visit(node.test, loop_frame)
self.write(':')
self.indent()
self.writeline('continue')
self.outdent(2)
self.indent()
self.blockvisit(node.body, loop_frame)
if node.else_:
self.writeline('%s = 0' % iteration_indicator)
self.outdent()
if node.else_:
self.writeline('if %s:' % iteration_indicator)
self.indent()
self.blockvisit(node.else_, loop_frame)
self.outdent()
# reset the aliases if there are any.
if not node.recursive:
self.pop_scope(aliases, loop_frame)
# if the node was recursive we have to return the buffer contents
# and start the iteration code
if node.recursive:
self.return_buffer_contents(loop_frame)
self.outdent()
self.start_write(frame, node)
self.write('loop(')
self.visit(node.iter, frame)
self.write(', loop)')
self.end_write(frame)
def visit_If(self, node, frame):
if_frame = frame.soft()
self.writeline('if ', node)
self.visit(node.test, if_frame)
self.write(':')
self.indent()
self.blockvisit(node.body, if_frame)
self.outdent()
if node.else_:
self.writeline('else:')
self.indent()
self.blockvisit(node.else_, if_frame)
self.outdent()
def visit_Macro(self, node, frame):
macro_frame = self.macro_body(node, frame)
self.newline()
if frame.toplevel:
if not node.name.startswith('_'):
self.write('context.exported_vars.add(%r)' % node.name)
self.writeline('context.vars[%r] = ' % node.name)
self.write('l_%s = ' % node.name)
self.macro_def(node, macro_frame)
frame.assigned_names.add(node.name)
def visit_CallBlock(self, node, frame):
children = node.iter_child_nodes(exclude=('call',))
call_frame = self.macro_body(node, frame, children)
self.writeline('caller = ')
self.macro_def(node, call_frame)
self.start_write(frame, node)
self.visit_Call(node.call, call_frame, forward_caller=True)
self.end_write(frame)
def visit_FilterBlock(self, node, frame):
filter_frame = frame.inner()
filter_frame.inspect(node.iter_child_nodes())
aliases = self.push_scope(filter_frame)
self.pull_locals(filter_frame)
self.buffer(filter_frame)
self.blockvisit(node.body, filter_frame)
self.start_write(frame, node)
self.visit_Filter(node.filter, filter_frame)
self.end_write(frame)
self.pop_scope(aliases, filter_frame)
def visit_ExprStmt(self, node, frame):
self.newline(node)
self.visit(node.node, frame)
def visit_Output(self, node, frame):
# if we have a known extends statement, we don't output anything
# if we are in a require_output_check section
if self.has_known_extends and frame.require_output_check:
return
if self.environment.finalize:
finalize = lambda x: unicode(self.environment.finalize(x))
else:
finalize = unicode
# if we are inside a frame that requires output checking, we do so
outdent_later = False
if frame.require_output_check:
self.writeline('if parent_template is None:')
self.indent()
outdent_later = True
# try to evaluate as many chunks as possible into a static
# string at compile time.
body = []
for child in node.nodes:
try:
const = child.as_const(frame.eval_ctx)
except nodes.Impossible:
body.append(child)
continue
# the frame can't be volatile here, becaus otherwise the
# as_const() function would raise an Impossible exception
# at that point.
try:
if frame.eval_ctx.autoescape:
if hasattr(const, '__html__'):
const = const.__html__()
else:
const = escape(const)
const = finalize(const)
except:
# if something goes wrong here we evaluate the node
# at runtime for easier debugging
body.append(child)
continue
if body and isinstance(body[-1], list):
body[-1].append(const)
else:
body.append([const])
# if we have less than 3 nodes or a buffer we yield or extend/append
if len(body) < 3 or frame.buffer is not None:
if frame.buffer is not None:
# for one item we append, for more we extend
if len(body) == 1:
self.writeline('%s.append(' % frame.buffer)
else:
self.writeline('%s.extend((' % frame.buffer)
self.indent()
for item in body:
if isinstance(item, list):
val = repr(concat(item))
if frame.buffer is None:
self.writeline('yield ' + val)
else:
self.writeline(val + ', ')
else:
if frame.buffer is None:
self.writeline('yield ', item)
else:
self.newline(item)
close = 1
if frame.eval_ctx.volatile:
self.write('(context.eval_ctx.autoescape and'
' escape or to_string)(')
elif frame.eval_ctx.autoescape:
self.write('escape(')
else:
self.write('to_string(')
if self.environment.finalize is not None:
self.write('environment.finalize(')
close += 1
self.visit(item, frame)
self.write(')' * close)
if frame.buffer is not None:
self.write(', ')
if frame.buffer is not None:
# close the open parentheses
self.outdent()
self.writeline(len(body) == 1 and ')' or '))')
# otherwise we create a format string as this is faster in that case
else:
format = []
arguments = []
for item in body:
if isinstance(item, list):
format.append(concat(item).replace('%', '%%'))
else:
format.append('%s')
arguments.append(item)
self.writeline('yield ')
self.write(repr(concat(format)) + ' % (')
idx = -1
self.indent()
for argument in arguments:
self.newline(argument)
close = 0
if frame.eval_ctx.volatile:
self.write('(context.eval_ctx.autoescape and'
' escape or to_string)(')
close += 1
elif frame.eval_ctx.autoescape:
self.write('escape(')
close += 1
if self.environment.finalize is not None:
self.write('environment.finalize(')
close += 1
self.visit(argument, frame)
self.write(')' * close + ', ')
self.outdent()
self.writeline(')')
if outdent_later:
self.outdent()
def visit_Assign(self, node, frame):
self.newline(node)
# toplevel assignments however go into the local namespace and
# the current template's context. We create a copy of the frame
# here and add a set so that the Name visitor can add the assigned
# names here.
if frame.toplevel:
assignment_frame = frame.copy()
assignment_frame.toplevel_assignments = set()
else:
assignment_frame = frame
self.visit(node.target, assignment_frame)
self.write(' = ')
self.visit(node.node, frame)
# make sure toplevel assignments are added to the context.
if frame.toplevel:
public_names = [x for x in assignment_frame.toplevel_assignments
if not x.startswith('_')]
if len(assignment_frame.toplevel_assignments) == 1:
name = next(iter(assignment_frame.toplevel_assignments))
self.writeline('context.vars[%r] = l_%s' % (name, name))
else:
self.writeline('context.vars.update({')
for idx, name in enumerate(assignment_frame.toplevel_assignments):
if idx:
self.write(', ')
self.write('%r: l_%s' % (name, name))
self.write('})')
if public_names:
if len(public_names) == 1:
self.writeline('context.exported_vars.add(%r)' %
public_names[0])
else:
self.writeline('context.exported_vars.update((%s))' %
', '.join(map(repr, public_names)))
# -- Expression Visitors
def visit_Name(self, node, frame):
if node.ctx == 'store' and frame.toplevel:
frame.toplevel_assignments.add(node.name)
self.write('l_' + node.name)
frame.assigned_names.add(node.name)
def visit_Const(self, node, frame):
val = node.value
if isinstance(val, float):
self.write(str(val))
else:
self.write(repr(val))
def visit_TemplateData(self, node, frame):
try:
self.write(repr(node.as_const(frame.eval_ctx)))
except nodes.Impossible:
self.write('(context.eval_ctx.autoescape and Markup or identity)(%r)'
% node.data)
def visit_Tuple(self, node, frame):
self.write('(')
idx = -1
for idx, item in enumerate(node.items):
if idx:
self.write(', ')
self.visit(item, frame)
self.write(idx == 0 and ',)' or ')')
def visit_List(self, node, frame):
self.write('[')
for idx, item in enumerate(node.items):
if idx:
self.write(', ')
self.visit(item, frame)
self.write(']')
def visit_Dict(self, node, frame):
self.write('{')
for idx, item in enumerate(node.items):
if idx:
self.write(', ')
self.visit(item.key, frame)
self.write(': ')
self.visit(item.value, frame)
self.write('}')
def binop(operator):
def visitor(self, node, frame):
self.write('(')
self.visit(node.left, frame)
self.write(' %s ' % operator)
self.visit(node.right, frame)
self.write(')')
return visitor
def uaop(operator):
def visitor(self, node, frame):
self.write('(' + operator)
self.visit(node.node, frame)
self.write(')')
return visitor
visit_Add = binop('+')
visit_Sub = binop('-')
visit_Mul = binop('*')
visit_Div = binop('/')
visit_FloorDiv = binop('//')
visit_Pow = binop('**')
visit_Mod = binop('%')
visit_And = binop('and')
visit_Or = binop('or')
visit_Pos = uaop('+')
visit_Neg = uaop('-')
visit_Not = uaop('not ')
del binop, uaop
def visit_Concat(self, node, frame):
if frame.eval_ctx.volatile:
func_name = '(context.eval_ctx.volatile and' \
' markup_join or unicode_join)'
elif frame.eval_ctx.autoescape:
func_name = 'markup_join'
else:
func_name = 'unicode_join'
self.write('%s((' % func_name)
for arg in node.nodes:
self.visit(arg, frame)
self.write(', ')
self.write('))')
def visit_Compare(self, node, frame):
self.visit(node.expr, frame)
for op in node.ops:
self.visit(op, frame)
def visit_Operand(self, node, frame):
self.write(' %s ' % operators[node.op])
self.visit(node.expr, frame)
def visit_Getattr(self, node, frame):
self.write('environment.getattr(')
self.visit(node.node, frame)
self.write(', %r)' % node.attr)
def visit_Getitem(self, node, frame):
# slices bypass the environment getitem method.
if isinstance(node.arg, nodes.Slice):
self.visit(node.node, frame)
self.write('[')
self.visit(node.arg, frame)
self.write(']')
else:
self.write('environment.getitem(')
self.visit(node.node, frame)
self.write(', ')
self.visit(node.arg, frame)
self.write(')')
def visit_Slice(self, node, frame):
if node.start is not None:
self.visit(node.start, frame)
self.write(':')
if node.stop is not None:
self.visit(node.stop, frame)
if node.step is not None:
self.write(':')
self.visit(node.step, frame)
def visit_Filter(self, node, frame):
self.write(self.filters[node.name] + '(')
func = self.environment.filters.get(node.name)
if func is None:
self.fail('no filter named %r' % node.name, node.lineno)
if getattr(func, 'contextfilter', False):
self.write('context, ')
elif getattr(func, 'evalcontextfilter', False):
self.write('context.eval_ctx, ')
elif getattr(func, 'environmentfilter', False):
self.write('environment, ')
# if the filter node is None we are inside a filter block
# and want to write to the current buffer
if node.node is not None:
self.visit(node.node, frame)
elif frame.eval_ctx.volatile:
self.write('(context.eval_ctx.autoescape and'
' Markup(concat(%s)) or concat(%s))' %
(frame.buffer, frame.buffer))
elif frame.eval_ctx.autoescape:
self.write('Markup(concat(%s))' % frame.buffer)
else:
self.write('concat(%s)' % frame.buffer)
self.signature(node, frame)
self.write(')')
def visit_Test(self, node, frame):
self.write(self.tests[node.name] + '(')
if node.name not in self.environment.tests:
self.fail('no test named %r' % node.name, node.lineno)
self.visit(node.node, frame)
self.signature(node, frame)
self.write(')')
def visit_CondExpr(self, node, frame):
def write_expr2():
if node.expr2 is not None:
return self.visit(node.expr2, frame)
self.write('environment.undefined(%r)' % ('the inline if-'
'expression on %s evaluated to false and '
'no else section was defined.' % self.position(node)))
if not have_condexpr:
self.write('((')
self.visit(node.test, frame)
self.write(') and (')
self.visit(node.expr1, frame)
self.write(',) or (')
write_expr2()
self.write(',))[0]')
else:
self.write('(')
self.visit(node.expr1, frame)
self.write(' if ')
self.visit(node.test, frame)
self.write(' else ')
write_expr2()
self.write(')')
def visit_Call(self, node, frame, forward_caller=False):
if self.environment.sandboxed:
self.write('environment.call(context, ')
else:
self.write('context.call(')
self.visit(node.node, frame)
extra_kwargs = forward_caller and {'caller': 'caller'} or None
self.signature(node, frame, extra_kwargs)
self.write(')')
def visit_Keyword(self, node, frame):
self.write(node.key + '=')
self.visit(node.value, frame)
# -- Unused nodes for extensions
def visit_MarkSafe(self, node, frame):
self.write('Markup(')
self.visit(node.expr, frame)
self.write(')')
def visit_MarkSafeIfAutoescape(self, node, frame):
self.write('(context.eval_ctx.autoescape and Markup or identity)(')
self.visit(node.expr, frame)
self.write(')')
def visit_EnvironmentAttribute(self, node, frame):
self.write('environment.' + node.name)
def visit_ExtensionAttribute(self, node, frame):
self.write('environment.extensions[%r].%s' % (node.identifier, node.name))
def visit_ImportedName(self, node, frame):
self.write(self.import_aliases[node.importname])
def visit_InternalName(self, node, frame):
self.write(node.name)
def visit_ContextReference(self, node, frame):
self.write('context')
def visit_Continue(self, node, frame):
self.writeline('continue', node)
def visit_Break(self, node, frame):
self.writeline('break', node)
def visit_Scope(self, node, frame):
scope_frame = frame.inner()
scope_frame.inspect(node.iter_child_nodes())
aliases = self.push_scope(scope_frame)
self.pull_locals(scope_frame)
self.blockvisit(node.body, scope_frame)
self.pop_scope(aliases, scope_frame)
def visit_EvalContextModifier(self, node, frame):
for keyword in node.options:
self.writeline('context.eval_ctx.%s = ' % keyword.key)
self.visit(keyword.value, frame)
try:
val = keyword.value.as_const(frame.eval_ctx)
except nodes.Impossible:
frame.eval_ctx.volatile = True
else:
setattr(frame.eval_ctx, keyword.key, val)
def visit_ScopedEvalContextModifier(self, node, frame):
old_ctx_name = self.temporary_identifier()
safed_ctx = frame.eval_ctx.save()
self.writeline('%s = context.eval_ctx.save()' % old_ctx_name)
self.visit_EvalContextModifier(node, frame)
for child in node.body:
self.visit(child, frame)
frame.eval_ctx.revert(safed_ctx)
self.writeline('context.eval_ctx.revert(%s)' % old_ctx_name)
| [
[
8,
0,
0.0037,
0.0055,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0067,
0.0006,
0,
0.66,
0.0417,
764,
0,
1,
0,
0,
764,
0,
0
],
[
1,
0,
0.0073,
0.0006,
0,
0.66... | [
"\"\"\"\n jinja2.compiler\n ~~~~~~~~~~~~~~~\n\n Compiles nodes into python code.\n\n :copyright: (c) 2010 by the Jinja Team.\n :license: BSD, see LICENSE for more details.",
"from cStringIO import StringIO",
"from itertools import chain",
"from copy import deepcopy",
"from jinja2 import nodes... |
# -*- coding: utf-8 -*-
"""
jinja2.optimizer
~~~~~~~~~~~~~~~~
The jinja optimizer is currently trying to constant fold a few expressions
and modify the AST in place so that it should be easier to evaluate it.
Because the AST does not contain all the scoping information and the
compiler has to find that out, we cannot do all the optimizations we
want. For example loop unrolling doesn't work because unrolled loops would
have a different scoping.
The solution would be a second syntax tree that has the scoping rules stored.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD.
"""
from jinja2 import nodes
from jinja2.visitor import NodeTransformer
def optimize(node, environment):
"""The context hint can be used to perform an static optimization
based on the context given."""
optimizer = Optimizer(environment)
return optimizer.visit(node)
class Optimizer(NodeTransformer):
def __init__(self, environment):
self.environment = environment
def visit_If(self, node):
"""Eliminate dead code."""
# do not optimize ifs that have a block inside so that it doesn't
# break super().
if node.find(nodes.Block) is not None:
return self.generic_visit(node)
try:
val = self.visit(node.test).as_const()
except nodes.Impossible:
return self.generic_visit(node)
if val:
body = node.body
else:
body = node.else_
result = []
for node in body:
result.extend(self.visit_list(node))
return result
def fold(self, node):
"""Do constant folding."""
node = self.generic_visit(node)
try:
return nodes.Const.from_untrusted(node.as_const(),
lineno=node.lineno,
environment=self.environment)
except nodes.Impossible:
return node
visit_Add = visit_Sub = visit_Mul = visit_Div = visit_FloorDiv = \
visit_Pow = visit_Mod = visit_And = visit_Or = visit_Pos = visit_Neg = \
visit_Not = visit_Compare = visit_Getitem = visit_Getattr = visit_Call = \
visit_Filter = visit_Test = visit_CondExpr = fold
del fold
| [
[
8,
0,
0.1471,
0.25,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2794,
0.0147,
0,
0.66,
0.25,
436,
0,
1,
0,
0,
436,
0,
0
],
[
1,
0,
0.2941,
0.0147,
0,
0.66,
... | [
"\"\"\"\n jinja2.optimizer\n ~~~~~~~~~~~~~~~~\n\n The jinja optimizer is currently trying to constant fold a few expressions\n and modify the AST in place so that it should be easier to evaluate it.\n\n Because the AST does not contain all the scoping information and the",
"from jinja2 import nodes... |
# -*- coding: utf-8 -*-
"""
jinja2.visitor
~~~~~~~~~~~~~~
This module implements a visitor for the nodes.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD.
"""
from jinja2.nodes import Node
class NodeVisitor(object):
"""Walks the abstract syntax tree and call visitor functions for every
node found. The visitor functions may return values which will be
forwarded by the `visit` method.
Per default the visitor functions for the nodes are ``'visit_'`` +
class name of the node. So a `TryFinally` node visit function would
be `visit_TryFinally`. This behavior can be changed by overriding
the `get_visitor` function. If no visitor function exists for a node
(return value `None`) the `generic_visit` visitor is used instead.
"""
def get_visitor(self, node):
"""Return the visitor function for this node or `None` if no visitor
exists for this node. In that case the generic visit function is
used instead.
"""
method = 'visit_' + node.__class__.__name__
return getattr(self, method, None)
def visit(self, node, *args, **kwargs):
"""Visit a node."""
f = self.get_visitor(node)
if f is not None:
return f(node, *args, **kwargs)
return self.generic_visit(node, *args, **kwargs)
def generic_visit(self, node, *args, **kwargs):
"""Called if no explicit visitor function exists for a node."""
for node in node.iter_child_nodes():
self.visit(node, *args, **kwargs)
class NodeTransformer(NodeVisitor):
"""Walks the abstract syntax tree and allows modifications of nodes.
The `NodeTransformer` will walk the AST and use the return value of the
visitor functions to replace or remove the old node. If the return
value of the visitor function is `None` the node will be removed
from the previous location otherwise it's replaced with the return
value. The return value may be the original node in which case no
replacement takes place.
"""
def generic_visit(self, node, *args, **kwargs):
for field, old_value in node.iter_fields():
if isinstance(old_value, list):
new_values = []
for value in old_value:
if isinstance(value, Node):
value = self.visit(value, *args, **kwargs)
if value is None:
continue
elif not isinstance(value, Node):
new_values.extend(value)
continue
new_values.append(value)
old_value[:] = new_values
elif isinstance(old_value, Node):
new_node = self.visit(old_value, *args, **kwargs)
if new_node is None:
delattr(node, field)
else:
setattr(node, field, new_node)
return node
def visit_list(self, node, *args, **kwargs):
"""As transformers may return lists in some places this method
can be used to enforce a list as return value.
"""
rv = self.visit(node, *args, **kwargs)
if not isinstance(rv, list):
rv = [rv]
return rv
| [
[
8,
0,
0.069,
0.1034,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1264,
0.0115,
0,
0.66,
0.3333,
990,
0,
1,
0,
0,
990,
0,
0
],
[
3,
0,
0.3333,
0.3563,
0,
0.66,... | [
"\"\"\"\n jinja2.visitor\n ~~~~~~~~~~~~~~\n\n This module implements a visitor for the nodes.\n\n :copyright: (c) 2010 by the Jinja Team.\n :license: BSD.",
"from jinja2.nodes import Node",
"class NodeVisitor(object):\n \"\"\"Walks the abstract syntax tree and call visitor functions for every\... |
# -*- coding: utf-8 -*-
"""
jinja2.parser
~~~~~~~~~~~~~
Implements the template parser.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
from jinja2 import nodes
from jinja2.exceptions import TemplateSyntaxError, TemplateAssertionError
from jinja2.utils import next
from jinja2.lexer import describe_token, describe_token_expr
#: statements that callinto
_statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'print',
'macro', 'include', 'from', 'import',
'set'])
_compare_operators = frozenset(['eq', 'ne', 'lt', 'lteq', 'gt', 'gteq'])
class Parser(object):
"""This is the central parsing class Jinja2 uses. It's passed to
extensions and can be used to parse expressions or statements.
"""
def __init__(self, environment, source, name=None, filename=None,
state=None):
self.environment = environment
self.stream = environment._tokenize(source, name, filename, state)
self.name = name
self.filename = filename
self.closed = False
self.extensions = {}
for extension in environment.iter_extensions():
for tag in extension.tags:
self.extensions[tag] = extension.parse
self._last_identifier = 0
self._tag_stack = []
self._end_token_stack = []
def fail(self, msg, lineno=None, exc=TemplateSyntaxError):
"""Convenience method that raises `exc` with the message, passed
line number or last line number as well as the current name and
filename.
"""
if lineno is None:
lineno = self.stream.current.lineno
raise exc(msg, lineno, self.name, self.filename)
def _fail_ut_eof(self, name, end_token_stack, lineno):
expected = []
for exprs in end_token_stack:
expected.extend(map(describe_token_expr, exprs))
if end_token_stack:
currently_looking = ' or '.join(
"'%s'" % describe_token_expr(expr)
for expr in end_token_stack[-1])
else:
currently_looking = None
if name is None:
message = ['Unexpected end of template.']
else:
message = ['Encountered unknown tag \'%s\'.' % name]
if currently_looking:
if name is not None and name in expected:
message.append('You probably made a nesting mistake. Jinja '
'is expecting this tag, but currently looking '
'for %s.' % currently_looking)
else:
message.append('Jinja was looking for the following tags: '
'%s.' % currently_looking)
if self._tag_stack:
message.append('The innermost block that needs to be '
'closed is \'%s\'.' % self._tag_stack[-1])
self.fail(' '.join(message), lineno)
def fail_unknown_tag(self, name, lineno=None):
"""Called if the parser encounters an unknown tag. Tries to fail
with a human readable error message that could help to identify
the problem.
"""
return self._fail_ut_eof(name, self._end_token_stack, lineno)
def fail_eof(self, end_tokens=None, lineno=None):
"""Like fail_unknown_tag but for end of template situations."""
stack = list(self._end_token_stack)
if end_tokens is not None:
stack.append(end_tokens)
return self._fail_ut_eof(None, stack, lineno)
def is_tuple_end(self, extra_end_rules=None):
"""Are we at the end of a tuple?"""
if self.stream.current.type in ('variable_end', 'block_end', 'rparen'):
return True
elif extra_end_rules is not None:
return self.stream.current.test_any(extra_end_rules)
return False
def free_identifier(self, lineno=None):
"""Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""
self._last_identifier += 1
rv = object.__new__(nodes.InternalName)
nodes.Node.__init__(rv, 'fi%d' % self._last_identifier, lineno=lineno)
return rv
def parse_statement(self):
"""Parse a single statement."""
token = self.stream.current
if token.type != 'name':
self.fail('tag name expected', token.lineno)
self._tag_stack.append(token.value)
pop_tag = True
try:
if token.value in _statement_keywords:
return getattr(self, 'parse_' + self.stream.current.value)()
if token.value == 'call':
return self.parse_call_block()
if token.value == 'filter':
return self.parse_filter_block()
ext = self.extensions.get(token.value)
if ext is not None:
return ext(self)
# did not work out, remove the token we pushed by accident
# from the stack so that the unknown tag fail function can
# produce a proper error message.
self._tag_stack.pop()
pop_tag = False
self.fail_unknown_tag(token.value, token.lineno)
finally:
if pop_tag:
self._tag_stack.pop()
def parse_statements(self, end_tokens, drop_needle=False):
"""Parse multiple statements into a list until one of the end tokens
is reached. This is used to parse the body of statements as it also
parses template data if appropriate. The parser checks first if the
current token is a colon and skips it if there is one. Then it checks
for the block end and parses until if one of the `end_tokens` is
reached. Per default the active token in the stream at the end of
the call is the matched end token. If this is not wanted `drop_needle`
can be set to `True` and the end token is removed.
"""
# the first token may be a colon for python compatibility
self.stream.skip_if('colon')
# in the future it would be possible to add whole code sections
# by adding some sort of end of statement token and parsing those here.
self.stream.expect('block_end')
result = self.subparse(end_tokens)
# we reached the end of the template too early, the subparser
# does not check for this, so we do that now
if self.stream.current.type == 'eof':
self.fail_eof(end_tokens)
if drop_needle:
next(self.stream)
return result
def parse_set(self):
"""Parse an assign statement."""
lineno = next(self.stream).lineno
target = self.parse_assign_target()
self.stream.expect('assign')
expr = self.parse_tuple()
return nodes.Assign(target, expr, lineno=lineno)
def parse_for(self):
"""Parse a for loop."""
lineno = self.stream.expect('name:for').lineno
target = self.parse_assign_target(extra_end_rules=('name:in',))
self.stream.expect('name:in')
iter = self.parse_tuple(with_condexpr=False,
extra_end_rules=('name:recursive',))
test = None
if self.stream.skip_if('name:if'):
test = self.parse_expression()
recursive = self.stream.skip_if('name:recursive')
body = self.parse_statements(('name:endfor', 'name:else'))
if next(self.stream).value == 'endfor':
else_ = []
else:
else_ = self.parse_statements(('name:endfor',), drop_needle=True)
return nodes.For(target, iter, body, else_, test,
recursive, lineno=lineno)
def parse_if(self):
"""Parse an if construct."""
node = result = nodes.If(lineno=self.stream.expect('name:if').lineno)
while 1:
node.test = self.parse_tuple(with_condexpr=False)
node.body = self.parse_statements(('name:elif', 'name:else',
'name:endif'))
token = next(self.stream)
if token.test('name:elif'):
new_node = nodes.If(lineno=self.stream.current.lineno)
node.else_ = [new_node]
node = new_node
continue
elif token.test('name:else'):
node.else_ = self.parse_statements(('name:endif',),
drop_needle=True)
else:
node.else_ = []
break
return result
def parse_block(self):
node = nodes.Block(lineno=next(self.stream).lineno)
node.name = self.stream.expect('name').value
node.scoped = self.stream.skip_if('name:scoped')
# common problem people encounter when switching from django
# to jinja. we do not support hyphens in block names, so let's
# raise a nicer error message in that case.
if self.stream.current.type == 'sub':
self.fail('Block names in Jinja have to be valid Python '
'identifiers and may not contain hypens, use an '
'underscore instead.')
node.body = self.parse_statements(('name:endblock',), drop_needle=True)
self.stream.skip_if('name:' + node.name)
return node
def parse_extends(self):
node = nodes.Extends(lineno=next(self.stream).lineno)
node.template = self.parse_expression()
return node
def parse_import_context(self, node, default):
if self.stream.current.test_any('name:with', 'name:without') and \
self.stream.look().test('name:context'):
node.with_context = next(self.stream).value == 'with'
self.stream.skip()
else:
node.with_context = default
return node
def parse_include(self):
node = nodes.Include(lineno=next(self.stream).lineno)
node.template = self.parse_expression()
if self.stream.current.test('name:ignore') and \
self.stream.look().test('name:missing'):
node.ignore_missing = True
self.stream.skip(2)
else:
node.ignore_missing = False
return self.parse_import_context(node, True)
def parse_import(self):
node = nodes.Import(lineno=next(self.stream).lineno)
node.template = self.parse_expression()
self.stream.expect('name:as')
node.target = self.parse_assign_target(name_only=True).name
return self.parse_import_context(node, False)
def parse_from(self):
node = nodes.FromImport(lineno=next(self.stream).lineno)
node.template = self.parse_expression()
self.stream.expect('name:import')
node.names = []
def parse_context():
if self.stream.current.value in ('with', 'without') and \
self.stream.look().test('name:context'):
node.with_context = next(self.stream).value == 'with'
self.stream.skip()
return True
return False
while 1:
if node.names:
self.stream.expect('comma')
if self.stream.current.type == 'name':
if parse_context():
break
target = self.parse_assign_target(name_only=True)
if target.name.startswith('_'):
self.fail('names starting with an underline can not '
'be imported', target.lineno,
exc=TemplateAssertionError)
if self.stream.skip_if('name:as'):
alias = self.parse_assign_target(name_only=True)
node.names.append((target.name, alias.name))
else:
node.names.append(target.name)
if parse_context() or self.stream.current.type != 'comma':
break
else:
break
if not hasattr(node, 'with_context'):
node.with_context = False
self.stream.skip_if('comma')
return node
def parse_signature(self, node):
node.args = args = []
node.defaults = defaults = []
self.stream.expect('lparen')
while self.stream.current.type != 'rparen':
if args:
self.stream.expect('comma')
arg = self.parse_assign_target(name_only=True)
arg.set_ctx('param')
if self.stream.skip_if('assign'):
defaults.append(self.parse_expression())
args.append(arg)
self.stream.expect('rparen')
def parse_call_block(self):
node = nodes.CallBlock(lineno=next(self.stream).lineno)
if self.stream.current.type == 'lparen':
self.parse_signature(node)
else:
node.args = []
node.defaults = []
node.call = self.parse_expression()
if not isinstance(node.call, nodes.Call):
self.fail('expected call', node.lineno)
node.body = self.parse_statements(('name:endcall',), drop_needle=True)
return node
def parse_filter_block(self):
node = nodes.FilterBlock(lineno=next(self.stream).lineno)
node.filter = self.parse_filter(None, start_inline=True)
node.body = self.parse_statements(('name:endfilter',),
drop_needle=True)
return node
def parse_macro(self):
node = nodes.Macro(lineno=next(self.stream).lineno)
node.name = self.parse_assign_target(name_only=True).name
self.parse_signature(node)
node.body = self.parse_statements(('name:endmacro',),
drop_needle=True)
return node
def parse_print(self):
node = nodes.Output(lineno=next(self.stream).lineno)
node.nodes = []
while self.stream.current.type != 'block_end':
if node.nodes:
self.stream.expect('comma')
node.nodes.append(self.parse_expression())
return node
def parse_assign_target(self, with_tuple=True, name_only=False,
extra_end_rules=None):
"""Parse an assignment target. As Jinja2 allows assignments to
tuples, this function can parse all allowed assignment targets. Per
default assignments to tuples are parsed, that can be disable however
by setting `with_tuple` to `False`. If only assignments to names are
wanted `name_only` can be set to `True`. The `extra_end_rules`
parameter is forwarded to the tuple parsing function.
"""
if name_only:
token = self.stream.expect('name')
target = nodes.Name(token.value, 'store', lineno=token.lineno)
else:
if with_tuple:
target = self.parse_tuple(simplified=True,
extra_end_rules=extra_end_rules)
else:
target = self.parse_primary()
target.set_ctx('store')
if not target.can_assign():
self.fail('can\'t assign to %r' % target.__class__.
__name__.lower(), target.lineno)
return target
def parse_expression(self, with_condexpr=True):
"""Parse an expression. Per default all expressions are parsed, if
the optional `with_condexpr` parameter is set to `False` conditional
expressions are not parsed.
"""
if with_condexpr:
return self.parse_condexpr()
return self.parse_or()
def parse_condexpr(self):
lineno = self.stream.current.lineno
expr1 = self.parse_or()
while self.stream.skip_if('name:if'):
expr2 = self.parse_or()
if self.stream.skip_if('name:else'):
expr3 = self.parse_condexpr()
else:
expr3 = None
expr1 = nodes.CondExpr(expr2, expr1, expr3, lineno=lineno)
lineno = self.stream.current.lineno
return expr1
def parse_or(self):
lineno = self.stream.current.lineno
left = self.parse_and()
while self.stream.skip_if('name:or'):
right = self.parse_and()
left = nodes.Or(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_and(self):
lineno = self.stream.current.lineno
left = self.parse_not()
while self.stream.skip_if('name:and'):
right = self.parse_not()
left = nodes.And(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_not(self):
if self.stream.current.test('name:not'):
lineno = next(self.stream).lineno
return nodes.Not(self.parse_not(), lineno=lineno)
return self.parse_compare()
def parse_compare(self):
lineno = self.stream.current.lineno
expr = self.parse_add()
ops = []
while 1:
token_type = self.stream.current.type
if token_type in _compare_operators:
next(self.stream)
ops.append(nodes.Operand(token_type, self.parse_add()))
elif self.stream.skip_if('name:in'):
ops.append(nodes.Operand('in', self.parse_add()))
elif self.stream.current.test('name:not') and \
self.stream.look().test('name:in'):
self.stream.skip(2)
ops.append(nodes.Operand('notin', self.parse_add()))
else:
break
lineno = self.stream.current.lineno
if not ops:
return expr
return nodes.Compare(expr, ops, lineno=lineno)
def parse_add(self):
lineno = self.stream.current.lineno
left = self.parse_sub()
while self.stream.current.type == 'add':
next(self.stream)
right = self.parse_sub()
left = nodes.Add(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_sub(self):
lineno = self.stream.current.lineno
left = self.parse_concat()
while self.stream.current.type == 'sub':
next(self.stream)
right = self.parse_concat()
left = nodes.Sub(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_concat(self):
lineno = self.stream.current.lineno
args = [self.parse_mul()]
while self.stream.current.type == 'tilde':
next(self.stream)
args.append(self.parse_mul())
if len(args) == 1:
return args[0]
return nodes.Concat(args, lineno=lineno)
def parse_mul(self):
lineno = self.stream.current.lineno
left = self.parse_div()
while self.stream.current.type == 'mul':
next(self.stream)
right = self.parse_div()
left = nodes.Mul(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_div(self):
lineno = self.stream.current.lineno
left = self.parse_floordiv()
while self.stream.current.type == 'div':
next(self.stream)
right = self.parse_floordiv()
left = nodes.Div(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_floordiv(self):
lineno = self.stream.current.lineno
left = self.parse_mod()
while self.stream.current.type == 'floordiv':
next(self.stream)
right = self.parse_mod()
left = nodes.FloorDiv(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_mod(self):
lineno = self.stream.current.lineno
left = self.parse_pow()
while self.stream.current.type == 'mod':
next(self.stream)
right = self.parse_pow()
left = nodes.Mod(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_pow(self):
lineno = self.stream.current.lineno
left = self.parse_unary()
while self.stream.current.type == 'pow':
next(self.stream)
right = self.parse_unary()
left = nodes.Pow(left, right, lineno=lineno)
lineno = self.stream.current.lineno
return left
def parse_unary(self, with_filter=True):
token_type = self.stream.current.type
lineno = self.stream.current.lineno
if token_type == 'sub':
next(self.stream)
node = nodes.Neg(self.parse_unary(False), lineno=lineno)
elif token_type == 'add':
next(self.stream)
node = nodes.Pos(self.parse_unary(False), lineno=lineno)
else:
node = self.parse_primary()
node = self.parse_postfix(node)
if with_filter:
node = self.parse_filter_expr(node)
return node
def parse_primary(self):
token = self.stream.current
if token.type == 'name':
if token.value in ('true', 'false', 'True', 'False'):
node = nodes.Const(token.value in ('true', 'True'),
lineno=token.lineno)
elif token.value in ('none', 'None'):
node = nodes.Const(None, lineno=token.lineno)
else:
node = nodes.Name(token.value, 'load', lineno=token.lineno)
next(self.stream)
elif token.type == 'string':
next(self.stream)
buf = [token.value]
lineno = token.lineno
while self.stream.current.type == 'string':
buf.append(self.stream.current.value)
next(self.stream)
node = nodes.Const(''.join(buf), lineno=lineno)
elif token.type in ('integer', 'float'):
next(self.stream)
node = nodes.Const(token.value, lineno=token.lineno)
elif token.type == 'lparen':
next(self.stream)
node = self.parse_tuple(explicit_parentheses=True)
self.stream.expect('rparen')
elif token.type == 'lbracket':
node = self.parse_list()
elif token.type == 'lbrace':
node = self.parse_dict()
else:
self.fail("unexpected '%s'" % describe_token(token), token.lineno)
return node
def parse_tuple(self, simplified=False, with_condexpr=True,
extra_end_rules=None, explicit_parentheses=False):
"""Works like `parse_expression` but if multiple expressions are
delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.
This method could also return a regular expression instead of a tuple
if no commas where found.
The default parsing mode is a full tuple. If `simplified` is `True`
only names and literals are parsed. The `no_condexpr` parameter is
forwarded to :meth:`parse_expression`.
Because tuples do not require delimiters and may end in a bogus comma
an extra hint is needed that marks the end of a tuple. For example
for loops support tuples between `for` and `in`. In that case the
`extra_end_rules` is set to ``['name:in']``.
`explicit_parentheses` is true if the parsing was triggered by an
expression in parentheses. This is used to figure out if an empty
tuple is a valid expression or not.
"""
lineno = self.stream.current.lineno
if simplified:
parse = self.parse_primary
elif with_condexpr:
parse = self.parse_expression
else:
parse = lambda: self.parse_expression(with_condexpr=False)
args = []
is_tuple = False
while 1:
if args:
self.stream.expect('comma')
if self.is_tuple_end(extra_end_rules):
break
args.append(parse())
if self.stream.current.type == 'comma':
is_tuple = True
else:
break
lineno = self.stream.current.lineno
if not is_tuple:
if args:
return args[0]
# if we don't have explicit parentheses, an empty tuple is
# not a valid expression. This would mean nothing (literally
# nothing) in the spot of an expression would be an empty
# tuple.
if not explicit_parentheses:
self.fail('Expected an expression, got \'%s\'' %
describe_token(self.stream.current))
return nodes.Tuple(args, 'load', lineno=lineno)
def parse_list(self):
token = self.stream.expect('lbracket')
items = []
while self.stream.current.type != 'rbracket':
if items:
self.stream.expect('comma')
if self.stream.current.type == 'rbracket':
break
items.append(self.parse_expression())
self.stream.expect('rbracket')
return nodes.List(items, lineno=token.lineno)
def parse_dict(self):
token = self.stream.expect('lbrace')
items = []
while self.stream.current.type != 'rbrace':
if items:
self.stream.expect('comma')
if self.stream.current.type == 'rbrace':
break
key = self.parse_expression()
self.stream.expect('colon')
value = self.parse_expression()
items.append(nodes.Pair(key, value, lineno=key.lineno))
self.stream.expect('rbrace')
return nodes.Dict(items, lineno=token.lineno)
def parse_postfix(self, node):
while 1:
token_type = self.stream.current.type
if token_type == 'dot' or token_type == 'lbracket':
node = self.parse_subscript(node)
# calls are valid both after postfix expressions (getattr
# and getitem) as well as filters and tests
elif token_type == 'lparen':
node = self.parse_call(node)
else:
break
return node
def parse_filter_expr(self, node):
while 1:
token_type = self.stream.current.type
if token_type == 'pipe':
node = self.parse_filter(node)
elif token_type == 'name' and self.stream.current.value == 'is':
node = self.parse_test(node)
# calls are valid both after postfix expressions (getattr
# and getitem) as well as filters and tests
elif token_type == 'lparen':
node = self.parse_call(node)
else:
break
return node
def parse_subscript(self, node):
token = next(self.stream)
if token.type == 'dot':
attr_token = self.stream.current
next(self.stream)
if attr_token.type == 'name':
return nodes.Getattr(node, attr_token.value, 'load',
lineno=token.lineno)
elif attr_token.type != 'integer':
self.fail('expected name or number', attr_token.lineno)
arg = nodes.Const(attr_token.value, lineno=attr_token.lineno)
return nodes.Getitem(node, arg, 'load', lineno=token.lineno)
if token.type == 'lbracket':
priority_on_attribute = False
args = []
while self.stream.current.type != 'rbracket':
if args:
self.stream.expect('comma')
args.append(self.parse_subscribed())
self.stream.expect('rbracket')
if len(args) == 1:
arg = args[0]
else:
arg = nodes.Tuple(args, 'load', lineno=token.lineno)
return nodes.Getitem(node, arg, 'load', lineno=token.lineno)
self.fail('expected subscript expression', self.lineno)
def parse_subscribed(self):
lineno = self.stream.current.lineno
if self.stream.current.type == 'colon':
next(self.stream)
args = [None]
else:
node = self.parse_expression()
if self.stream.current.type != 'colon':
return node
next(self.stream)
args = [node]
if self.stream.current.type == 'colon':
args.append(None)
elif self.stream.current.type not in ('rbracket', 'comma'):
args.append(self.parse_expression())
else:
args.append(None)
if self.stream.current.type == 'colon':
next(self.stream)
if self.stream.current.type not in ('rbracket', 'comma'):
args.append(self.parse_expression())
else:
args.append(None)
else:
args.append(None)
return nodes.Slice(lineno=lineno, *args)
def parse_call(self, node):
token = self.stream.expect('lparen')
args = []
kwargs = []
dyn_args = dyn_kwargs = None
require_comma = False
def ensure(expr):
if not expr:
self.fail('invalid syntax for function call expression',
token.lineno)
while self.stream.current.type != 'rparen':
if require_comma:
self.stream.expect('comma')
# support for trailing comma
if self.stream.current.type == 'rparen':
break
if self.stream.current.type == 'mul':
ensure(dyn_args is None and dyn_kwargs is None)
next(self.stream)
dyn_args = self.parse_expression()
elif self.stream.current.type == 'pow':
ensure(dyn_kwargs is None)
next(self.stream)
dyn_kwargs = self.parse_expression()
else:
ensure(dyn_args is None and dyn_kwargs is None)
if self.stream.current.type == 'name' and \
self.stream.look().type == 'assign':
key = self.stream.current.value
self.stream.skip(2)
value = self.parse_expression()
kwargs.append(nodes.Keyword(key, value,
lineno=value.lineno))
else:
ensure(not kwargs)
args.append(self.parse_expression())
require_comma = True
self.stream.expect('rparen')
if node is None:
return args, kwargs, dyn_args, dyn_kwargs
return nodes.Call(node, args, kwargs, dyn_args, dyn_kwargs,
lineno=token.lineno)
def parse_filter(self, node, start_inline=False):
while self.stream.current.type == 'pipe' or start_inline:
if not start_inline:
next(self.stream)
token = self.stream.expect('name')
name = token.value
while self.stream.current.type == 'dot':
next(self.stream)
name += '.' + self.stream.expect('name').value
if self.stream.current.type == 'lparen':
args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)
else:
args = []
kwargs = []
dyn_args = dyn_kwargs = None
node = nodes.Filter(node, name, args, kwargs, dyn_args,
dyn_kwargs, lineno=token.lineno)
start_inline = False
return node
def parse_test(self, node):
token = next(self.stream)
if self.stream.current.test('name:not'):
next(self.stream)
negated = True
else:
negated = False
name = self.stream.expect('name').value
while self.stream.current.type == 'dot':
next(self.stream)
name += '.' + self.stream.expect('name').value
dyn_args = dyn_kwargs = None
kwargs = []
if self.stream.current.type == 'lparen':
args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)
elif self.stream.current.type in ('name', 'string', 'integer',
'float', 'lparen', 'lbracket',
'lbrace') and not \
self.stream.current.test_any('name:else', 'name:or',
'name:and'):
if self.stream.current.test('name:is'):
self.fail('You cannot chain multiple tests with is')
args = [self.parse_expression()]
else:
args = []
node = nodes.Test(node, name, args, kwargs, dyn_args,
dyn_kwargs, lineno=token.lineno)
if negated:
node = nodes.Not(node, lineno=token.lineno)
return node
def subparse(self, end_tokens=None):
body = []
data_buffer = []
add_data = data_buffer.append
if end_tokens is not None:
self._end_token_stack.append(end_tokens)
def flush_data():
if data_buffer:
lineno = data_buffer[0].lineno
body.append(nodes.Output(data_buffer[:], lineno=lineno))
del data_buffer[:]
try:
while self.stream:
token = self.stream.current
if token.type == 'data':
if token.value:
add_data(nodes.TemplateData(token.value,
lineno=token.lineno))
next(self.stream)
elif token.type == 'variable_begin':
next(self.stream)
add_data(self.parse_tuple(with_condexpr=True))
self.stream.expect('variable_end')
elif token.type == 'block_begin':
flush_data()
next(self.stream)
if end_tokens is not None and \
self.stream.current.test_any(*end_tokens):
return body
rv = self.parse_statement()
if isinstance(rv, list):
body.extend(rv)
else:
body.append(rv)
self.stream.expect('block_end')
else:
raise AssertionError('internal parsing error')
flush_data()
finally:
if end_tokens is not None:
self._end_token_stack.pop()
return body
def parse(self):
"""Parse the whole template into a `Template` node."""
result = nodes.Template(self.subparse(), lineno=1)
result.set_environment(self.environment)
return result
| [
[
8,
0,
0.0067,
0.01,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0123,
0.0011,
0,
0.66,
0.1429,
436,
0,
1,
0,
0,
436,
0,
0
],
[
1,
0,
0.0134,
0.0011,
0,
0.66,
... | [
"\"\"\"\n jinja2.parser\n ~~~~~~~~~~~~~\n\n Implements the template parser.\n\n :copyright: (c) 2010 by the Jinja Team.\n :license: BSD, see LICENSE for more details.",
"from jinja2 import nodes",
"from jinja2.exceptions import TemplateSyntaxError, TemplateAssertionError",
"from jinja2.utils im... |
# -*- coding: utf-8 -*-
"""
jinja2.loaders
~~~~~~~~~~~~~~
Jinja loader classes.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import os
import sys
import weakref
from types import ModuleType
from os import path
try:
from hashlib import sha1
except ImportError:
from sha import new as sha1
from jinja2.exceptions import TemplateNotFound
from jinja2.utils import LRUCache, open_if_exists, internalcode
def split_template_path(template):
"""Split a path into segments and perform a sanity check. If it detects
'..' in the path it will raise a `TemplateNotFound` error.
"""
pieces = []
for piece in template.split('/'):
if path.sep in piece \
or (path.altsep and path.altsep in piece) or \
piece == path.pardir:
raise TemplateNotFound(template)
elif piece and piece != '.':
pieces.append(piece)
return pieces
class BaseLoader(object):
"""Baseclass for all loaders. Subclass this and override `get_source` to
implement a custom loading mechanism. The environment provides a
`get_template` method that calls the loader's `load` method to get the
:class:`Template` object.
A very basic example for a loader that looks up templates on the file
system could look like this::
from jinja2 import BaseLoader, TemplateNotFound
from os.path import join, exists, getmtime
class MyLoader(BaseLoader):
def __init__(self, path):
self.path = path
def get_source(self, environment, template):
path = join(self.path, template)
if not exists(path):
raise TemplateNotFound(template)
mtime = getmtime(path)
with file(path) as f:
source = f.read().decode('utf-8')
return source, path, lambda: mtime == getmtime(path)
"""
#: if set to `False` it indicates that the loader cannot provide access
#: to the source of templates.
#:
#: .. versionadded:: 2.4
has_source_access = True
def get_source(self, environment, template):
"""Get the template source, filename and reload helper for a template.
It's passed the environment and template name and has to return a
tuple in the form ``(source, filename, uptodate)`` or raise a
`TemplateNotFound` error if it can't locate the template.
The source part of the returned tuple must be the source of the
template as unicode string or a ASCII bytestring. The filename should
be the name of the file on the filesystem if it was loaded from there,
otherwise `None`. The filename is used by python for the tracebacks
if no loader extension is used.
The last item in the tuple is the `uptodate` function. If auto
reloading is enabled it's always called to check if the template
changed. No arguments are passed so the function must store the
old state somewhere (for example in a closure). If it returns `False`
the template will be reloaded.
"""
if not self.has_source_access:
raise RuntimeError('%s cannot provide access to the source' %
self.__class__.__name__)
raise TemplateNotFound(template)
def list_templates(self):
"""Iterates over all templates. If the loader does not support that
it should raise a :exc:`TypeError` which is the default behavior.
"""
raise TypeError('this loader cannot iterate over all templates')
@internalcode
def load(self, environment, name, globals=None):
"""Loads a template. This method looks up the template in the cache
or loads one by calling :meth:`get_source`. Subclasses should not
override this method as loaders working on collections of other
loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)
will not call this method but `get_source` directly.
"""
code = None
if globals is None:
globals = {}
# first we try to get the source for this template together
# with the filename and the uptodate function.
source, filename, uptodate = self.get_source(environment, name)
# try to load the code from the bytecode cache if there is a
# bytecode cache configured.
bcc = environment.bytecode_cache
if bcc is not None:
bucket = bcc.get_bucket(environment, name, filename, source)
code = bucket.code
# if we don't have code so far (not cached, no longer up to
# date) etc. we compile the template
if code is None:
code = environment.compile(source, name, filename)
# if the bytecode cache is available and the bucket doesn't
# have a code so far, we give the bucket the new code and put
# it back to the bytecode cache.
if bcc is not None and bucket.code is None:
bucket.code = code
bcc.set_bucket(bucket)
return environment.template_class.from_code(environment, code,
globals, uptodate)
class FileSystemLoader(BaseLoader):
"""Loads templates from the file system. This loader can find templates
in folders on the file system and is the preferred way to load them.
The loader takes the path to the templates as string, or if multiple
locations are wanted a list of them which is then looked up in the
given order:
>>> loader = FileSystemLoader('/path/to/templates')
>>> loader = FileSystemLoader(['/path/to/templates', '/other/path'])
Per default the template encoding is ``'utf-8'`` which can be changed
by setting the `encoding` parameter to something else.
"""
def __init__(self, searchpath, encoding='utf-8'):
if isinstance(searchpath, basestring):
searchpath = [searchpath]
self.searchpath = list(searchpath)
self.encoding = encoding
def get_source(self, environment, template):
pieces = split_template_path(template)
for searchpath in self.searchpath:
filename = path.join(searchpath, *pieces)
f = open_if_exists(filename)
if f is None:
continue
try:
contents = f.read().decode(self.encoding)
finally:
f.close()
mtime = path.getmtime(filename)
def uptodate():
try:
return path.getmtime(filename) == mtime
except OSError:
return False
return contents, filename, uptodate
raise TemplateNotFound(template)
def list_templates(self):
found = set()
for searchpath in self.searchpath:
for dirpath, dirnames, filenames in os.walk(searchpath):
for filename in filenames:
template = os.path.join(dirpath, filename) \
[len(searchpath):].strip(os.path.sep) \
.replace(os.path.sep, '/')
if template[:2] == './':
template = template[2:]
if template not in found:
found.add(template)
return sorted(found)
class PackageLoader(BaseLoader):
"""Load templates from python eggs or packages. It is constructed with
the name of the python package and the path to the templates in that
package::
loader = PackageLoader('mypackage', 'views')
If the package path is not given, ``'templates'`` is assumed.
Per default the template encoding is ``'utf-8'`` which can be changed
by setting the `encoding` parameter to something else. Due to the nature
of eggs it's only possible to reload templates if the package was loaded
from the file system and not a zip file.
"""
def __init__(self, package_name, package_path='templates',
encoding='utf-8'):
from pkg_resources import DefaultProvider, ResourceManager, \
get_provider
provider = get_provider(package_name)
self.encoding = encoding
self.manager = ResourceManager()
self.filesystem_bound = isinstance(provider, DefaultProvider)
self.provider = provider
self.package_path = package_path
def get_source(self, environment, template):
pieces = split_template_path(template)
p = '/'.join((self.package_path,) + tuple(pieces))
if not self.provider.has_resource(p):
raise TemplateNotFound(template)
filename = uptodate = None
if self.filesystem_bound:
filename = self.provider.get_resource_filename(self.manager, p)
mtime = path.getmtime(filename)
def uptodate():
try:
return path.getmtime(filename) == mtime
except OSError:
return False
source = self.provider.get_resource_string(self.manager, p)
return source.decode(self.encoding), filename, uptodate
def list_templates(self):
path = self.package_path
if path[:2] == './':
path = path[2:]
elif path == '.':
path = ''
offset = len(path)
results = []
def _walk(path):
for filename in self.provider.resource_listdir(path):
fullname = path + '/' + filename
if self.provider.resource_isdir(fullname):
for item in _walk(fullname):
results.append(item)
else:
results.append(fullname[offset:].lstrip('/'))
_walk(path)
results.sort()
return results
class DictLoader(BaseLoader):
"""Loads a template from a python dict. It's passed a dict of unicode
strings bound to template names. This loader is useful for unittesting:
>>> loader = DictLoader({'index.html': 'source here'})
Because auto reloading is rarely useful this is disabled per default.
"""
def __init__(self, mapping):
self.mapping = mapping
def get_source(self, environment, template):
if template in self.mapping:
source = self.mapping[template]
return source, None, lambda: source != self.mapping.get(template)
raise TemplateNotFound(template)
def list_templates(self):
return sorted(self.mapping)
class FunctionLoader(BaseLoader):
"""A loader that is passed a function which does the loading. The
function becomes the name of the template passed and has to return either
an unicode string with the template source, a tuple in the form ``(source,
filename, uptodatefunc)`` or `None` if the template does not exist.
>>> def load_template(name):
... if name == 'index.html':
... return '...'
...
>>> loader = FunctionLoader(load_template)
The `uptodatefunc` is a function that is called if autoreload is enabled
and has to return `True` if the template is still up to date. For more
details have a look at :meth:`BaseLoader.get_source` which has the same
return value.
"""
def __init__(self, load_func):
self.load_func = load_func
def get_source(self, environment, template):
rv = self.load_func(template)
if rv is None:
raise TemplateNotFound(template)
elif isinstance(rv, basestring):
return rv, None, None
return rv
class PrefixLoader(BaseLoader):
"""A loader that is passed a dict of loaders where each loader is bound
to a prefix. The prefix is delimited from the template by a slash per
default, which can be changed by setting the `delimiter` argument to
something else::
loader = PrefixLoader({
'app1': PackageLoader('mypackage.app1'),
'app2': PackageLoader('mypackage.app2')
})
By loading ``'app1/index.html'`` the file from the app1 package is loaded,
by loading ``'app2/index.html'`` the file from the second.
"""
def __init__(self, mapping, delimiter='/'):
self.mapping = mapping
self.delimiter = delimiter
def get_source(self, environment, template):
try:
prefix, name = template.split(self.delimiter, 1)
loader = self.mapping[prefix]
except (ValueError, KeyError):
raise TemplateNotFound(template)
try:
return loader.get_source(environment, name)
except TemplateNotFound:
# re-raise the exception with the correct fileame here.
# (the one that includes the prefix)
raise TemplateNotFound(template)
def list_templates(self):
result = []
for prefix, loader in self.mapping.iteritems():
for template in loader.list_templates():
result.append(prefix + self.delimiter + template)
return result
class ChoiceLoader(BaseLoader):
"""This loader works like the `PrefixLoader` just that no prefix is
specified. If a template could not be found by one loader the next one
is tried.
>>> loader = ChoiceLoader([
... FileSystemLoader('/path/to/user/templates'),
... FileSystemLoader('/path/to/system/templates')
... ])
This is useful if you want to allow users to override builtin templates
from a different location.
"""
def __init__(self, loaders):
self.loaders = loaders
def get_source(self, environment, template):
for loader in self.loaders:
try:
return loader.get_source(environment, template)
except TemplateNotFound:
pass
raise TemplateNotFound(template)
def list_templates(self):
found = set()
for loader in self.loaders:
found.update(loader.list_templates())
return sorted(found)
class _TemplateModule(ModuleType):
"""Like a normal module but with support for weak references"""
class ModuleLoader(BaseLoader):
"""This loader loads templates from precompiled templates.
Example usage:
>>> loader = ChoiceLoader([
... ModuleLoader('/path/to/compiled/templates'),
... FileSystemLoader('/path/to/templates')
... ])
"""
has_source_access = False
def __init__(self, path):
package_name = '_jinja2_module_templates_%x' % id(self)
# create a fake module that looks for the templates in the
# path given.
mod = _TemplateModule(package_name)
if isinstance(path, basestring):
path = [path]
else:
path = list(path)
mod.__path__ = path
sys.modules[package_name] = weakref.proxy(mod,
lambda x: sys.modules.pop(package_name, None))
# the only strong reference, the sys.modules entry is weak
# so that the garbage collector can remove it once the
# loader that created it goes out of business.
self.module = mod
self.package_name = package_name
@staticmethod
def get_template_key(name):
return 'tmpl_' + sha1(name.encode('utf-8')).hexdigest()
@staticmethod
def get_module_filename(name):
return ModuleLoader.get_template_key(name) + '.py'
@internalcode
def load(self, environment, name, globals=None):
key = self.get_template_key(name)
module = '%s.%s' % (self.package_name, key)
mod = getattr(self.module, module, None)
if mod is None:
try:
mod = __import__(module, None, None, ['root'])
except ImportError:
raise TemplateNotFound(name)
# remove the entry from sys.modules, we only want the attribute
# on the module object we have stored on the loader.
sys.modules.pop(module, None)
return environment.template_class.from_module_dict(
environment, mod.__dict__, globals)
| [
[
8,
0,
0.0134,
0.02,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0245,
0.0022,
0,
0.66,
0.0556,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0267,
0.0022,
0,
0.66,
... | [
"\"\"\"\n jinja2.loaders\n ~~~~~~~~~~~~~~\n\n Jinja loader classes.\n\n :copyright: (c) 2010 by the Jinja Team.\n :license: BSD, see LICENSE for more details.",
"import os",
"import sys",
"import weakref",
"from types import ModuleType",
"from os import path",
"try:\n from hashlib impo... |
# -*- coding: utf-8 -*-
"""
jinja2.tests
~~~~~~~~~~~~
Jinja test functions. Used with the "is" operator.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import re
from jinja2.runtime import Undefined
# nose, nothing here to test
__test__ = False
number_re = re.compile(r'^-?\d+(\.\d+)?$')
regex_type = type(number_re)
try:
test_callable = callable
except NameError:
def test_callable(x):
return hasattr(x, '__call__')
def test_odd(value):
"""Return true if the variable is odd."""
return value % 2 == 1
def test_even(value):
"""Return true if the variable is even."""
return value % 2 == 0
def test_divisibleby(value, num):
"""Check if a variable is divisible by a number."""
return value % num == 0
def test_defined(value):
"""Return true if the variable is defined:
.. sourcecode:: jinja
{% if variable is defined %}
value of variable: {{ variable }}
{% else %}
variable is not defined
{% endif %}
See the :func:`default` filter for a simple way to set undefined
variables.
"""
return not isinstance(value, Undefined)
def test_undefined(value):
"""Like :func:`defined` but the other way round."""
return isinstance(value, Undefined)
def test_none(value):
"""Return true if the variable is none."""
return value is None
def test_lower(value):
"""Return true if the variable is lowercased."""
return unicode(value).islower()
def test_upper(value):
"""Return true if the variable is uppercased."""
return unicode(value).isupper()
def test_string(value):
"""Return true if the object is a string."""
return isinstance(value, basestring)
def test_number(value):
"""Return true if the variable is a number."""
return isinstance(value, (int, long, float, complex))
def test_sequence(value):
"""Return true if the variable is a sequence. Sequences are variables
that are iterable.
"""
try:
len(value)
value.__getitem__
except:
return False
return True
def test_sameas(value, other):
"""Check if an object points to the same memory address than another
object:
.. sourcecode:: jinja
{% if foo.attribute is sameas false %}
the foo attribute really is the `False` singleton
{% endif %}
"""
return value is other
def test_iterable(value):
"""Check if it's possible to iterate over an object."""
try:
iter(value)
except TypeError:
return False
return True
def test_escaped(value):
"""Check if the value is escaped."""
return hasattr(value, '__html__')
TESTS = {
'odd': test_odd,
'even': test_even,
'divisibleby': test_divisibleby,
'defined': test_defined,
'undefined': test_undefined,
'none': test_none,
'lower': test_lower,
'upper': test_upper,
'string': test_string,
'number': test_number,
'sequence': test_sequence,
'iterable': test_iterable,
'callable': test_callable,
'sameas': test_sameas,
'escaped': test_escaped
}
| [
[
8,
0,
0.0411,
0.0616,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0753,
0.0068,
0,
0.66,
0.0476,
540,
0,
1,
0,
0,
540,
0,
0
],
[
1,
0,
0.0822,
0.0068,
0,
0.66... | [
"\"\"\"\n jinja2.tests\n ~~~~~~~~~~~~\n\n Jinja test functions. Used with the \"is\" operator.\n\n :copyright: (c) 2010 by the Jinja Team.\n :license: BSD, see LICENSE for more details.",
"import re",
"from jinja2.runtime import Undefined",
"__test__ = False",
"number_re = re.compile(r'^-?\\d... |
# -*- coding: utf-8 -*-
"""
jinja2.filters
~~~~~~~~~~~~~~
Bundled jinja filters.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import re
import math
from random import choice
from operator import itemgetter
from itertools import imap, groupby
from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode
from jinja2.runtime import Undefined
from jinja2.exceptions import FilterArgumentError, SecurityError
_word_re = re.compile(r'\w+(?u)')
def contextfilter(f):
"""Decorator for marking context dependent filters. The current
:class:`Context` will be passed as first argument.
"""
f.contextfilter = True
return f
def evalcontextfilter(f):
"""Decorator for marking eval-context dependent filters. An eval
context object is passed as first argument. For more information
about the eval context, see :ref:`eval-context`.
.. versionadded:: 2.4
"""
f.evalcontextfilter = True
return f
def environmentfilter(f):
"""Decorator for marking evironment dependent filters. The current
:class:`Environment` is passed to the filter as first argument.
"""
f.environmentfilter = True
return f
def do_forceescape(value):
"""Enforce HTML escaping. This will probably double escape variables."""
if hasattr(value, '__html__'):
value = value.__html__()
return escape(unicode(value))
@evalcontextfilter
def do_replace(eval_ctx, s, old, new, count=None):
"""Return a copy of the value with all occurrences of a substring
replaced with a new one. The first argument is the substring
that should be replaced, the second is the replacement string.
If the optional third argument ``count`` is given, only the first
``count`` occurrences are replaced:
.. sourcecode:: jinja
{{ "Hello World"|replace("Hello", "Goodbye") }}
-> Goodbye World
{{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
-> d'oh, d'oh, aaargh
"""
if count is None:
count = -1
if not eval_ctx.autoescape:
return unicode(s).replace(unicode(old), unicode(new), count)
if hasattr(old, '__html__') or hasattr(new, '__html__') and \
not hasattr(s, '__html__'):
s = escape(s)
else:
s = soft_unicode(s)
return s.replace(soft_unicode(old), soft_unicode(new), count)
def do_upper(s):
"""Convert a value to uppercase."""
return soft_unicode(s).upper()
def do_lower(s):
"""Convert a value to lowercase."""
return soft_unicode(s).lower()
@evalcontextfilter
def do_xmlattr(_eval_ctx, d, autospace=True):
"""Create an SGML/XML attribute string based on the items in a dict.
All values that are neither `none` nor `undefined` are automatically
escaped:
.. sourcecode:: html+jinja
<ul{{ {'class': 'my_list', 'missing': none,
'id': 'list-%d'|format(variable)}|xmlattr }}>
...
</ul>
Results in something like this:
.. sourcecode:: html
<ul class="my_list" id="list-42">
...
</ul>
As you can see it automatically prepends a space in front of the item
if the filter returned something unless the second parameter is false.
"""
rv = u' '.join(
u'%s="%s"' % (escape(key), escape(value))
for key, value in d.iteritems()
if value is not None and not isinstance(value, Undefined)
)
if autospace and rv:
rv = u' ' + rv
if _eval_ctx.autoescape:
rv = Markup(rv)
return rv
def do_capitalize(s):
"""Capitalize a value. The first character will be uppercase, all others
lowercase.
"""
return soft_unicode(s).capitalize()
def do_title(s):
"""Return a titlecased version of the value. I.e. words will start with
uppercase letters, all remaining characters are lowercase.
"""
return soft_unicode(s).title()
def do_dictsort(value, case_sensitive=False, by='key'):
"""Sort a dict and yield (key, value) pairs. Because python dicts are
unsorted you may want to use this function to order them by either
key or value:
.. sourcecode:: jinja
{% for item in mydict|dictsort %}
sort the dict by key, case insensitive
{% for item in mydict|dicsort(true) %}
sort the dict by key, case sensitive
{% for item in mydict|dictsort(false, 'value') %}
sort the dict by key, case insensitive, sorted
normally and ordered by value.
"""
if by == 'key':
pos = 0
elif by == 'value':
pos = 1
else:
raise FilterArgumentError('You can only sort by either '
'"key" or "value"')
def sort_func(item):
value = item[pos]
if isinstance(value, basestring) and not case_sensitive:
value = value.lower()
return value
return sorted(value.items(), key=sort_func)
def do_sort(value, reverse=False, case_sensitive=False):
"""Sort an iterable. Per default it sorts ascending, if you pass it
true as first argument it will reverse the sorting.
If the iterable is made of strings the third parameter can be used to
control the case sensitiveness of the comparison which is disabled by
default.
.. sourcecode:: jinja
{% for item in iterable|sort %}
...
{% endfor %}
"""
if not case_sensitive:
def sort_func(item):
if isinstance(item, basestring):
item = item.lower()
return item
else:
sort_func = None
return sorted(value, key=sort_func, reverse=reverse)
def do_default(value, default_value=u'', boolean=False):
"""If the value is undefined it will return the passed default value,
otherwise the value of the variable:
.. sourcecode:: jinja
{{ my_variable|default('my_variable is not defined') }}
This will output the value of ``my_variable`` if the variable was
defined, otherwise ``'my_variable is not defined'``. If you want
to use default with variables that evaluate to false you have to
set the second parameter to `true`:
.. sourcecode:: jinja
{{ ''|default('the string was empty', true) }}
"""
if (boolean and not value) or isinstance(value, Undefined):
return default_value
return value
@evalcontextfilter
def do_join(eval_ctx, value, d=u''):
"""Return a string which is the concatenation of the strings in the
sequence. The separator between elements is an empty string per
default, you can define it with the optional parameter:
.. sourcecode:: jinja
{{ [1, 2, 3]|join('|') }}
-> 1|2|3
{{ [1, 2, 3]|join }}
-> 123
"""
# no automatic escaping? joining is a lot eaiser then
if not eval_ctx.autoescape:
return unicode(d).join(imap(unicode, value))
# if the delimiter doesn't have an html representation we check
# if any of the items has. If yes we do a coercion to Markup
if not hasattr(d, '__html__'):
value = list(value)
do_escape = False
for idx, item in enumerate(value):
if hasattr(item, '__html__'):
do_escape = True
else:
value[idx] = unicode(item)
if do_escape:
d = escape(d)
else:
d = unicode(d)
return d.join(value)
# no html involved, to normal joining
return soft_unicode(d).join(imap(soft_unicode, value))
def do_center(value, width=80):
"""Centers the value in a field of a given width."""
return unicode(value).center(width)
@environmentfilter
def do_first(environment, seq):
"""Return the first item of a sequence."""
try:
return iter(seq).next()
except StopIteration:
return environment.undefined('No first item, sequence was empty.')
@environmentfilter
def do_last(environment, seq):
"""Return the last item of a sequence."""
try:
return iter(reversed(seq)).next()
except StopIteration:
return environment.undefined('No last item, sequence was empty.')
@environmentfilter
def do_random(environment, seq):
"""Return a random item from the sequence."""
try:
return choice(seq)
except IndexError:
return environment.undefined('No random item, sequence was empty.')
def do_filesizeformat(value, binary=False):
"""Format the value like a 'human-readable' file size (i.e. 13 KB,
4.1 MB, 102 bytes, etc). Per default decimal prefixes are used (mega,
giga, etc.), if the second parameter is set to `True` the binary
prefixes are used (mebi, gibi).
"""
bytes = float(value)
base = binary and 1024 or 1000
middle = binary and 'i' or ''
if bytes < base:
return "%d Byte%s" % (bytes, bytes != 1 and 's' or '')
elif bytes < base * base:
return "%.1f K%sB" % (bytes / base, middle)
elif bytes < base * base * base:
return "%.1f M%sB" % (bytes / (base * base), middle)
return "%.1f G%sB" % (bytes / (base * base * base), middle)
def do_pprint(value, verbose=False):
"""Pretty print a variable. Useful for debugging.
With Jinja 1.2 onwards you can pass it a parameter. If this parameter
is truthy the output will be more verbose (this requires `pretty`)
"""
return pformat(value, verbose=verbose)
@evalcontextfilter
def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False):
"""Converts URLs in plain text into clickable links.
If you pass the filter an additional integer it will shorten the urls
to that number. Also a third argument exists that makes the urls
"nofollow":
.. sourcecode:: jinja
{{ mytext|urlize(40, true) }}
links are shortened to 40 chars and defined with rel="nofollow"
"""
rv = urlize(value, trim_url_limit, nofollow)
if eval_ctx.autoescape:
rv = Markup(rv)
return rv
def do_indent(s, width=4, indentfirst=False):
"""Return a copy of the passed string, each line indented by
4 spaces. The first line is not indented. If you want to
change the number of spaces or indent the first line too
you can pass additional parameters to the filter:
.. sourcecode:: jinja
{{ mytext|indent(2, true) }}
indent by two spaces and indent the first line too.
"""
indention = u' ' * width
rv = (u'\n' + indention).join(s.splitlines())
if indentfirst:
rv = indention + rv
return rv
def do_truncate(s, length=255, killwords=False, end='...'):
"""Return a truncated copy of the string. The length is specified
with the first parameter which defaults to ``255``. If the second
parameter is ``true`` the filter will cut the text at length. Otherwise
it will try to save the last word. If the text was in fact
truncated it will append an ellipsis sign (``"..."``). If you want a
different ellipsis sign than ``"..."`` you can specify it using the
third parameter.
.. sourcecode jinja::
{{ mytext|truncate(300, false, '»') }}
truncate mytext to 300 chars, don't split up words, use a
right pointing double arrow as ellipsis sign.
"""
if len(s) <= length:
return s
elif killwords:
return s[:length] + end
words = s.split(' ')
result = []
m = 0
for word in words:
m += len(word) + 1
if m > length:
break
result.append(word)
result.append(end)
return u' '.join(result)
def do_wordwrap(s, width=79, break_long_words=True):
"""
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`.
"""
import textwrap
return u'\n'.join(textwrap.wrap(s, width=width, expand_tabs=False,
replace_whitespace=False,
break_long_words=break_long_words))
def do_wordcount(s):
"""Count the words in that string."""
return len(_word_re.findall(s))
def do_int(value, default=0):
"""Convert the value into an integer. If the
conversion doesn't work it will return ``0``. You can
override this default using the first parameter.
"""
try:
return int(value)
except (TypeError, ValueError):
# this quirk is necessary so that "42.23"|int gives 42.
try:
return int(float(value))
except (TypeError, ValueError):
return default
def do_float(value, default=0.0):
"""Convert the value into a floating point number. If the
conversion doesn't work it will return ``0.0``. You can
override this default using the first parameter.
"""
try:
return float(value)
except (TypeError, ValueError):
return default
def do_format(value, *args, **kwargs):
"""
Apply python string formatting on an object:
.. sourcecode:: jinja
{{ "%s - %s"|format("Hello?", "Foo!") }}
-> Hello? - Foo!
"""
if args and kwargs:
raise FilterArgumentError('can\'t handle positional and keyword '
'arguments at the same time')
return soft_unicode(value) % (kwargs or args)
def do_trim(value):
"""Strip leading and trailing whitespace."""
return soft_unicode(value).strip()
def do_striptags(value):
"""Strip SGML/XML tags and replace adjacent whitespace by one space.
"""
if hasattr(value, '__html__'):
value = value.__html__()
return Markup(unicode(value)).striptags()
def do_slice(value, slices, fill_with=None):
"""Slice an iterator and return a list of lists containing
those items. Useful if you want to create a div containing
three ul tags that represent columns:
.. sourcecode:: html+jinja
<div class="columwrapper">
{%- for column in items|slice(3) %}
<ul class="column-{{ loop.index }}">
{%- for item in column %}
<li>{{ item }}</li>
{%- endfor %}
</ul>
{%- endfor %}
</div>
If you pass it a second argument it's used to fill missing
values on the last iteration.
"""
seq = list(value)
length = len(seq)
items_per_slice = length // slices
slices_with_extra = length % slices
offset = 0
for slice_number in xrange(slices):
start = offset + slice_number * items_per_slice
if slice_number < slices_with_extra:
offset += 1
end = offset + (slice_number + 1) * items_per_slice
tmp = seq[start:end]
if fill_with is not None and slice_number >= slices_with_extra:
tmp.append(fill_with)
yield tmp
def do_batch(value, linecount, fill_with=None):
"""
A filter that batches items. It works pretty much like `slice`
just the other way round. It returns a list of lists with the
given number of items. If you provide a second parameter this
is used to fill missing items. See this example:
.. sourcecode:: html+jinja
<table>
{%- for row in items|batch(3, ' ') %}
<tr>
{%- for column in row %}
<td>{{ column }}</td>
{%- endfor %}
</tr>
{%- endfor %}
</table>
"""
result = []
tmp = []
for item in value:
if len(tmp) == linecount:
yield tmp
tmp = []
tmp.append(item)
if tmp:
if fill_with is not None and len(tmp) < linecount:
tmp += [fill_with] * (linecount - len(tmp))
yield tmp
def do_round(value, precision=0, method='common'):
"""Round the number to a given precision. The first
parameter specifies the precision (default is ``0``), the
second the rounding method:
- ``'common'`` rounds either up or down
- ``'ceil'`` always rounds up
- ``'floor'`` always rounds down
If you don't specify a method ``'common'`` is used.
.. sourcecode:: jinja
{{ 42.55|round }}
-> 43.0
{{ 42.55|round(1, 'floor') }}
-> 42.5
Note that even if rounded to 0 precision, a float is returned. If
you need a real integer, pipe it through `int`:
.. sourcecode:: jinja
{{ 42.55|round|int }}
-> 43
"""
if not method in ('common', 'ceil', 'floor'):
raise FilterArgumentError('method must be common, ceil or floor')
if method == 'common':
return round(value, precision)
func = getattr(math, method)
return func(value * (10 ** precision)) / (10 ** precision)
@environmentfilter
def do_groupby(environment, value, attribute):
"""Group a sequence of objects by a common attribute.
If you for example have a list of dicts or objects that represent persons
with `gender`, `first_name` and `last_name` attributes and you want to
group all users by genders you can do something like the following
snippet:
.. sourcecode:: html+jinja
<ul>
{% for group in persons|groupby('gender') %}
<li>{{ group.grouper }}<ul>
{% for person in group.list %}
<li>{{ person.first_name }} {{ person.last_name }}</li>
{% endfor %}</ul></li>
{% endfor %}
</ul>
Additionally it's possible to use tuple unpacking for the grouper and
list:
.. sourcecode:: html+jinja
<ul>
{% for grouper, list in persons|groupby('gender') %}
...
{% endfor %}
</ul>
As you can see the item we're grouping by is stored in the `grouper`
attribute and the `list` contains all the objects that have this grouper
in common.
"""
expr = lambda x: environment.getitem(x, attribute)
return sorted(map(_GroupTuple, groupby(sorted(value, key=expr), expr)))
class _GroupTuple(tuple):
__slots__ = ()
grouper = property(itemgetter(0))
list = property(itemgetter(1))
def __new__(cls, (key, value)):
return tuple.__new__(cls, (key, list(value)))
def do_list(value):
"""Convert the value into a list. If it was a string the returned list
will be a list of characters.
"""
return list(value)
def do_mark_safe(value):
"""Mark the value as safe which means that in an environment with automatic
escaping enabled this variable will not be escaped.
"""
return Markup(value)
def do_mark_unsafe(value):
"""Mark a value as unsafe. This is the reverse operation for :func:`safe`."""
return unicode(value)
def do_reverse(value):
"""Reverse the object or return an iterator the iterates over it the other
way round.
"""
if isinstance(value, basestring):
return value[::-1]
try:
return reversed(value)
except TypeError:
try:
rv = list(value)
rv.reverse()
return rv
except TypeError:
raise FilterArgumentError('argument must be iterable')
@environmentfilter
def do_attr(environment, obj, name):
"""Get an attribute of an object. ``foo|attr("bar")`` works like
``foo["bar"]`` just that always an attribute is returned and items are not
looked up.
See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.
"""
try:
name = str(name)
except UnicodeError:
pass
else:
try:
value = getattr(obj, name)
except AttributeError:
pass
else:
if environment.sandboxed and not \
environment.is_safe_attribute(obj, name, value):
return environment.unsafe_undefined(obj, name)
return value
return environment.undefined(obj=obj, name=name)
FILTERS = {
'attr': do_attr,
'replace': do_replace,
'upper': do_upper,
'lower': do_lower,
'escape': escape,
'e': escape,
'forceescape': do_forceescape,
'capitalize': do_capitalize,
'title': do_title,
'default': do_default,
'd': do_default,
'join': do_join,
'count': len,
'dictsort': do_dictsort,
'sort': do_sort,
'length': len,
'reverse': do_reverse,
'center': do_center,
'indent': do_indent,
'title': do_title,
'capitalize': do_capitalize,
'first': do_first,
'last': do_last,
'random': do_random,
'filesizeformat': do_filesizeformat,
'pprint': do_pprint,
'truncate': do_truncate,
'wordwrap': do_wordwrap,
'wordcount': do_wordcount,
'int': do_int,
'float': do_float,
'string': soft_unicode,
'list': do_list,
'urlize': do_urlize,
'format': do_format,
'trim': do_trim,
'striptags': do_striptags,
'slice': do_slice,
'batch': do_batch,
'sum': sum,
'abs': abs,
'round': do_round,
'groupby': do_groupby,
'safe': do_mark_safe,
'xmlattr': do_xmlattr
}
| [
[
8,
0,
0.0084,
0.0126,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0153,
0.0014,
0,
0.66,
0.02,
540,
0,
1,
0,
0,
540,
0,
0
],
[
1,
0,
0.0167,
0.0014,
0,
0.66,
... | [
"\"\"\"\n jinja2.filters\n ~~~~~~~~~~~~~~\n\n Bundled jinja filters.\n\n :copyright: (c) 2010 by the Jinja Team.\n :license: BSD, see LICENSE for more details.",
"import re",
"import math",
"from random import choice",
"from operator import itemgetter",
"from itertools import imap, groupby"... |
import gc
import unittest
from jinja2._markupsafe import Markup, escape, escape_silent
class MarkupTestCase(unittest.TestCase):
def test_markup_operations(self):
# adding two strings should escape the unsafe one
unsafe = '<script type="application/x-some-script">alert("foo");</script>'
safe = Markup('<em>username</em>')
assert unsafe + safe == unicode(escape(unsafe)) + unicode(safe)
# string interpolations are safe to use too
assert Markup('<em>%s</em>') % '<bad user>' == \
'<em><bad user></em>'
assert Markup('<em>%(username)s</em>') % {
'username': '<bad user>'
} == '<em><bad user></em>'
# an escaped object is markup too
assert type(Markup('foo') + 'bar') is Markup
# and it implements __html__ by returning itself
x = Markup("foo")
assert x.__html__() is x
# it also knows how to treat __html__ objects
class Foo(object):
def __html__(self):
return '<em>awesome</em>'
def __unicode__(self):
return 'awesome'
assert Markup(Foo()) == '<em>awesome</em>'
assert Markup('<strong>%s</strong>') % Foo() == \
'<strong><em>awesome</em></strong>'
# escaping and unescaping
assert escape('"<>&\'') == '"<>&''
assert Markup("<em>Foo & Bar</em>").striptags() == "Foo & Bar"
assert Markup("<test>").unescape() == "<test>"
def test_all_set(self):
import jinja2._markupsafe as markup
for item in markup.__all__:
getattr(markup, item)
def test_escape_silent(self):
assert escape_silent(None) == Markup()
assert escape(None) == Markup(None)
assert escape_silent('<foo>') == Markup(u'<foo>')
class MarkupLeakTestCase(unittest.TestCase):
def test_markup_leaks(self):
counts = set()
for count in xrange(20):
for item in xrange(1000):
escape("foo")
escape("<foo>")
escape(u"foo")
escape(u"<foo>")
counts.add(len(gc.get_objects()))
assert len(counts) == 1, 'ouch, c extension seems to leak objects'
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(MarkupTestCase))
# this test only tests the c extension
if not hasattr(escape, 'func_code'):
suite.addTest(unittest.makeSuite(MarkupLeakTestCase))
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| [
[
1,
0,
0.0125,
0.0125,
0,
0.66,
0,
92,
0,
1,
0,
0,
92,
0,
0
],
[
1,
0,
0.025,
0.0125,
0,
0.66,
0.1667,
88,
0,
1,
0,
0,
88,
0,
0
],
[
1,
0,
0.0375,
0.0125,
0,
0.66,... | [
"import gc",
"import unittest",
"from jinja2._markupsafe import Markup, escape, escape_silent",
"class MarkupTestCase(unittest.TestCase):\n\n def test_markup_operations(self):\n # adding two strings should escape the unsafe one\n unsafe = '<script type=\"application/x-some-script\">alert(\"fo... |
# -*- coding: utf-8 -*-
"""
jinja2._markupsafe._bundle
~~~~~~~~~~~~~~~~~~~~~~~~~~
This script pulls in markupsafe from a source folder and
bundles it with Jinja2. It does not pull in the speedups
module though.
:copyright: Copyright 2010 by the Jinja team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import sys
import os
import re
def rewrite_imports(lines):
for idx, line in enumerate(lines):
new_line = re.sub(r'(import|from)\s+markupsafe\b',
r'\1 jinja2._markupsafe', line)
if new_line != line:
lines[idx] = new_line
def main():
if len(sys.argv) != 2:
print 'error: only argument is path to markupsafe'
sys.exit(1)
basedir = os.path.dirname(__file__)
markupdir = sys.argv[1]
for filename in os.listdir(markupdir):
if filename.endswith('.py'):
f = open(os.path.join(markupdir, filename))
try:
lines = list(f)
finally:
f.close()
rewrite_imports(lines)
f = open(os.path.join(basedir, filename), 'w')
try:
for line in lines:
f.write(line)
finally:
f.close()
if __name__ == '__main__':
main()
| [
[
8,
0,
0.1429,
0.2245,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2653,
0.0204,
0,
0.66,
0.1667,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.2857,
0.0204,
0,
0.66... | [
"\"\"\"\n jinja2._markupsafe._bundle\n ~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n This script pulls in markupsafe from a source folder and\n bundles it with Jinja2. It does not pull in the speedups\n module though.",
"import sys",
"import os",
"import re",
"def rewrite_imports(lines):\n for idx, line... |
# -*- coding: utf-8 -*-
"""
markupsafe._native
~~~~~~~~~~~~~~~~~~
Native Python implementation the C module is not compiled.
:copyright: (c) 2010 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
from jinja2._markupsafe import Markup
def escape(s):
"""Convert the characters &, <, >, ' and " in string s to HTML-safe
sequences. Use this if you need to display text that might contain
such characters in HTML. Marks return value as markup string.
"""
if hasattr(s, '__html__'):
return s.__html__()
return Markup(unicode(s)
.replace('&', '&')
.replace('>', '>')
.replace('<', '<')
.replace("'", ''')
.replace('"', '"')
)
def escape_silent(s):
"""Like :func:`escape` but converts `None` into an empty
markup string.
"""
if s is None:
return Markup()
return escape(s)
def soft_unicode(s):
"""Make a string unicode if it isn't already. That way a markup
string is not converted back to unicode.
"""
if not isinstance(s, unicode):
s = unicode(s)
return s
| [
[
8,
0,
0.1333,
0.2,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2444,
0.0222,
0,
0.66,
0.25,
409,
0,
1,
0,
0,
409,
0,
0
],
[
2,
0,
0.4556,
0.3111,
0,
0.66,
... | [
"\"\"\"\n markupsafe._native\n ~~~~~~~~~~~~~~~~~~\n\n Native Python implementation the C module is not compiled.\n\n :copyright: (c) 2010 by Armin Ronacher.\n :license: BSD, see LICENSE for more details.",
"from jinja2._markupsafe import Markup",
"def escape(s):\n \"\"\"Convert the characters ... |
# -*- coding: utf-8 -*-
"""
markupsafe
~~~~~~~~~~
Implements a Markup string.
:copyright: (c) 2010 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import re
from itertools import imap
__all__ = ['Markup', 'soft_unicode', 'escape', 'escape_silent']
_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
_entity_re = re.compile(r'&([^;]+);')
class Markup(unicode):
r"""Marks a string as being safe for inclusion in HTML/XML output without
needing to be escaped. This implements the `__html__` interface a couple
of frameworks and web applications use. :class:`Markup` is a direct
subclass of `unicode` and provides all the methods of `unicode` just that
it escapes arguments passed and always returns `Markup`.
The `escape` function returns markup objects so that double escaping can't
happen.
The constructor of the :class:`Markup` class can be used for three
different things: When passed an unicode object it's assumed to be safe,
when passed an object with an HTML representation (has an `__html__`
method) that representation is used, otherwise the object passed is
converted into a unicode string and then assumed to be safe:
>>> Markup("Hello <em>World</em>!")
Markup(u'Hello <em>World</em>!')
>>> class Foo(object):
... def __html__(self):
... return '<a href="#">foo</a>'
...
>>> Markup(Foo())
Markup(u'<a href="#">foo</a>')
If you want object passed being always treated as unsafe you can use the
:meth:`escape` classmethod to create a :class:`Markup` object:
>>> Markup.escape("Hello <em>World</em>!")
Markup(u'Hello <em>World</em>!')
Operations on a markup string are markup aware which means that all
arguments are passed through the :func:`escape` function:
>>> em = Markup("<em>%s</em>")
>>> em % "foo & bar"
Markup(u'<em>foo & bar</em>')
>>> strong = Markup("<strong>%(text)s</strong>")
>>> strong % {'text': '<blink>hacker here</blink>'}
Markup(u'<strong><blink>hacker here</blink></strong>')
>>> Markup("<em>Hello</em> ") + "<foo>"
Markup(u'<em>Hello</em> <foo>')
"""
__slots__ = ()
def __new__(cls, base=u'', encoding=None, errors='strict'):
if hasattr(base, '__html__'):
base = base.__html__()
if encoding is None:
return unicode.__new__(cls, base)
return unicode.__new__(cls, base, encoding, errors)
def __html__(self):
return self
def __add__(self, other):
if hasattr(other, '__html__') or isinstance(other, basestring):
return self.__class__(unicode(self) + unicode(escape(other)))
return NotImplemented
def __radd__(self, other):
if hasattr(other, '__html__') or isinstance(other, basestring):
return self.__class__(unicode(escape(other)) + unicode(self))
return NotImplemented
def __mul__(self, num):
if isinstance(num, (int, long)):
return self.__class__(unicode.__mul__(self, num))
return NotImplemented
__rmul__ = __mul__
def __mod__(self, arg):
if isinstance(arg, tuple):
arg = tuple(imap(_MarkupEscapeHelper, arg))
else:
arg = _MarkupEscapeHelper(arg)
return self.__class__(unicode.__mod__(self, arg))
def __repr__(self):
return '%s(%s)' % (
self.__class__.__name__,
unicode.__repr__(self)
)
def join(self, seq):
return self.__class__(unicode.join(self, imap(escape, seq)))
join.__doc__ = unicode.join.__doc__
def split(self, *args, **kwargs):
return map(self.__class__, unicode.split(self, *args, **kwargs))
split.__doc__ = unicode.split.__doc__
def rsplit(self, *args, **kwargs):
return map(self.__class__, unicode.rsplit(self, *args, **kwargs))
rsplit.__doc__ = unicode.rsplit.__doc__
def splitlines(self, *args, **kwargs):
return map(self.__class__, unicode.splitlines(self, *args, **kwargs))
splitlines.__doc__ = unicode.splitlines.__doc__
def unescape(self):
r"""Unescape markup again into an unicode string. This also resolves
known HTML4 and XHTML entities:
>>> Markup("Main » <em>About</em>").unescape()
u'Main \xbb <em>About</em>'
"""
from jinja2._markupsafe._constants import HTML_ENTITIES
def handle_match(m):
name = m.group(1)
if name in HTML_ENTITIES:
return unichr(HTML_ENTITIES[name])
try:
if name[:2] in ('#x', '#X'):
return unichr(int(name[2:], 16))
elif name.startswith('#'):
return unichr(int(name[1:]))
except ValueError:
pass
return u''
return _entity_re.sub(handle_match, unicode(self))
def striptags(self):
r"""Unescape markup into an unicode string and strip all tags. This
also resolves known HTML4 and XHTML entities. Whitespace is
normalized to one:
>>> Markup("Main » <em>About</em>").striptags()
u'Main \xbb About'
"""
stripped = u' '.join(_striptags_re.sub('', self).split())
return Markup(stripped).unescape()
@classmethod
def escape(cls, s):
"""Escape the string. Works like :func:`escape` with the difference
that for subclasses of :class:`Markup` this function would return the
correct subclass.
"""
rv = escape(s)
if rv.__class__ is not cls:
return cls(rv)
return rv
def make_wrapper(name):
orig = getattr(unicode, name)
def func(self, *args, **kwargs):
args = _escape_argspec(list(args), enumerate(args))
_escape_argspec(kwargs, kwargs.iteritems())
return self.__class__(orig(self, *args, **kwargs))
func.__name__ = orig.__name__
func.__doc__ = orig.__doc__
return func
for method in '__getitem__', 'capitalize', \
'title', 'lower', 'upper', 'replace', 'ljust', \
'rjust', 'lstrip', 'rstrip', 'center', 'strip', \
'translate', 'expandtabs', 'swapcase', 'zfill':
locals()[method] = make_wrapper(method)
# new in python 2.5
if hasattr(unicode, 'partition'):
partition = make_wrapper('partition'),
rpartition = make_wrapper('rpartition')
# new in python 2.6
if hasattr(unicode, 'format'):
format = make_wrapper('format')
# not in python 3
if hasattr(unicode, '__getslice__'):
__getslice__ = make_wrapper('__getslice__')
del method, make_wrapper
def _escape_argspec(obj, iterable):
"""Helper for various string-wrapped functions."""
for key, value in iterable:
if hasattr(value, '__html__') or isinstance(value, basestring):
obj[key] = escape(value)
return obj
class _MarkupEscapeHelper(object):
"""Helper for Markup.__mod__"""
def __init__(self, obj):
self.obj = obj
__getitem__ = lambda s, x: _MarkupEscapeHelper(s.obj[x])
__str__ = lambda s: str(escape(s.obj))
__unicode__ = lambda s: unicode(escape(s.obj))
__repr__ = lambda s: str(escape(repr(s.obj)))
__int__ = lambda s: int(s.obj)
__float__ = lambda s: float(s.obj)
# we have to import it down here as the speedups and native
# modules imports the markup type which is define above.
try:
from jinja2._markupsafe._speedups import escape, escape_silent, soft_unicode
except ImportError:
from jinja2._markupsafe._native import escape, escape_silent, soft_unicode
| [
[
8,
0,
0.0267,
0.04,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0489,
0.0044,
0,
0.66,
0.1111,
540,
0,
1,
0,
0,
540,
0,
0
],
[
1,
0,
0.0533,
0.0044,
0,
0.66,
... | [
"\"\"\"\n markupsafe\n ~~~~~~~~~~\n\n Implements a Markup string.\n\n :copyright: (c) 2010 by Armin Ronacher.\n :license: BSD, see LICENSE for more details.",
"import re",
"from itertools import imap",
"__all__ = ['Markup', 'soft_unicode', 'escape', 'escape_silent']",
"_striptags_re = re.comp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.