本文整理汇总了Python中social._函数的典型用法代码示例。如果您正苦于以下问题:Python _函数的具体用法?Python _怎么用?Python _使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了_函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: removeAdmin
def removeAdmin(group, user, me):
"""strip admin privileges of user.
Throw an error if @me is not group-admin or is the only admin and
trying to removing self.
Raise an exception when user is not a group-memeber or not a group-admin.
Keyword params:
@me:
@user: user object
@group: group object
"""
if me.id not in group.admins:
raise errors.PermissionDenied(_('You are not an administrator of the group'))
if me.id == user.id and len(group.admins.keys()) == 1:
raise errors.InvalidRequest(_('You are the only administrator of the group'))
cols = yield db.get_slice(group.id, "groupMembers", [user.id])
if not cols:
raise errors.InvalidRequest(_("User is not a member of the group"))
if user.id not in group.admins:
raise errors.InvalidRequest(_('User is not administrator of the group'))
yield db.remove(group.id, "entities", user.id, "admins")
yield db.remove(user.id, "entities", group.id, "adminOfGroups")
开发者ID:psunkari,项目名称:flocked-in,代码行数:25,代码来源:Group.py
示例2: getValidEntityId
def getValidEntityId(request, arg, type="user", columns=None):
entityId = getRequestArg(request, arg, sanitize=False)
if not entityId:
raise errors.MissingParams([_("%s id") % _(type).capitalize()])
if not columns:
columns = []
columns.extend(["basic"])
entity = yield db.get_slice(entityId, "entities", columns)
if not entity:
raise errors.InvalidEntity(type, entityId)
entity = supercolumnsToDict(entity)
basic = entity["basic"]
if type != basic["type"]:
raise errors.InvalidEntity(type, entityId)
authinfo = request.getSession(IAuthInfo)
myOrgId = authinfo.organization
org = basic["org"] if basic["type"] != "org" else entityId
if myOrgId != org:
raise errors.EntityAccessDenied(type, entityId)
defer.returnValue((entityId, entity))
开发者ID:psunkari,项目名称:flocked-in,代码行数:25,代码来源:utils.py
示例3: _invite
def _invite(self, request):
src = utils.getRequestArg(request, 'from') or None
rawEmailIds = request.args.get('email')
stats = yield invite(request, rawEmailIds)
if not src:
src = "sidebar" if len(rawEmailIds) == 1 else "people"
if src == "sidebar" and self._ajax:
request.write("$('#invite-others').val('');")
elif src == "sidebar":
request.redirect('/feed/')
elif src == "people" and self._ajax:
pass
elif src == "people":
request.redirect('/people')
if not stats and self._ajax:
request.write("$$.alerts.error('%s');" \
% (_("Use company email addresses only.")))
elif stats and self._ajax:
if len(stats[0]) == 1:
request.write("$$.alerts.info('%s');" % _("Invitation sent"))
request.write("$$.dialog.close('invitepeople-dlg', true);")
elif len(stats[0]) > 1:
request.write("$$.alerts.info('%s');" % _("Invitations sent"))
request.write("$$.dialog.close('invitepeople-dlg', true);")
else:
#TODO: when user tries to send invitations to existing members,
# show these members as add-as-friend/follow list
request.write("$$.alerts.info('%s');\
$$.dialog.close('invitepeople-dlg', true);" \
% _("Invitations sent"))
开发者ID:psunkari,项目名称:flocked-in,代码行数:31,代码来源:people.py
示例4: untag
def untag(itemId, item, tagId, tag, myId, orgId):
if "parent" in item:
raise errors.InvalidRequest(_("Tags cannot be applied or removed from comments"))
if tagId not in item.get("tags", {}):
raise errors.InvalidRequest(_("No such tag on the item")) # No such tag on item
d1 = db.remove(itemId, "items", tagId, "tags")
d2 = db.remove(tagId, "tagItems", item["meta"]["uuid"])
d3 = db.get_slice(tagId, "tagFollowers")
try:
itemsCountCol = yield db.get(orgId, "orgTags", "itemsCount", tagId)
tagItemsCount = int(itemsCountCol.column.value) - 1
if tagItemsCount % 10 == 7:
tagItemsCount = yield db.get_count(tagId, "tagItems")
tagItemsCount = tagItemsCount - 1
db.insert(orgId, "orgTags", "%s" % tagItemsCount, "itemsCount", tagId)
except ttypes.NotFoundException:
pass
result = yield defer.DeferredList([d1, d2, d3])
followers = utils.columnsToDict(result[2][1]).keys()
feedUpdateVal = "T:%s:%s::%s" % (myId, itemId, tagId)
yield Feed.unpush(myId, orgId, itemId, item,
feedUpdateVal, followers + [myId])
开发者ID:psunkari,项目名称:flocked-in,代码行数:27,代码来源:item.py
示例5: _attendance
def _attendance(self, request):
itemId, item = yield utils.getValidItemId(request, "id",
columns=["invitees"])
list_type = utils.getRequestArg(request, 'type') or "yes"
user_list = []
if itemId and list_type in ["yes", "no", "maybe"]:
cols = yield db.get_slice(itemId, "eventResponses")
res = utils.columnsToDict(cols)
for rsvp in res.keys():
resp = rsvp.split(":")[0]
uid = rsvp.split(":")[1]
if resp == list_type:
if uid in item["invitees"] and \
item["invitees"][uid] == list_type:
user_list.insert(0, uid)
else:
user_list.append(uid)
invited = user_list
owner = item["meta"].get("owner")
entities = base.EntitySet(invited+[owner])
yield entities.fetchData()
args = {"users": invited, "entities": entities}
args['title'] = {"yes":_("People attending this event"),
"no": _("People not attending this event"),
"maybe": _("People who may attend this event")
}[list_type]
t.renderScriptBlock(request, "item.mako", "userListDialog", False,
"#invitee-dlg-%s"%(itemId), "set", **args)
开发者ID:psunkari,项目名称:flocked-in,代码行数:33,代码来源:event.py
示例6: delete
def delete(itemId, item, myId, orgId):
convId = item["meta"].get("parent", itemId)
itemOwnerId = item["meta"]["owner"]
if itemId == convId:
conv = item
convOwnerId = itemOwnerId
else:
conv = yield db.get_slice(convId, "items", ["meta", "tags"])
conv = utils.supercolumnsToDict(conv)
if not conv:
raise errors.InvalidRequest(_('Conversation does not exist!'))
convOwnerId = conv["meta"]["owner"]
# TODO: Admin actions.
# Do I have permission to delete the comment
if (itemOwnerId != myId and convOwnerId != myId):
raise errors.PermissionDenied(_("You must either own the comment or the conversation to delete this comment"))
deferreds = []
convType = conv["meta"].get('type', 'status')
convACL = conv["meta"]["acl"]
timestamp = str(int(time.time()))
itemUUID = item["meta"]["uuid"]
# The conversation is lazy deleted.
# If it is the comment being deleted, rollback all feed updates
# that were made due to this comment and likes on this comment.
d = deleteItem(itemId, myId, orgId, item, conv)
deferreds.append(d)
yield defer.DeferredList(deferreds)
defer.returnValue(conv)
开发者ID:psunkari,项目名称:flocked-in,代码行数:34,代码来源:item.py
示例7: renderFeedSideBlock
def renderFeedSideBlock(self, request, landing, entityId, args):
authinfo = request.getSession(IAuthInfo)
myId = authinfo.username
myOrgId = authinfo.organization
groupId = args["groupId"] if "groupId" in args else None
if entityId == myOrgId:
args["title"] = _("Company Wide Events")
yield event.fetchMatchingEvents(request, args, myOrgId)
t.renderScriptBlock(request, "event.mako", "side_agenda",
landing, "#feed-side-block-container",
"append", **args)
elif entityId == myId:
args["title"] = _("My Upcoming Events")
yield event.fetchMatchingEvents(request, args, myId)
t.renderScriptBlock(request, "event.mako", "side_agenda",
landing, "#feed-side-block-container",
"append", **args)
elif entityId == groupId:
args["title"] = _("Group Agenda")
groupId = args["groupId"]
yield event.fetchMatchingEvents(request, args, groupId)
t.renderScriptBlock(request, "event.mako", "side_agenda",
landing, "#feed-side-block-container",
"append", **args)
开发者ID:psunkari,项目名称:flocked-in,代码行数:25,代码来源:event.py
示例8: tag
def tag(itemId, item, tagName, myId, orgId):
if "parent" in item["meta"]:
raise errors.InvalidRequest(_("Tag cannot be applied on a comment"))
(tagId, tag) = yield tags._ensureTag(tagName, myId, orgId)
if tagId in item.get("tags", {}):
raise errors.InvalidRequest(_("Tag already exists on the choosen item"))
d1 = db.insert(itemId, "items", myId, tagId, "tags")
d2 = db.insert(tagId, "tagItems", itemId, item["meta"]["uuid"])
d3 = db.get_slice(tagId, "tagFollowers")
tagItemsCount = int(tag.get("itemsCount", "0")) + 1
if tagItemsCount % 10 == 7:
tagItemsCount = yield db.get_count(tagId, "tagItems")
tagItemsCount += 1
db.insert(orgId, "orgTags", "%s" % tagItemsCount, "itemsCount", tagId)
result = yield defer.DeferredList([d1, d2, d3])
followers = utils.columnsToDict(result[2][1]).keys()
if followers:
timeUUID = uuid.uuid1().bytes
feedUpdateVal = "T:%s:%s::%s" % (myId, itemId, tagId)
yield Feed.push(myId, orgId, itemId, item, timeUUID,
feedUpdateVal, feeds=followers)
defer.returnValue((tagId, tag))
开发者ID:psunkari,项目名称:flocked-in,代码行数:28,代码来源:item.py
示例9: unsubscribe
def unsubscribe(request, group, user):
"""Unsubscribe @user from @group.
Remove the user from group-followers, group from user-groups,
create a group-leave activity item and push item to group-followers
and group feed. Remove the group from user display name indices.
Raises an error if user is not member of group or when
user is the only administrator of the group.
keyword params:
@user: entity object of user
@group: entity object of the group
@request:
"""
try:
yield db.get(group.id, "groupMembers", user.id)
except ttypes.NotFoundException:
raise errors.InvalidRequest(_("You are not a member of the group"))
if len(getattr(group, 'admins', {}).keys()) == 1 \
and user.id in group.admins:
raise errors.InvalidRequest(_("You are the only administrator of this group"))
colname = _entityGroupMapColName(group)
itemType = "activity"
responseType = "I"
itemId = utils.getUniqueKey()
acl = {"accept": {"groups": [group.id]}}
_acl = pickle.dumps(acl)
item = yield utils.createNewItem(request, itemType, user,
acl, "groupLeave")
item["meta"]["target"] = group.id
d1 = db.remove(group.id, "followers", user.id)
d2 = db.remove(user.id, "entityGroupsMap", colname)
d3 = db.batch_insert(itemId, 'items', item)
d4 = db.remove(group.id, "groupMembers", user.id)
d5 = feed.pushToOthersFeed(user.id, user.basic['org'],
item["meta"]["uuid"], itemId, itemId, _acl,
responseType, itemType, user.id,
promoteActor=False)
d6 = utils.updateDisplayNameIndex(user.id, [group.id], None,
user.basic['name'])
deferreds = [d1, d2, d3, d4, d5, d6]
if user.id in group.admins:
d7 = db.remove(group.id, "entities", user.id, "admins")
d8 = db.remove(user.id, "entities", group.id, "adminOfGroups")
deferreds.extend([d7, d8])
yield defer.DeferredList(deferreds)
开发者ID:psunkari,项目名称:flocked-in,代码行数:52,代码来源:Group.py
示例10: _likes
def _likes(self, request, data=None):
itemId, item = data['id']
entities, users = yield Item.likes(itemId, item)
args = {"users": users, "entities": entities}
if not users:
raise errors.InvalidRequest(_("Currently, no one likes the item"))
itemType = item['meta'].get('type', 'comment')
ownerId = item["meta"]["owner"]
args['title'] = _("People who like %s's %s") %\
(utils.userName(ownerId, entities[ownerId]), _(itemType))
t.renderScriptBlock(request, "item.mako", "userListDialog", False,
"#likes-dlg-%s" % (itemId), "set", **args)
开发者ID:psunkari,项目名称:flocked-in,代码行数:13,代码来源:item.py
示例11: createNewItem
def createNewItem(request, itemType, owner, acl=None, subType=None, groupIds=None, richText=False):
if not acl:
acl = getRequestArg(request, "acl", sanitize=False)
try:
acl = json.loads(acl)
orgs = acl.get("accept", {}).get("orgs", [])
if len(orgs) > 1 or (len(orgs) == 1 and orgs[0] != owner.basic["org"]):
msg = "Cannot grant access to other orgs on this item"
raise errors.PermissionDenied(_(msg))
except:
acl = {"accept": {"orgs": [owner.basic["org"]]}}
accept_groups = acl.get("accept", {}).get("groups", [])
deny_groups = acl.get("deny", {}).get("groups", [])
groups = [x for x in accept_groups if x not in deny_groups]
if groups:
relation = Relation(owner.id, [])
yield relation.initGroupsList()
if not all([x in relation.groups for x in groups]):
msg = "Only group members can post to a group"
raise errors.PermissionDenied(_(msg))
acl = pickle.dumps(acl)
item = {
"meta": {
"acl": acl,
"org": owner.basic["org"],
"type": itemType,
"uuid": uuid.uuid1().bytes,
"owner": owner.id,
"timestamp": str(int(time.time())),
"richText": str(richText),
},
"followers": {owner.id: ""},
}
if subType:
item["meta"]["subType"] = subType
if groups:
item["meta"]["target"] = ",".join(groups)
tmpFileIds = getRequestArg(request, "fId", False, True)
attachments = {}
if tmpFileIds:
attachments = yield _upload_files(owner.id, tmpFileIds)
if attachments:
item["attachments"] = {}
for attachmentId in attachments:
fileId, name, size, ftype = attachments[attachmentId]
item["attachments"][attachmentId] = "%s:%s:%s" % (name, size, ftype)
defer.returnValue(item)
开发者ID:psunkari,项目名称:flocked-in,代码行数:51,代码来源:utils.py
示例12: block
def block(group, user, me):
"""Block user from joining a group/ sending further group-join requests.
Keyword params:
@me: entity object with my info
@user: entity object of the user
@group: entity object of the group
"""
if me.id not in group.admins:
raise errors.PermissionDenied('Access Denied')
if me.id == user.id:
raise errors.InvalidRequest(_("An administrator cannot ban himself/herself from the group"))
try:
yield db.get(group.id, "pendingConnections", "GI:%s" % (user.id))
yield _removeFromPending(group, user)
# Add user to blocked users
yield db.insert(group.id, "blockedUsers", '', user.id)
defer.returnValue(True)
except ttypes.NotFoundException:
# If the users is already a member, remove the user from the group
colname = _entityGroupMapColName(group)
yield db.remove(group.id, "groupMembers", user.id)
yield db.remove(group.id, "followers", user.id)
yield db.remove(user.id, "entityGroupsMap", colname)
# Add user to blocked users
yield db.insert(group.id, "blockedUsers", '', user.id)
defer.returnValue(False)
开发者ID:psunkari,项目名称:flocked-in,代码行数:29,代码来源:Group.py
示例13: _create
def _create(self, request, data=None):
authInfo = request.getSession(IAuthInfo)
myId = authInfo.username
name = data['name']
description = data['desc']
access = data['access']
dp = data['dp']
me = base.Entity(myId)
yield me.fetchData()
try:
yield Group.create(request, me, name, access, description, dp)
except errors.InvalidGroupName as e:
request.write("<script> parent.$$.alerts.error('Group with same name already exists.'); </script>")
raise e
response = """
<script>
parent.$$.alerts.info('%s');
parent.$.get('/ajax/notifications/new');
parent.$$.fetchUri('/groups');
parent.$$.dialog.close('addgroup-dlg', true);
</script>
""" % (_("Group Created"))
request.write(response)
开发者ID:psunkari,项目名称:flocked-in,代码行数:25,代码来源:groups.py
示例14: getValidItemId
def getValidItemId(request, arg, type=None, columns=None, itemId=None, myOrgId=None, myId=None):
if not itemId:
itemId = getRequestArg(request, arg, sanitize=False)
itemType = type if type else "item"
if not itemId:
raise errors.MissingParams([_("%s id") % _(itemType).capitalize()])
columns = [] if not columns else columns
columns.extend(["meta", "attachments"])
item = yield db.get_slice(itemId, "items", columns)
if not item:
raise errors.InvalidItem(itemType, itemId)
item = supercolumnsToDict(item)
meta = item["meta"]
if type and meta["type"] != type:
raise errors.InvalidItem(itemType, itemId)
parentId = meta.get("parent", None)
if parentId:
parent = yield db.get_slice(parentId, "items", ["meta"])
parent = supercolumnsToDict(parent)
acl = parent["meta"]["acl"]
owner = parent["meta"]["owner"]
deleted = parent["meta"].get("state", None) == "deleted"
else:
parent = item
acl = meta["acl"]
owner = meta["owner"]
deleted = parent["meta"].get("state", None) == "deleted"
if deleted:
raise errors.InvalidItem(itemType, itemId)
if not myOrgId:
myOrgId = request.getSession(IAuthInfo).organization
if not myId:
myId = request.getSession(IAuthInfo).username
relation = Relation(myId, [])
yield relation.initGroupsList()
if not checkAcl(myId, myOrgId, False, relation, parent["meta"]):
raise errors.ItemAccessDenied(itemType, itemId)
defer.returnValue((itemId, item))
开发者ID:psunkari,项目名称:flocked-in,代码行数:47,代码来源:utils.py
示例15: _changePassword
def _changePassword(self, request):
(appchange, script, args, myId) = yield self._getBasicArgs(request)
currentPass = utils.getRequestArg(request, "curr_passwd", sanitize=False)
newPass = utils.getRequestArg(request, "passwd1", sanitize=False)
rptPass = utils.getRequestArg(request, "passwd2", sanitize=False)
if not currentPass:
request.write('$$.alerts.error("%s");' % _("Enter your current password"))
defer.returnValue(None)
if not newPass:
request.write('$$.alerts.error("%s");' % _("Enter new password"))
defer.returnValue(None)
if not rptPass:
request.write('$$.alerts.error("%s");' % _("Confirm new password"))
defer.returnValue(None)
if newPass != rptPass:
request.write('$$.alerts.error("%s");' % _("Passwords do not match"))
defer.returnValue(None)
if currentPass == newPass:
request.write('$$.alerts.error("%s");' % _("New password should be different from current password"))
defer.returnValue(None)
emailId = args["me"].basic["emailId"]
col = yield db.get(emailId, "userAuth", "passwordHash")
storedPass= col.column.value
if not utils.checkpass(currentPass, storedPass):
request.write('$$.alerts.error("%s");' % _("Incorrect Password"))
defer.returnValue(None)
newPasswd = utils.hashpass(newPass)
yield db.insert(emailId, "userAuth", newPasswd, "passwordHash")
request.write('$$.alerts.info("%s");' % _('Password changed'))
开发者ID:psunkari,项目名称:flocked-in,代码行数:34,代码来源:settings.py
示例16: _editWorkInfo
def _editWorkInfo(self, request):
# Contact information at work.
myId = request.getSession(IAuthInfo).username
orgId = request.getSession(IAuthInfo).organization
me = base.Entity(myId)
yield me.fetchData([])
data = {}
to_remove = []
for field in ["phone", "mobile"]:
val = utils.getRequestArg(request, field)
if val:
data[field] = val
else:
to_remove.append(field)
if 'phone' in data and not re.match('^\+?[0-9x\- ]{5,20}$', data['phone']):
raise errors.InvalidRequest(_('Phone numbers can only have numerals, hyphens, spaces and a plus sign'))
if 'mobile' in data and not re.match('^\+?[0-9x\- ]{5,20}$', data['mobile']):
raise errors.InvalidRequest(_('Phone numbers can only have numerals, hyphens, spaces and a plus sign'))
if data:
yield db.batch_insert(myId, "entities", {"contact": data})
if to_remove:
yield db.batch_remove({"entities":[myId]}, names=to_remove, supercolumn='contact')
contactInfo = me.get('contact', {})
if any([contactInfo.get(x, None) != data.get(x, None) for x in ["phone", "mobile"]]):
request.write('$$.alerts.info("%s");' % _('Profile updated'))
args = {"detail": "", "me": me}
suggestedSections = yield self._checkProfileCompleteness(request, myId, args)
tmp_suggested_sections = {}
for section, items in suggestedSections.iteritems():
if len(suggestedSections[section]) > 0:
tmp_suggested_sections[section] = items
args.update({'suggested_sections':tmp_suggested_sections})
t.renderScriptBlock(request, "settings.mako", "right",
False, ".right-contents", "set", **args)
me.update({'contact':data})
yield search.solr.updatePeopleIndex(myId, me, orgId)
开发者ID:psunkari,项目名称:flocked-in,代码行数:44,代码来源:settings.py
示例17: _render
def _render(self, request, viewType, start):
(appchange, script, args, myId) = yield self._getBasicArgs(request)
landing = not self._ajax
orgId = args["orgId"]
args["entities"] = {}
args["menuId"] = "people"
if script and landing:
t.render(request, "people.mako", **args)
if script and appchange:
t.renderScriptBlock(request, "people.mako", "layout",
landing, "#mainbar", "set", **args)
d = None
if viewType == "all":
d = getPeople(myId, orgId, orgId, start=start, fetchBlocked=False)
elif viewType == "invitations":
d = _getInvitationsSent(myId, start=start)
else:
raise errors.InvalidRequest(_("Unknown view type"))
sentInvitationsCount = yield db.get_count(myId, "invitationsSent")
if viewType == 'all':
users, relations, userIds,\
blockedUsers, nextPageStart, prevPageStart = yield d
# First result tuple contains the list of user objects.
args["entities"] = users
args["relations"] = relations
args["people"] = userIds
elif viewType == 'invitations':
emailIds, prevPageStart, nextPageStart = yield d
args['emailIds'] = emailIds
# display the invitations tab only when there are invitations sent or
# when user explicitly checks for viewType "invitations"
showInvitationsTab = sentInvitationsCount > 0 or viewType == 'invitations'
args["nextPageStart"] = nextPageStart
args["prevPageStart"] = prevPageStart
args["viewType"] = viewType
args['showInvitationsTab'] = showInvitationsTab
if script:
t.renderScriptBlock(request, "people.mako", "viewOptions",
landing, "#people-view", "set", args=[viewType],
showInvitationsTab=showInvitationsTab)
t.renderScriptBlock(request, "people.mako", "listPeople",
landing, "#users-wrapper", "set", **args)
t.renderScriptBlock(request, "people.mako", "paging",
landing, "#people-paging", "set", **args)
if not script:
t.render(request, "people.mako", **args)
开发者ID:psunkari,项目名称:flocked-in,代码行数:56,代码来源:people.py
示例18: makeAdmin
def makeAdmin(request, group, user, me):
"""make user admin of the group.
Only an group-administrator can make an group-member and administrator.
Keyword params:
@request:
@me:
@user: user object
@group: group object
"""
if me.id not in group.admins:
raise errors.PermissionDenied(_('You are not an administrator of the group'))
cols = yield db.get_slice(group.id, "groupMembers", [user.id])
if not cols:
raise errors.InvalidRequest(_('Only group member can become administrator'))
if user.id in group.admins:
defer.returnValue(None)
yield db.insert(group.id, "entities", '', user.id, 'admins')
yield db.insert(user.id, "entities", group.basic['name'],
group.id, "adminOfGroups")
itemType = "activity"
responseType = "I"
acl = {"accept": {"groups": [group.id]}}
_acl = pickle.dumps(acl)
itemId = utils.getUniqueKey()
item = yield utils.createNewItem(request, "activity", user,
acl, "groupAdmin")
item["meta"]["target"] = group.id
d1 = db.batch_insert(itemId, 'items', item)
d2 = feed.pushToFeed(group.id, item["meta"]["uuid"], itemId,
itemId, responseType, itemType, user.id)
d3 = feed.pushToOthersFeed(user.id, user.basic['org'],
item["meta"]["uuid"], itemId, itemId,
_acl, responseType, itemType,
user.id, promoteActor=False)
yield defer.DeferredList([d1, d2, d3])
开发者ID:psunkari,项目名称:flocked-in,代码行数:43,代码来源:Group.py
示例19: _addKeywords
def _addKeywords(self, request):
orgId = request.getSession(IAuthInfo).organization
original = utils.getRequestArg(request, 'keywords', sanitize=False)
if not original:
return
original = original.split(',')
decoded = set([x.decode('utf-8', 'replace').strip() for x in original])
# Check if any word is longer than 50 chars
decoded = set([x for x in decoded if len(x) < 50])
if len(decoded) != len(original):
raise errors.InvalidRequest(_('Keywords cannot be more than 50 characters long'))
# Check if any word has invalid characters
decoded = set([x for x in decoded if regex.match('^[\w-]*$', x)])
if len(decoded) != len(original):
raise errors.InvalidRequest(_('Keywords can only include numerals, alphabet and hyphens (-)'))
# Convert to lower case
decoded = set([x.lower() for x in decoded])
# Remove stopwords
keywords = set([x.encode('utf-8') for x in decoded\
if x not in stopwords.words()])
# After all this if we still have words, add them to database
if keywords:
for keyword in keywords:
yield db.insert(orgId, "keywords", '', keyword)
yield db.insert(orgId, "originalKeywords", '', keyword)
keywords = yield db.get_slice(orgId, "originalKeywords", count=100)
keywords = utils.columnsToDict(keywords, ordered=True)
args = {'keywords': keywords}
t.renderScriptBlock(request, "admin.mako", "listKeywords",
False, "#content", "set", **args)
# We may want to display an error when we removed stopwords.
if len(keywords) < len(decoded):
pass
开发者ID:psunkari,项目名称:flocked-in,代码行数:42,代码来源:admin.py
示例20: decodeKey
def decodeKey(key):
if not key.startswith("xX"):
return key
length = len(key) - 2
try:
decoded_key = base64.urlsafe_b64decode(key[2:] + ((length % 4) * "="))
except TypeError:
raise errors.InvalidRequest(_("Invalid Key"))
else:
return decoded_key
开发者ID:psunkari,项目名称:flocked-in,代码行数:11,代码来源:utils.py
注:本文中的social._函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论