• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python models.Token类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中models.Token的典型用法代码示例。如果您正苦于以下问题:Python Token类的具体用法?Python Token怎么用?Python Token使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Token类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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))
开发者ID:danggo,项目名称:caucse_api,代码行数:26,代码来源:views.py


示例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
开发者ID:yakinaround,项目名称:myadventure-api,代码行数:25,代码来源:validators.py


示例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({}))
开发者ID:spicavigo,项目名称:onlinesms_server,代码行数:26,代码来源:hello_world.py


示例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)
开发者ID:marauder37,项目名称:django-token-auth,代码行数:30,代码来源:views.py


示例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"))
开发者ID:SemanticMultimedia,项目名称:tlr,代码行数:7,代码来源:web.py


示例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)
开发者ID:bluedisk,项目名称:bunker1_endpoint,代码行数:9,代码来源:push.py


示例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")
开发者ID:bluedisk,项目名称:bunker1_endpoint,代码行数:10,代码来源:weekly_api.py


示例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)
开发者ID:mcherkassky,项目名称:listen,代码行数:11,代码来源:registration.py


示例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
开发者ID:matheussl,项目名称:django-fukinbook,代码行数:11,代码来源:backends.py


示例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
开发者ID:shebson,项目名称:django-expiring-tokens,代码行数:12,代码来源:tokens.py


示例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( "/" )
开发者ID:johl,项目名称:FireCheckIn,代码行数:28,代码来源:views.py


示例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}))
开发者ID:spicavigo,项目名称:onlinesms_server,代码行数:30,代码来源:hello_world.py


示例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
开发者ID:andrewhead,项目名称:StackSkim,代码行数:26,代码来源:get_snippets.py


示例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
开发者ID:cloudappsetup,项目名称:appengine_oauth_provider,代码行数:33,代码来源:stores.py


示例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
开发者ID:saltdealer,项目名称:space,代码行数:47,代码来源:urls.py


示例16: createProject

def createProject(request):

  pd = ocpcaproj.OCPCAProjectsDB()  

  if request.method == 'POST':
    if 'createproject' in request.POST:

      form = ProjectForm(request.POST)
      
# RBRM I think this is not right.  Omit and delete by 8/1.   6/9/15
#      # restrict datasets to user visible fields
#      form.fields['dataset'].queryset = Dataset.objects.filter(user_id=request.user.id) | Dataset.objects.filter(public=1)

      if form.is_valid():
        new_project=form.save(commit=False)
        new_project.user_id=request.user.id
        if request.POST.get('legacy') == 'yes':
          new_project.ocp_version='0.0'
        else:
          new_project.ocp_version=OCP_VERSION
        new_project.schema_version=SCHEMA_VERSION
        new_project.save()
        try:
          # create a database when not linking to an existing databases
          if not request.POST.get('nocreate') == 'on':
            pd.newOCPCAProject( new_project.project_name )
          if 'token' in request.POST:
            tk = Token ( token_name = new_project.project_name, token_description = 'Default token for public project', project_id=new_project, user_id=request.user.id, public=new_project.public ) 
            tk.save()

          ## RBTODO create a default channel

        except Exception, e:
          logger.error("Failed to create project.  Error {}".format(e))
          messages.error(request,"Failed to create project Error {}".format(e))

        return HttpResponseRedirect(get_script_prefix()+'ocpuser/projects/')
      else:
        context = {'form': form}
        return render_to_response('createproject.html',context,context_instance=RequestContext(request))

    else:
      #default
      return redirect(getProjects)
开发者ID:felipebetancur,项目名称:open-connectome,代码行数:44,代码来源:views.py


示例17: save_token

