本文整理汇总了Python中models.Token类的典型用法代码示例。如果您正苦于以下问题:Python Token类的具体用法?Python Token怎么用?Python Token使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Token类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: consumer_create
def consumer_create(request):
if request.method == "POST":
form = ConsumerCreateForm(request.POST)
if form.is_valid():
consumer = Consumer()
consumer.name = form.cleaned_data['name']
consumer.description = form.cleaned_data['description']
consumer.user_id = request.user.username
consumer.refresh_key_secret()
consumer.save()
token = Token()
token.key = Token.generate_token()
token.secret = Token.generate_token()
token.consumer = consumer
token.user = request.user.username
token.type = 'A'
token.save()
return HttpResponseRedirect('/accounts/profile')
else:
form = ConsumerCreateForm()
params = {'form': form}
return render_to_response('oauth/consumer_form.tpl', params,
context_instance=RequestContext(request))
示例2: save_token
def save_token(token, request, *args, **kwargs):
user = request.user
toks = Token.objects(
client_id=request.client.client_id,
user_id=user.id
)
# make sure that every client has only one token connected to a user
for t in toks:
t.delete()
expires_in = token.pop('expires_in')
expires = datetime.utcnow() + timedelta(seconds=expires_in)
tok = Token(
access_token=token['access_token'],
refresh_token=token['refresh_token'],
token_type=token['token_type'],
_scopes=token['scope'],
expires=expires,
client_id=request.client.client_id,
user_id=user.id,
user=user
)
tok.save()
return tok
示例3: get
def get(self):
apid = self.request.get("apid")
email = self.request.get("email",'').lower()
version = int(self.request.get("version", "0"))
q = Token.query(Token.email == email)
token = q.get()
if token:
token.apid = apid
token.email = email
token.version = version
else:
q = Token.query(Token.apid == apid)
token = q.get()
if token:
token.apid = apid
token.email = email
token.version=version
else:token = Token(apid=apid, email=email, version=version)
token.put()
cb = self.request.get('callback')
self.response.headers['Content-Type'] = 'application/json'
if cb:
self.response.out.write(cb+'(' + json.dumps({}) +');')
else:
self.response.out.write(json.dumps({}))
示例4: forward_token
def forward_token(request, token_str=None, **kwargs):
kwargs['extra_context'] = {}
error = None
token = get_object_or_404(Token, token=token_str)
user_tokens = get_tokens_from_cookie(request)
if not token.can_forward:
error = _("Apologies! This token can not be forwarded.")
else:
if request.user.is_staff:
pass
elif not token.token in user_tokens:
error = _("Apologies! You are not allowed to forward this token.")
kwargs['extra_context']['token'] = token
kwargs['extra_context']['error'] = error
if not error:
if request.method == 'POST':
form = ForwardProtectedURLForm(token, request.POST)
if form.is_valid():
if token.forward_count:
token.forward_count = token.forward_count - len(form.cleaned_data['emails'])
token.save()
for email in form.cleaned_data['emails']:
forwarded_token = Token( url=token.url, valid_until=token.valid_until, forward_count=0, email=email )
forwarded_token.save()
forwarded_token.send_token_email()
return HttpResponseRedirect(reverse('token_list'))
else:
form = ForwardProtectedURLForm(token)
kwargs['extra_context']['form'] = form
return direct_to_template(request, template='token_auth/forward_token.html', **kwargs)
示例5: post
def post(self):
user = self.current_user
desc = self.get_argument("description")
value = "%040x" % random.randrange(16 ** 40)
# TODO: Retry on duplicate token value (peewee.IntegrityError)?
Token.create(user=user, value=value, desc=desc)
self.redirect(self.reverse_url("web:settings"))
示例6: push_to_all
def push_to_all(text, count):
ios_tokens = Token.query(Token.os!='android').fetch()
and_tokens = Token.query(Token.os=='android').fetch()
for token in ios_tokens:
push_to_apns(token.token, text, count)
push_to_gcm(list(token.token for token in and_tokens), text, count)
示例7: regist_token
def regist_token(self, request):
if Token.query(Token.token==request.token).fetch():
return RegistTokenResult(result="DUP")
token = Token(token=request.token, os='ios');
token.put();
push_to(token, u"환영합니다! 벙커원 교회 주보 알림목록에 등록되었습니다!", 0)
return RegistTokenResult(result="OK")
示例8: email_key
def email_key(user):
token = Token(key=registration_key(),
email=user.email)
g = Global.objects()[0]
g.n_tokens += 1
g.save()
token.save()
body = "Hey! Create an account by clicking on the link below:"
body += "localhost:5000/createAccount?accountEmail={0}&signupToken={1}".format(user.email, token.key)
send_email("Lsten.fm, all the music.", body, user.email)
示例9: save_token
def save_token(self, session, user):
uid = user.username
try:
token = Token.objects.get(uid=uid, user=user)
except Exception:
token = Token(uid=uid, user=user)
token.access_token = session.access_token
token.expires = session.expires
token.save()
return token
示例10: _make_token_with_timestamp
def _make_token_with_timestamp(self, user, timestamp):
from django.utils.hashcompat import sha_constructor
hash = sha_constructor(settings.SECRET_KEY + unicode(user.id) +
user.password +
unicode(timestamp)).hexdigest()[::2]
self.delete_token(user)
token = Token(user = user, hash = hash)
token.save()
return hash
示例11: fs_request_token_ready
def fs_request_token_ready(request):
"""
OAuth dance for Foursquare, callback URL
"""
CONSUMER_KEY = FS_CONSUMER_KEY
CONSUMER_SECRET = FS_CONSUMER_SECRET
token = Token.gql( "WHERE user = :1", str(request.user) ).get()
request_values = token.fs_request_token.split("&")
env = os.environ['QUERY_STRING'].split("&")
for e in env:
request_values.append(e)
values = {}
for rv in request_values:
(key, value) = rv.split("=")
values[key] = value
oauth_token = oauth.OAuthToken.from_string( token.fs_request_token )
oauth_verifier = values['oauth_verifier']
request_token_key = oauth_token
request_token_secret = values['oauth_token_secret']
credentials = foursquare.OAuthCredentials(CONSUMER_KEY, CONSUMER_SECRET)
fs = foursquare.Foursquare(credentials)
user_token = fs.access_token(token=request_token_key, oauth_verifier=oauth_verifier)
credentials.set_access_token(user_token)
fs_token = "oauth_token_secret=%s&oauth_token=%s" % (request_token_secret, str(user_token))
token.fs_token = fs_token
token.fs_user_token = str(user_token)
token.put()
return redirect( "/" )
示例12: post
def post(self):
isajax = self.request.get('isajax')
phone = self.request.get('phone')
msg = self.request.get('msg')
contact_name = self.request.get('contact_name')
user = users.get_current_user()
email = user.email().lower()
q = Token.query(Token.email == email)
token = q.get()
status = 100
hist=''
logging.debug(email + ' ' + phone + ' ' + msg + ' ' + contact_name)
if token:
status = 101
if len(phone) and len(msg):
status = 200
hist = History(email=email, msg=msg, phone=phone, contact_name = contact_name)
hist.put()
airship.push({
"android": {
"extra": {"msgid": str(hist.key.id()), "phone": phone, "msg":msg}
}
}, apids=[token.apid])
id = hist.key.id()
hist = hist.to_dict()
hist['created']=hist['created'].isoformat();
hist['id'] = id
hist['type'] = 'sms'
self.response.out.write(json.dumps({'status':status, 'msg':hist}))
示例13: save_snippet
def save_snippet(node, page):
snippet = Snippet.create(
page=page,
text_above=extract_text_above(node),
text_below=extract_text_below(node),
header=extract_header_above(node),
code=extract_code(node),
line_count=len(node.text.split('\n')),
)
for tok_str in extract_tokens(node):
token, _ = Token.get_or_create(string=tok_str)
SnippetToken.create(
snippet=snippet,
token=token,
)
for comment_str in extract_comments(node):
comment, _ = Comment.get_or_create(string=comment_str)
SnippetComment.create(
snippet=snippet,
comment=comment,
)
return snippet
示例14: fetch_request_token
def fetch_request_token(self, oauth_consumer, oauth_callback):
logger.warning("!!! In MockOAuthDataStore.fetch_request_token args: %s"%locals())
if oauth_consumer.key != self.consumer.key:
raise OAuthError('Consumer key does not match.')
# OAuth 1.0a: if there is a callback, check its validity
callback = None
callback_confirmed = False
if oauth_callback:
if oauth_callback != OUT_OF_BAND:
if check_valid_callback(oauth_callback):
callback = oauth_callback
callback_confirmed = True
else:
raise oauth.OAuthError('Invalid callback URL.')
#not going to implement scope just yet-so just hard code this for now
resource = Resource.all().filter("name =","default")[0]
#try:
# resource = Resource.objects.get(name=self.scope)
#except:
# raise OAuthError('Resource %s does not exist.' % escape(self.scope))
self.request_token = Token.create_token(consumer=self.consumer,
token_type=Token.REQUEST,
timestamp=self.timestamp,
resource=resource,
callback=callback,
callback_confirmed=callback_confirmed)
return self.request_token
示例15: create_user
def create_user():
i = ctx.request.input(phone='',password='',code='')
phone = i.phone.strip()
password = i.password.strip()
code = i.code.strip()
verify = VerifyCode.find_first('where num=?', phone)
logging.info('the code %s and verify %s' %(code,verify))
if not verify or verify.code!=code:
raise APIError('register:failed','verify code','verify code is not correct.','-1')
if time.time() - verify.created_at > 90:
raise APIValueError('code',errcode='-3')
if not phone or not _RE_PHONE.match(phone):
raise APIValueError('phone',errcode='-1')
if not password:
raise APIValueError('password', errcode='-1')
verify.delete()
user = User.find_first('where phone=?',phone)
if user and user.valid==True:
raise APIError('register:failed','phone','phone is already in use.')
if user:
token = Token.find_first('where id=?', user.id)
if not token:
token_string = next_id()
token = Token(id = user.id, token1=token_string, token2 = token_string)
token.insert()
else:
token.token1 = next_id()
logging.info('the update token is %s' % token.token1)
token.update()
user.password = password
user.update()
user.token = token.token1
else:
user = User(phone=phone, valid=False, password=password)
user.insert()
token_string = next_id()
token = Token(id = user.id, token1=token_string, token2 = token_string)
token.insert()
user.token = token.token1
user.pop('id')
user.pop('password')
user.pop('created_at')
user.errcode='0'
return user