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

Python model.User类代码示例

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

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



在下文中一共展示了User类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: __init__

class Single:
  def __init__(self, client):
    self.model = User(client, bcrypt)

  def on_get(self, req, resp, user_id):
    if authorize_as(req.auth, 'developer'):
      resource = self.model.find(user_id)
      if resource != None:
        resp.body = dumps(resource)
      else:
        resp.status = HTTP_404
    else:
      raise HTTPUnauthorized('unautharized', 'unautharized')

  def on_put(self, req, resp, user_id):
    try:
      if(authorize_as(req.auth, 'developer')):
        is_dev = True
    except:
      is_player = authorize_as(req.auth, 'player')
      is_dev = False
      if not is_player:
        raise HTTPUnauthorized('unautharized', 'unautharized')

    body = loads(req.stream.read().decode('utf-8'))
    resource = self.model.update(body, user_id, is_dev)
    if resource.modified_count == 1:
      resp.status = HTTP_204
    else:
      raise HTTPBadRequest('failed to update resource',
                           'a resource with id: ' + user_id + ' was not found')
开发者ID:monster-club,项目名称:trainer-card,代码行数:31,代码来源:Single.py


示例2: get

 def get(self, user_email):
   flow = createFlow(self, user_email)
   credentials = StorageByKeyName(CredentialsModel, user_email, 'credentials').get()
   force = self.request.get('force')
   if force and force == 'true':
       self.redirect(flow.step1_get_authorize_url()) 
       return
   
   if credentials:
     user = User.get_by_key_name(user_email)
     if not user or not user.is_oauth_complete:
       ctxIO = ContextIO(consumer_key=settings.CONTEXTIO_OAUTH_KEY, 
                         consumer_secret=settings.CONTEXTIO_OAUTH_SECRET)
       current_account = ctxIO.post_account(email=user_email)
       user = User.get_or_insert(key_name = user_email, 
                                 user_ctx_id=current_account.id,
                                 email=user_email)
       refresh_token = credentials.refresh_token
       try:
         if not refresh_token:
           raise Exception('no refresh token')
         current_account.post_source(email=user_email,
                                            username=user_email,
                                            server='imap.gmail.com',
                                            provider_refresh_token=refresh_token,
                                            provider_consumer_key=settings.APPENGINE_CONSUMER_KEY)
       except Exception as e:
         logging.error(str(e))
         self.redirect(flow.step1_get_authorize_url())
       user.is_oauth_complete = True
       user.put()
     self.response.out.write(r"""<html><head><script type="text/javascript">window.close();</script></head><body><div id="sbi_camera_button" class="sbi_search" style="left: 0px; top: 0px; position: absolute; width: 29px; height: 27px; border: none; margin: 0px; padding: 0px; z-index: 2147483647; display: none;"></div></body></html>""")
   else:
     logging.info('redirect')
     self.redirect(flow.step1_get_authorize_url()) 
开发者ID:B-Rich,项目名称:cs377d-proj1,代码行数:35,代码来源:oauth.py


示例3: authorized

def authorized(resp):
    if resp is None:
        return 'Access denied: reason=%s error=%s' % (
            request.args['error_reason'],
            request.args['error_description']
        )
    # Save token to the session for the immediately following gmail request
    session['gmail_token'] = (resp['access_token'], )
    # Check if that user already exists in the db
    gmail_user = gmail.get('userinfo')
    try:
        postal_user = (db_session.query(User)
                                 .filter_by(email_address=gmail_user.data['email'])
                                 .one())
        # Choosing to just update the token the db
        postal_user.save_new_token(resp['access_token'])
        session['user_email'] = gmail_user.data['email']
        session['user_id'] = postal_user.id
    except sqlalchemy.orm.exc.NoResultFound, e:
        # If a new user, save them to the db
        postal_user = User(name=gmail_user.data['name'],
                           email_address=gmail_user.data['email'],
                           access_token=resp['access_token'])
        postal_user.save()
        session['user_email'] = gmail_user.data['email']
        session['user_id'] = postal_user.id
开发者ID:etothemanders,项目名称:GoingPostal,代码行数:26,代码来源:views.py


示例4: api_register_user

def api_register_user(*,email,name,passwd):
	logging.info('comming into register post users')
	if not name or not name.strip():
		raise APIValueError('name')
	if not name or not _RE_EMAIL.match(email):
		raise APIValueError('email')
	if not passwd or not _RE_SHA1.match(passwd):
		raise APIValueError('passwd')
	users = yield from User.findAll('email=?',[email])

	if len(users) > 0 :
		raise APIError('register:failed','email','Email is already in use.')
	uid = next_id()
	sha1_passwd = '%s:%s' %(uid,passwd)
	user = User(id=uid,name=name.strip(),email=email,passwd=hashlib.sha1(
		sha1_passwd.encode('utf-8')).hexdigest(),image='http://www.gravatar.com/avatar/%s?d=mm&s=120' % hashlib.md5(email.encode('utf-8')).hexdigest())
	yield from user.save()

	#make session cookie from here:
	r = web.Response()
	r.set_cookie(COOKIE_NAME,user2cookie(user,86400),max_age=86400,httponly=True)

	user.passwd = '******'
	r.content_type = 'application/json'
	r.body = json.dumps(user,ensure_ascii=False).encode('utf-8')

	return r 
开发者ID:wentixiaogege,项目名称:python3,代码行数:27,代码来源:handlers.py


示例5: get

	def get(self):
		if(not isUserAdmin(self)):
			self.session[LOGIN_NEXT_PAGE_KEY] = self.URL
			self.redirect("/")
			return
		pageText=self.request.get("page")
		pageSize=20
		actualPage=0
		if (pageText!=None and pageText!=""):
			actualPage=int(pageText)-1
		orderByText=self.request.get("order")
		if (orderByText==None or orderByText==""):
			orderByText='familyName'
		userCount=User.all().count()
		roles=Role.all().order("name")
		usersToDisplay=User.all().order(orderByText).run(offset=actualPage*pageSize, limit=pageSize)
		pages=[]
		corrector=1
		if (userCount/pageSize) * pageSize == userCount:
			corrector=0
		for i in range(0,userCount/pageSize + corrector):
			pages.append(i+1)
		template_values={
			'page':actualPage+1,
			'pages':pages,
			'userList':usersToDisplay,
			'order':orderByText,
			'roles':roles
		}
		if actualPage < userCount/ pageSize - 1 - corrector:
			template_values["nextPage"]=actualPage + 2
		if actualPage > 0:
			template_values["nextPage"]=actualPage
		template = jinja_environment.get_template('templates/userList.html')
		self.printPage("Felhasznalok", template.render(template_values), False, False)
开发者ID:lajthabalazs,项目名称:diet-futar,代码行数:35,代码来源:user_admin.py


示例6: api_register_user

async def api_register_user(*, email, name, passwd):
    '''
    这个函数其实是用来注册用户的。
    '''
    if not name or not name.strip():
        raise APIValueError('name')
    if not email or not _RE_EMAIL.match(email):
        raise APIValueError('email')
    if not passwd or not _RE_SHA1.match(passwd):
        raise APIValueError('passwd')
    uid = next_id()
    sha1_passwd = '%s:%s' % (uid, passwd)
    user = User(
        id=uid,
        name=name.strip(),
        email=email,
        passwd=hashlib.sha1(sha1_passwd.encode('utf-8')).hexdigest(),
        image='http://www.gravatar.com/avatar/%s?d=mm&s=120' % hashlib.md5(email.encode('utf-8')).hexdigest()
    )

    await user.save()
    # make session cookie:
    r = web.Response()
    # 登陆的时候要创建cookie信息
    r.set_cookie(COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True)
    user.passwd = '******'
    r.content_type = 'application/json'
    r.body = json.dumps(user, ensure_ascii=False).encode('utf-8')
    return r
开发者ID:lishuhuakai,项目名称:CS,代码行数:29,代码来源:handlers.py


示例7: insert_user