def save_token(token, request, *args, **kwargs):
    # app.logger.debug('save_token')
    #toks = db.session.query(Token).filter_by(client_id=request.client.client_id,
    #                             user_id=request.user.id).all()
    #app.logger.debug('client_id={client_id}, user_id={user_id}'.format(client_id=request.client.client_id, user_id=request.user.id))
    #app.logger.debug(toks)
    ## make sure that every client has only one token connected to a user
    #db.session.delete(toks)

    expires_in = token.pop('expires_in')
    expires = datetime.utcnow() + timedelta(seconds=expires_in)

    # app.logger.debug(token)

    #from pprint import pprint
    # import pprint
    # from inspect import getmembers
    #
    # pp = pprint.PrettyPrinter(indent=4)
    #
    # app.logger.debug('=' * 80)
    # app.logger.debug(pp.pformat(getmembers(request)))
    # app.logger.debug('=' * 80)
    # app.logger.debug(pp.pformat(getmembers(current_user)))
    # app.logger.debug('=' * 80)
    #app.logger.debug(current_user.dir())
    tok = Token(**token)
    tok.expires = expires
    tok.client_id = request.client.client_id

    if not request.user:
        tok.user_id = current_user.id
    else:
        tok.user_id = request.user.id

        #if hasattr(request, 'user'):
        #tok.user_id = request.user.id
        #elif current_user.id:
        #tok.user_id = current_user.id
    #tok.user_id = current_user.id
    db.session.add(tok)
    db.session.commit()
    return tok
开发者ID:yoophi,项目名称:today-api,代码行数:43,代码来源:app.py


示例18: render_index

def render_index(request, template):
    """
    Render the single landing page we have in FireCheckIn. Fill in information on the state
    of the connections to Fire Eagle and Foursquare and see if the user is logged in.
    """
    fireeagle_connected = False
    foursquare_connected = False
    if request.user.is_anonymous():
        return render_to_response(template,  { 'fireeagle_connected': fireeagle_connected,
                                                 'foursquare_connected': foursquare_connected})
    else:
        if ( Token.gql( "WHERE user = :1", str(request.user) ).get() != None ):
              token = Token.gql( "WHERE user = :1", str(request.user) ).get()
              if ( token.fe_token ):
                  fireeagle_connected = True
              if ( token.fs_token ):
                  foursquare_connected = True
        return render_to_response(template,  { 'fireeagle_connected': fireeagle_connected,
                                                 'foursquare_connected': foursquare_connected})
开发者ID:johl,项目名称:FireCheckIn,代码行数:19,代码来源:views.py


示例19: register

def register(request):
    info = ''
    if request.method == 'POST':
        form = CustomerRegisterForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            if Customer.objects.filter(email= email).count() == 0:
                customer = form.save()
                customer.save()
                token = Token(token = utility.generate_token(), customer = customer)
                token.save()
                content = '''<!DOCTYPE HTML><html><head><meta charset="utf-8"><title>Guo Hao Hotel注册验证</title></head><body><a href='http://10.131.255.124/account/%s/'>激活</a></body></html>'''
                utility.send_mail(customer.email, 'GuoHaoHotel', content % token.token)
                info = '已经发送一封邮件至%s,请点击链接激活账户' % customer.email
            else:
                info = '邮箱已经注册!'
    elif request.method == 'GET':
        form = CustomerRegisterForm()
    return render(request, 'register.html', {'form' : form, 'info' : info})
开发者ID:vaputa,项目名称:chain-hotel-book-system,代码行数:19,代码来源:views.py


示例20: deleteme

def deleteme(request):
    """
    Remove the currently logged in user from our database and log them out. 
    Privacy, you know? Don't request this casually :)
    """
    if (not (request.user.is_anonymous())):
        logout = users.create_logout_url( "/" )
        db.delete(Token.gql( "WHERE user = :1", str(request.user) ).get())
        return redirect( logout )
    else:
        return redirect( "/" )
开发者ID:johl,项目名称:FireCheckIn,代码行数:11,代码来源:views.py



注:本文中的models.Token类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python models.Topic类代码示例发布时间:2022-05-27
下一篇:
Python models.Todo类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap