本文整理汇总了Python中social.utils.getRequestArg函数的典型用法代码示例。如果您正苦于以下问题:Python getRequestArg函数的具体用法?Python getRequestArg怎么用?Python getRequestArg使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getRequestArg函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _comment
def _comment(self, request, data=None):
authInfo = request.getSession(IAuthInfo)
myId = authInfo.username
orgId = authInfo.organization
convId, conv = data['parent']
fids = data['fId']
comment, snippet = data['comment']
review = data['_review']
itemId, convId, items, keywords = yield Item._comment(convId, conv, comment, snippet, myId, orgId, False, review, fids)
if keywords:
block = t.getBlock('item.mako', 'requireReviewDlg', keywords=keywords, convId=convId)
request.write('$$.convs.reviewRequired(%s, "%s");' % (json.dumps(block), convId))
return
# Finally, update the UI
entities = base.EntitySet([myId])
yield entities.fetchData()
args = {"entities": entities, "items": items, "me": entities[myId]}
numShowing = utils.getRequestArg(request, "nc") or "0"
numShowing = int(numShowing) + 1
responseCount = items[convId]['meta']['responseCount']
isItemView = (utils.getRequestArg(request, "_pg") == "/item")
t.renderScriptBlock(request, 'item.mako', 'conv_comments_head',
False, '#comments-header-%s' % (convId), 'set',
args=[convId, responseCount, numShowing, isItemView], **args)
onload = """(function(){$('.comment-input', '#comment-form-%s').val(''); $('[name=\"nc\"]', '#comment-form-%s').val('%s');})();$('#comment-attach-%s-uploaded').empty()""" % (convId, convId, numShowing, convId)
t.renderScriptBlock(request, 'item.mako', 'conv_comment', False,
'#comments-%s' % convId, 'append', True,
handlers={"onload": onload},
args=[convId, itemId], **args)
示例2: _uploadDone
def _uploadDone(self, request):
SKey = config.get('CloudFiles', 'SecretKey')
AKey = config.get('CloudFiles', 'AccessKey')
creds = AWSCredentials(AKey, SKey)
client = s3Client.S3Client(creds)
bucket = utils.getRequestArg(request, "bucket")
key = utils.getRequestArg(request, "key")
file_info = yield client.head_object(bucket, key)
tmp_files_info = {}
name = file_info['x-amz-meta-filename'][0]
size = file_info['content-length'][0]
fileType = file_info['content-type'][0]
fileId = file_info['x-amz-meta-fileid'][0]
val = "%s:%s:%s:%s" % (fileId, name, size, fileType)
filename = urlsafe_b64decode(name)
tmp_files_info[fileId] = [fileId, filename, size, fileType]
# XXX: We currently don't generate any thumbnails!
# yield threads.deferToThread(self._enqueueMessage, bucket, key, name, fileType)
yield db.insert(fileId, "tmp_files", val, "fileId")
response = """
<textarea data-type="application/json">
{"ok": true, "files": %s}
</textarea>
""" % (json.dumps(tmp_files_info))
request.write(response)
示例3: _renderKeywordMatches
def _renderKeywordMatches(self, request):
(appchange, script, args, myId) = yield self._getBasicArgs(request)
landing = not self._ajax
keyword = utils.getRequestArg(request, 'keyword')
if not keyword:
errors.MissingParams(['Keyword'])
args["keyword"] = keyword
start = utils.getRequestArg(request, "start") or ""
args["start"] = start
if script and landing:
t.render(request, "keyword-matches.mako", **args)
if script and appchange:
t.renderScriptBlock(request, "keyword-matches.mako", "layout",
landing, "#mainbar", "set", **args)
keywordItems = yield self._getKeywordMatches(request, keyword,
start=start)
args.update(keywordItems)
if script:
onload = "(function(obj){$$.convs.load(obj);})(this);"
t.renderScriptBlock(request, "keyword-matches.mako", "feed",
landing, "#convs-wrapper", "set", True,
handlers={"onload": onload}, **args)
if not script:
t.render(request, "keyword-matches.mako", **args)
示例4: _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'))
示例5: get
def get(self, request, entityId=None):
itemType = utils.getRequestArg(request, 'type')
start = utils.getRequestArg(request, 'start') or ''
more = utils.getRequestArg(request, 'more') or False
if more:
return self._renderMore(request, entityId, start, itemType)
else:
return self._render(request, entityId, start, itemType)
示例6: _getFileInfo
def _getFileInfo(self, request):
"""Fetch the meta info on a file that is being requested to be
downloaded. Returns the meta info of the file in question.
Keyword Arguments:
itemId: id of the conversation on which this file is attached.
attachmentId: id of the file on the amazon S3 that is to be served.
version: version of the file on the amazon S3 that the user is
requesting.
"""
authinfo = request.getSession(IAuthInfo)
myId = authinfo.username
myOrgId = authinfo.organization
itemId = utils.getRequestArg(request, "id", sanitize=False)
attachmentId = utils.getRequestArg(request, "fid", sanitize=False)
version = utils.getRequestArg(request, "ver", sanitize=False) or ''
columns = ["meta", "attachments", "participants"]
if not (itemId and attachmentId):
raise errors.MissingParams([])
item = yield db.get_slice(itemId, "mConversations", columns)
item = utils.supercolumnsToDict(item)
if not item:
raise errors.InvalidMessage(itemId)
if myId not in item.get('participants', {}):
raise errors.MessageAccessDenied(itemId)
# Check if the attachmentId belong to item
if attachmentId not in item['attachments'].keys():
raise errors.InvalidAttachment(itemId, attachmentId, version)
fileId, filetype, name = None, 'text/plain', 'file'
if version:
version = utils.decodeKey(version)
try:
cols = yield db.get(attachmentId, "attachmentVersions", version)
except ttypes.NotFoundException:
raise errors.InvalidAttachment(itemId, attachmentId, version)
except ttypes.InvalidRequestException:
raise errors.InvalidAttachment(itemId, attachmentId, version)
cols = utils.columnsToDict([cols])
else:
cols = yield db.get_slice(attachmentId, "attachmentVersions", count=1, reverse=True)
cols = utils.columnsToDict(cols)
version = cols.keys()[0]
fileId, name, size, filetype = cols[version].split(':')
files = yield db.get_slice(fileId, "files", ["meta"])
files = utils.supercolumnsToDict(files)
url = files['meta']['uri']
owner = files["meta"]["owner"]
defer.returnValue([owner, url, filetype, size, name])
示例7: _S3FormData
def _S3FormData(self, request):
(appchange, script, args, myId) = yield self._getBasicArgs(request)
landing = not self._ajax
myOrgId = args["orgId"]
SKey = config.get('CloudFiles', 'SecretKey')
AKey = config.get('CloudFiles', 'AccessKey')
domain = config.get('CloudFiles', 'Domain')
bucket = config.get('CloudFiles', 'Bucket')
if domain == "":
calling_format = SubdomainCallingFormat()
domain = "s3.amazonaws.com"
else:
calling_format = VHostCallingFormat()
conn = S3Connection(AKey, SKey, host=domain, is_secure=True,
calling_format=calling_format)
filename = utils.getRequestArg(request, "name") or None
#TODO:If name is None raise an exception
mime = utils.getRequestArg(request, "mime") or None
if mime:
if not mimetypes.guess_extension(mime):
mime = mimetypes.guess_type(filename)[0]
else:
mime = mimetypes.guess_type(filename)[0]
if not mime:
mime = "text/plain"
filename = urlsafe_b64encode(filename)
fileId = utils.getUniqueKey()
key = '%s/%s/%s' % (myOrgId, myId, fileId)
attachment_filename = 'attachment;filename=\"%s\"' % (filename)
x_conds = ['{"x-amz-meta-uid":"%s"}' % myId,
'{"x-amz-meta-filename":"%s"}' % filename,
'{"x-amz-meta-fileId":"%s"}' % fileId,
'{"content-type":"%s"}' % mime]
x_fields = [{"name":"x-amz-meta-uid", "value":"%s" % myId},
{"name":"x-amz-meta-filename", "value":"%s" % filename},
{"name":"content-type", "value":"%s" % mime},
{"name":"x-amz-meta-fileId", "value":"%s" % fileId}]
max_content_length = constants.MAX_FILE_SIZE
x_conds.append('["content-length-range", 0, %i]' % max_content_length)
redirect_url = config.get('General', 'URL') + "/files/update"
form_data = conn.build_post_form_args(bucket,
key,
http_method="https",
fields=x_fields,
conditions=x_conds,
success_action_redirect=redirect_url)
request.write(json.dumps([form_data]))
defer.returnValue(0)
示例8: _registerClient
def _registerClient(self, request):
(appchange, script, args, myId) = yield self._getBasicArgs(request)
landing = not self._ajax
myOrgId = args["orgId"]
name = utils.getRequestArg(request, "name")
desc = utils.getRequestArg(request, "desc")
scope = utils.getRequestArg(request, "scope", multiValued=True)
category = utils.getRequestArg(request, "category")
redirect = utils.getRequestArg(request, "redirect", sanitize=False)
if not name:
raise errors.MissingParams(["Name"])
if not scope:
raise errors.MissingParams(["Permissions"])
if category != "apikey" and not redirect:
raise errors.MissingParams(["Redirect URL"])
knownScopes = globals().get("scopes")
unknownScopes = [x for x in scope if x not in knownScopes.keys()]
if category not in ["webapp", "native", "apikey"] or unknownScopes:
raise errors.BaseError("Invalid value sent for Type/Permissions")
clientId = utils.getUniqueKey()
clientSecret = utils.getRandomKey()
meta = {
"author": myId,
"name": name,
"org": myOrgId,
"secret": utils.hashpass(clientSecret),
"scope": " ".join(scope),
"category": category,
}
if category != "apikey":
meta["redirect"] = b64encode(redirect)
meta["desc"] = desc
yield db.batch_insert(clientId, "apps", {"meta": meta})
yield db.insert(myId, "appsByOwner", "", clientId)
yield db.insert(myOrgId, "appsByOwner", "", clientId)
else:
yield db.batch_insert(clientId, "apps", {"meta": meta})
yield db.insert(myId, "entities", "", clientId, "apikeys")
self.setTitle(request, name)
args["clientId"] = clientId
args["client"] = meta
args["client"]["secret"] = clientSecret
t.renderScriptBlock(request, "apps.mako", "registrationResults", landing, "#apps-contents", "set", **args)
示例9: _signupGotUserData
def _signupGotUserData(self, request):
authinfo = yield defer.maybeDeferred(request.getSession, IAuthInfo)
if authinfo.username:
raise errors.InvalidRequest(_("Another user is currently signed-in. Please signout and then click the invitation link"))
emailId = utils.getRequestArg(request, "email")
token = utils.getRequestArg(request, "token")
valid = yield self._isValidToken(emailId, token)
if not valid:
raise InvalidRegistration("The invite is not valid anymore. Already registered?")
yield self._addUser(request)
示例10: renderResetPassword
def renderResetPassword(self, request):
email = utils.getRequestArg(request, 'email')
token = utils.getRequestArg(request, 'token')
if not (email and token):
raise MissingParams([''])
validEmail, tokens, deleteTokens, leastTimestamp = yield _getResetPasswordTokens(email)
# XXX: If not validEmail, send invite to the user
if not validEmail or token not in tokens:
raise PermissionDenied("Invalid token. <a href='/password/resend?email=%s'>Click here</a> to reset password" % (email))
args = {"view": "resetPassword", "email": email, "token": token}
t.render(request, "signup.mako", **args)
示例11: _events
def _events(self, request):
(appchange, script, args, myId) = yield self._getBasicArgs(request)
landing = not self._ajax
page = utils.getRequestArg(request, 'page') or '1'
entityId = utils.getRequestArg(request, 'id') or myId
view = utils.getRequestArg(request, 'view') or "agenda"
authinfo = request.getSession(IAuthInfo)
myOrgId = authinfo.organization
start = utils.getRequestArg(request, 'start') or ""
#Check if entity Id is my Org or a group that I have access to.
if entityId != myId and entityId != myOrgId:
yield utils.getValidEntityId(request, "id", "group")
if view == "invitations":
entityId = "%s:%s" %(myId, "I")
if page.isdigit():
page = int(page)
else:
page = 1
count = constants.EVENTS_PER_PAGE
try:
start = datetime.datetime.strptime(start, "%Y-%m-%d")
except ValueError:
start = None
args.update({'view':view, 'menuId': 'events'})
args.update({'page':page, 'entityId': entityId})
if script and landing:
t.render(request, "event.mako", **args)
if script and appchange:
t.renderScriptBlock(request, "event.mako", "layout",
landing, "#mainbar", "set", **args)
yield event.fetchMatchingEvents(request, args, entityId, count=count,
start=start)
if script:
onload = """
$$.menu.selectItem('events');
$$.events.prepareAgendaDatePicker('%s')
""" % (args["start"])
t.renderScriptBlock(request, 'event.mako', "render_events",
landing, ".center-contents", "set", True,
handlers={"onload": onload}, **args)
else:
t.render(request, "event.mako", **args)
示例12: _signupCheckToken
def _signupCheckToken(self, request):
authinfo = yield defer.maybeDeferred(request.getSession, IAuthInfo)
if authinfo.username:
raise errors.InvalidRequest(_("Another user is currently signed-in. Please signout and then click the invitation link"))
emailId = utils.getRequestArg(request, "email")
token = utils.getRequestArg(request, "token")
valid = yield self._isValidToken(emailId, token)
if not valid:
raise InvalidRegistration("The invite is not valid anymore. Already registered?")
args = {'emailId': emailId, 'token': token, 'view': 'userinfo'}
t.render(request, "signup.mako", **args)
示例13: render_GET
def render_GET(self, request):
segmentCount = len(request.postpath)
viewType = utils.getRequestArg(request, "type") or "all"
start = utils.getRequestArg(request, "start") or ""
start = utils.decodeKey(start)
d = None
if segmentCount == 0:
d = self._render(request, viewType, start)
elif segmentCount == 1 and self._ajax and request.postpath[0] == "invite":
d = self._renderInvitePeople(request)
elif segmentCount == 1 and request.postpath[0] == "suggestions":
d = self._renderSuggestions(request)
return self._epilogue(request, d)
示例14: _editCompany
def _editCompany(self, request):
(appchange, script, args, myId) = yield self._getBasicArgs(request)
remove = utils.getRequestArg(request, 'action') == 'd'
encodedCompanyId = utils.getRequestArg(request, 'id', sanitize=False)
companyId = utils.decodeKey(encodedCompanyId) if encodedCompanyId else None
if companyId and remove:
db.remove(myId, "entities", companyId, "companies")
request.write('$("#%s").remove();' % encodedCompanyId)
return
today = datetime.date.today()
try:
startYear = int(utils.getRequestArg(request, 'startyear'))
startMonth = int(utils.getRequestArg(request, 'startmonth'))
startDay = datetime.date(startYear, startMonth, 1)
except (ValueError, TypeError):
raise errors.InvalidRequest('Please give a valid start month and year')
try:
endYear = utils.getRequestArg(request, 'endyear')
if not endYear:
endYear = 9999
endMonth = 12
else:
endYear = int(endYear)
endMonth = int(utils.getRequestArg(request, 'endmonth'))
endDay = datetime.date(endYear, endMonth, 1)
except (ValueError, TypeError):
raise errors.InvalidRequest('Please give a valid end month and year')
if startDay > today or startDay > endDay or (endDay > today and endYear != 9999):
raise errors.InvalidRequest('The start month/year and end month/year are invalid!')
name = utils.getRequestArg(request, 'company')
title = utils.getRequestArg(request, 'title')
if not remove and not name:
errors.MissingParams(['Name'])
if companyId:
db.remove(myId, "entities", companyId, "companies")
newCompanyId = "%s%s:%s%s:%s" % (endYear, endMonth, startYear, startMonth, name)
newCompanyVal = title
db.insert(myId, "entities", newCompanyVal, newCompanyId, "companies")
if companyId:
yield t.renderScriptBlock(request, "settings.mako", "companyItem",
False, "#"+encodedCompanyId, "replace",
args=[newCompanyId, newCompanyVal])
else:
onload = """$('#company-empty-msg').remove();"""+\
"""$('#addemp-wrap').replaceWith('<div id="addemp-wrap"><button class="button ajax" id="addedu-button" data-ref="/settings/company">Add Company</button></div>');"""
yield t.renderScriptBlock(request, "settings.mako", "companyItem",
False, "#companies-wrapper", "append", True,
handlers={'onload': onload},
args=[newCompanyId, newCompanyVal])
示例15: _members
def _members(self, request):
"""Allow a participant of a conversation to add or remove another user
to the conversation.
Keyword arguments:
action: Either one of [add, remove]
convId: The conversation to which this user wants to either add or
remove another user.
"""
(appchange, script, args, myId) = yield self._getBasicArgs(request)
landing = not self._ajax
action = utils.getRequestArg(request, "action")
convId = utils.getRequestArg(request, 'parent') or None
if not convId:
raise errors.MissingParams([_('Conversation Id')])
if action not in ('add', 'remove'):
raise errors.InvalidRequest()
if action == "add":
yield self._addMembers(request)
elif action == "remove":
yield self._removeMembers(request)
cols = yield db.get_slice(convId, "mConversations")
conv = utils.supercolumnsToDict(cols)
participants = set(conv['participants'])
people = base.EntitySet(participants)
yield people.fetchData()
args.update({"people": people})
args.update({"conv": conv})
args.update({"id": convId})
args.update({"view": "message"})
if script:
onload = """
$('#conversation_add_member').autocomplete({
source: '/auto/users',
minLength: 2,
select: function( event, ui ) {
$('#conversation_recipients').attr('value', ui.item.uid)
}
});
"""
t.renderScriptBlock(request, "message.mako", "right",
landing, ".right-contents", "set", True,
handlers={"onload": onload}, **args)