def insert_user(user_json):
  #print "INSERT USER"
  #print user_json
 
  user_string = json.loads(user_json)
  userAddress = Address(number = user_string["number"],
                    street = user_string["street"],
                    postalCode = user_string["postalCode"],
                    city = user_string["city"],
                    province = user_string["province"])

  #print "pizzaId: " + user_string["pizzaId"]
  
  userOrder = Order(qty = int(user_string["quantity"]),
								size = int(user_string["pizzaSize"]),
                pizza_type = int(user_string["pizzaId"]))   
  userAddress.put()
  userOrder.put()
  user = User(name = user_string["name"],
              phoneNumber = user_string["phoneNumber"],
              email = user_string["email"],
              addressId = userAddress.key(), 
              orderId = userOrder.key())  

  user.put()
  return user.key();
开发者ID:gmacleod,项目名称:PizzaButton,代码行数:26,代码来源:model_wrapper.py


示例8: register

def register():
    if request.method == 'GET':
        return render_template('register.html', page='signup')
    elif request.method == 'POST':
        username = request.form.get('username', None)
        nickname = request.form.get('nickname', None)
        password = request.form.get('password', None)
        password_again = request.form.get('password_again', None)

        if username is None or nickname is None or password is None or password_again is None:
            flash(u'请检查输入是否为空', 'danger')
            return redirect(url_for('register'))
        password, password_again, username, nickname = unicode(password), unicode(password_again), unicode(username), unicode(nickname)

        # 1. 用户名是否存在
        user = User.query.filter_by(username=username).first()
        if user:
            flash(u'该用户名已被注册', 'danger')
            return redirect(url_for('register'))
        # 2. 密码输入不一致
        if password != password_again:
            flash(u'两次密码输入不一致', 'danger')
            return redirect(url_for('register'))

        proc_password = utils.encrypt_password(password, salt=config.SALT)
        User.add(User(username, proc_password, nickname))
        flash(u'注册成功', 'success')
        return redirect(url_for('login'))
开发者ID:tiny656,项目名称:show-me-the-code,代码行数:28,代码来源:app.py


示例9: populate

    def populate(self):
        # clear the existing cache
        for x in range(0, len(self)):
            self.pop()

        if self.location != 'global':
            location = Location.get(self.location)
            if location.is_region:
                hubs = location.has_hubs
                profile_select = User.select(AND(IN(User.q.homeplaceID, hubs),
                    User.q.public_field==1,
                    User.q.active==1,
                    User.q.description != u"",
                    User.q.modified > datetime.datetime.now() - datetime.timedelta(days=365))).orderBy('modified').reversed()[:30]
            else:
                profile_select = User.select(AND(User.q.homeplaceID==location,
                    User.q.public_field==1,
                    User.q.active==1,
                    User.q.description != u"",
                    User.q.modified > datetime.datetime.now() - datetime.timedelta(days=365))).orderBy('modified').reversed()[:30]
        else:
            profile_select = User.select(AND(User.q.public_field==1,
                    User.q.active==1,
                    User.q.description != u"",
                    User.q.modified > datetime.datetime.now() - datetime.timedelta(days=365))).orderBy('modified').reversed()[:30]
        for profile in profile_select:
            cache_obj = self.objectcache_factory(profile)
            self.append(cache_obj)
开发者ID:salfield,项目名称:hubspace,代码行数:28,代码来源:feeds.py


示例10: get

 def get(self, username):
     """Loads user's properties. If logged user is admin it loads also non public properties"""
     if auth.is_admin():
         properties = User.get_private_properties()
     else:
         properties = User.get_public_properties()
     return g.user_db.to_dict(include=properties)
开发者ID:Huijari,项目名称:gae_test,代码行数:7,代码来源:user_api.py


示例11: get

    def get(self):
        verification_code = self.request.get("code")
        args = dict(client_id=Constants.FACEBOOK_APP_ID, redirect_uri=self.request.path_url)
        if self.request.get("code"):
            args["client_secret"] = Constants.FACEBOOK_APP_SECRET
            args["code"] = self.request.get("code")
            response = cgi.parse_qs(urllib.urlopen(
                "https://graph.facebook.com/oauth/access_token?" +
                urllib.urlencode(args)).read())
            access_token = response["access_token"][-1]

            # Download the user profile and cache a local instance of the
            # basic profile info
            profile = json.load(urllib.urlopen(
                "https://graph.facebook.com/me?" +
                urllib.urlencode(dict(access_token=access_token))))
            user = User(key_name=str(profile["id"]), id=str(profile["id"]),
                        name=profile["name"], access_token=access_token,
                        profile_url=profile["link"])
            user.put()
            functions.set_cookie(self.response, "fb_user", str(profile["id"]),
                       expires=time.time() + 30 * 86400)
            self.redirect("/")
        else:
            self.redirect(
                "https://graph.facebook.com/oauth/authorize?" +
                urllib.urlencode(args))
开发者ID:DavidYKay,项目名称:locool,代码行数:27,代码来源:main.py


示例12: post

    def post(self):
        email = self.request.get('email', '')
        password = self.request.get('password', '')
        other_username = self.request.get('other-user')

        logging.info('%s, %s' % (email, other_username))

        user = User.user_from_email(email)

        if not user:
            logging.info('not a valid email address')
            self.render('error.html', **{'error_msg': 'You cannot do this'})
            return
        if not self.validate_user(user, password):
            logging.info('username password fail')
            self.render('error.html', **{'error_msg': 'You cannot do this'})
            return
        if not user.admin:
            logging.info('Need to be admin to login as other user')
            self.render('error.html', **{'error_msg': 'You cannot do this'})
            return

        other_user = User.user_from_name(other_username)
        logging.info('Other user: %s' % other_user)

        if not other_user:
            logging.info('cannot find other user')
            self.render('error.html', **{'error_msg': "Can't find other user"})
            return

        self.set_cookie(other_user)
        self.redirect('/user/%d' % other_user.key.id())
开发者ID:PreludeAndFugue,项目名称:prelude-hmpc,代码行数:32,代码来源:user_admin.py


示例13: testPassword

 def testPassword(self):
     # Valid passwords
     password = '11111111'
     self.assertTrue(User.isPasswordValid(password), 'Misqualified valid password: ' + password)
     password = '111wr311111'
     self.assertTrue(User.isPasswordValid(password), 'Misqualified valid password: ' + password)
     password = 'asdasdawdas'
     self.assertTrue(User.isPasswordValid(password), 'Misqualified valid password: ' + password)
     
     # invalid passwords       
     password = '1234567'
     self.assertFalse(User.isPasswordValid(password), 'Misqualified invalid password: ' + password)
     password = ''
     self.assertFalse(User.isPasswordValid(password), 'Misqualified invalid password: ' + password)
     password = ' '
     self.assertFalse(User.isPasswordValid(password), 'Misqualified invalid password: ' + password)
     password = '12 3 4567'
     self.assertFalse(User.isPasswordValid(password), 'Misqualified invalid password: ' + password)
     password = 'asdasdasd;'
     self.assertFalse(User.isPasswordValid(password), 'Misqualified invalid password: ' + password)
     password = 'asdasdasd\''
     self.assertFalse(User.isPasswordValid(password), 'Misqualified invalid password: ' + password)
     password = 'asdasdasd"'
     self.assertFalse(User.isPasswordValid(password), 'Misqualified invalid password: ' + password)
              
开发者ID:szilardhuber,项目名称:shopper,代码行数:24,代码来源:test_user_unit.py


示例14: text_message

    def text_message(self, message):
        email = extract_email(message.sender)

        try:
            sender = users.User(email)
        except users.UserNotFoundError as e:
            message.reply("You don't seem to have an account that I can find.")

        appuser = User.all().filter("info = ", sender).get()

        if not appuser:
            appuser = User(info = sender)
            appuser.put()

        try:
            datum = parser.parse(message.body)
        except parser.ParseException as e:
            message.reply("I couldn't understand you. (Message was: {msg})".format(msg = e.message))

        variable = Variable.all().filter("name = ", datum["variable"]).get()
        if not variable:
            variable = Variable(name = datum["variable"], user = appuser)
            variable.put()

        value = Value(value = datum["value"], variable = variable)
        value.put()

        message.reply("I've logged variable {variable} as being {value}".format(sender = email,
                                                                                variable = datum["variable"],
                                                                                value = datum["value"]))
开发者ID:mizhi,项目名称:tictic,代码行数:30,代码来源:xmpp.py


示例15: load_users

def load_users():
    """Load users from user.csv into database."""
    # open file
    user_csv = open("user.csv")
    # Iterate through the lines
    # This will put the data into a list
    for line in user_csv:
        line_list = line.strip().split("|")
        # Another for loop to iterate through
        for i in range(len(line_list)):
            line_list[i] = line_list[i].strip()
        user_id, email, password, street_address, zipcode, first_name, last_name, admin = line_list[0], line_list[1], \
                                                                                          line_list[2], line_list[3], \
                                                                                          line_list[4], line_list[5], \
                                                                                          line_list[6], line_list[7]

        print "EMAIL: {}, PASSWORD: {}, STREET_ADDRESS: {}, ZIPCODE: {}, FIRST {}, LAST {}".format(email, password,
                                                                                                   street_address,
                                                                                                   zipcode, first_name,
                                                                                                   last_name)

        user = User(user_id=user_id, email=email, street_address=street_address, zipcode=zipcode, first_name=first_name,
                    last_name=last_name, admin=admin)
        user.hash_password(password)

        db.session.add(user)
    db.session.commit()
开发者ID:ShortyStack,项目名称:Hackbright-Final-Project-,代码行数:27,代码来源:seed.py


示例16: login

def login():
    """Log in page"""

    name = request.form.get('name')
    email = request.form.get('email')
    image = request.form.get('image')

    user = User.query.filter_by(email=email).first()

    if user:
        user_id = user.user_id
        session['user_id']=user_id
        session['name']=name
        session['image']=image
       
        return "%s is in session" %(name)

    if not user:
        User.add_user(email=email, name=name, image=image)
        session['user_id']=user_id
        session['name']=name
        session['image']=image
       
        return "%s is in session" %(name)

    else:
        return None
开发者ID:katherinehuwu,项目名称:Word_Fit,代码行数:27,代码来源:server.py


示例17: set_up

 def set_up(self):
     u = User()
     path = u.path(self.id)
     try:
         os.remove(path)
     except Exception, e:
         pass
开发者ID:lateefj,项目名称:Py-Event-Programing-Example,代码行数:7,代码来源:test_model.py


示例18: login_telnet

def login_telnet(frame,username):
    user = User(username)
    user.init_user_info()
    frame.session.update(user.dict)
    frame.session['_user'] = user
    frame.session['username'] = username
    return user
开发者ID:yanwen,项目名称:argon,代码行数:7,代码来源:libtelnet.py


示例19: profile_get

def profile_get(username):
    """
    Show user's profile with at most recent 10 tweets

    :param username: username of the user
    :type username: string
    :rtype: profile page of the user

    Note:
        Need to check whether authenticated or not
        if so add an profile edit button
        if not follow button or followed status

        Use 'action' param to judge whether to update profile or password
        if it is 'profile', show profile update form
        if it is 'password', show password update form
    """
    user = User.get(username)
    ownername = request.get_cookie('username', secret=COOKIES_SECRET)
    owner = User.get(ownername)
    action = request.GET.get('action', '')
    if ownername == username:
        if action == 'profile':
            return template('profile_update', user=user)
        elif action == 'password':
            return template('password_update', user=user)
    tweets = user.get_tweets()
    isfollow = owner.isfollow(username)
    return template('profile', user=user, owner=owner, tweets=tweets,
        isfollow=isfollow)
开发者ID:huxuan,项目名称:pyneo4jet,代码行数:30,代码来源:pyneo4jet.py


示例20: confirm_new_user

def confirm_new_user():
    """Creates new user"""

    # flash=[]
    # It gets email and password from the POST param
    user_email = request.form.get("email")

    user_password = request.form.get("password")

    name = request.form.get("name")

    #It checks if user already exists or email is invalid
    confirmed_user = User.get_user_by_email(user_email)

    # is_valid = validate_email(user_email,verify=True)

    # EMAIL_RE.search(user_email)
    if True:

        if not confirmed_user:
            User.create_user_by_email_password(user_email, user_password, name)
            flash("You successfully created an account!")
            return redirect('/')
        else:
            flash("You already have an account")
            return render_template('error.html',url='homepage.html')

    else:
        flash("The email that you entered is invalid")
        # return render_template('error.html',url='homepage.html')

    return render_template('error.html',url='homepage.html')
开发者ID:Francydijesi,项目名称:hackbright_project,代码行数:32,代码来源:server.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python User.User类代码示例发布时间:2022-05-27
下一篇:
Python model.Task类代码示例发布时间: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