当前位置: 首页>>代码示例>>Python>>正文


Python User.objects方法代码示例

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


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

示例1: register

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import objects [as 别名]
def register():
    form = SignupForm()
    if request.method == 'POST' and form.validate():
        user_per_email = User.objects(email=form.email.data)
        user_per_username = User.objects(username=form.username.data)
        if user_per_email:
            form.errors['email'] = ['Email is already taken.']
        elif user_per_username:
            form.errors['username'] = ['Username is already taken.']
        else:
            user = User(email=form.email.data, username=form.username.data)
            user.set_password(form.password.data)
            user.save()
            login_user(user)
            analytics.identify(str(user.id), {'email': str(user.email)})
            analytics.track(str(user.id), 'Registered (srv)')
            return redirect('/data')

    for field, errors in form.errors.items():
        # type(errors)
        for error in errors:
            flash(u"Error in %s  - %s" % (
                getattr(form, field).label.text, error))

    return render_template('users/user.html', form=form)
开发者ID:abdelhai,项目名称:dyform,代码行数:27,代码来源:views.py

示例2: register

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import objects [as 别名]
def register(language='en'):
    # login information
    username = request.form['username']
    password = request.form['password']
    email = request.form['email']
    firstname = request.form['firstname']
    lastname = request.form['lastname']

    num_users = User.objects(username=username).count()
    if num_users > 0:
        session['alert_place'] = 'register'
        session['alert_message'] = 'Username has been registered.'
        return redirect(url_for('index.index_backend', language=language))

    num_users = User.objects(email=email).count()
    if num_users > 0:
        session['alert_place'] = 'register'
        session['alert_message'] = 'Email has been registered.'
        return redirect(url_for('index.index_backend', language=language))

    user = User(username=username,
                password=password,
                email=email,
                firstname=firstname,
                lastname=lastname,
                admin=False)

    user.save()

    session['username'] = username
    return redirect(url_for('index.index_backend', language=language))
开发者ID:yuany12,项目名称:biopedia,代码行数:33,代码来源:login.py

示例3: newbrainstorm

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import objects [as 别名]
def newbrainstorm():
    me = User.objects(id = g.user.id).first()
    
    form = AddNewBrainstormForm()
    if form.validate_on_submit():
        people = [me]
        c = Comment(message = form.initialcomment.data, user = me)

        b = Brainstorm(title = form.title.data, comments = [c], people = [me])
        b.save()

        me.brainstorms.append(b)
        me.save()

        feeditem = BrainstormRequest(brainstorm=b,message=g.user.name+" started a brainstorm with you.",user = me)

        for person in form.data['people']:
            friend = User.objects(username = person).first()
            friend.feed.append(feeditem)
            friend.save()

        return redirect(url_for('brainstorms'))
    else:
        print 'nope'

    return render_template('newbrainstorm.html',form=form)
开发者ID:akosel,项目名称:mesh,代码行数:28,代码来源:views.py

示例4: test_user_post

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import objects [as 别名]
	def test_user_post(self):
		data={
			'email':'[email protected]','password':'test','fname':'test','lname':'test'

		}	
		response=self.client.post('/api/user/',json.dumps(data),content_type='application/json')
		self.assertEqual(response.status_code,201)
		self.assertEqual(str(json.loads(response.content)['lname']),data['lname'])
		User.objects(id__iexact = str(json.loads(response.content)['id']) ).delete()
开发者ID:mohitmehta93,项目名称:eventify,代码行数:11,代码来源:tests.py

示例5: unsubscribe

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import objects [as 别名]
def unsubscribe(rss_id):
    '''Logic to unsubscribe a user from an rss feed, and all articles from that feed'''
    try:
        feed_to_be_removed = Feed.objects.get(id = rss_id)
        #atomically remove feed subscription from current user
        User.objects(id = current_user.id).update_one(pull__subscriptions__feed_id = feed_to_be_removed.id)
        #atomically remove articles from unsubscribed feed for current user
        Article.objects(feed_id = feed_to_be_removed.id).update(pull__readers__user_id = current_user.id)
        return jsonify(dict(status = 'Success'))
    except DoesNotExist:
        return jsonify(dict(status = 'Error', message = 'Given feed does not exist'))
开发者ID:AkarshES,项目名称:Readless,代码行数:13,代码来源:routes_logic.py

示例6: next

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import objects [as 别名]
def next():
    if request.method == "POST":
        # TODO: helper
        tags = set(map(unicode.lower, request.form.getlist("tags")))

        Cluster.objects(pk=request.form["_id"]).update_one(
            push__tags=ShredTags(
                user=g.user.id,
                tags=list(tags),
                recognizable_chars=request.form.get("recognizable_chars", ""),
                angle=int(request.form.get("angle", 0))),
            inc__users_count=1,
            add_to_set__users_processed=g.user.id)

        User.objects(pk=g.user.id).update_one(
            inc__processed=1, inc__tags_count=len(tags),
            add_to_set__tags=list(tags))

        session["processed"] = session.get("processed", 0) + 1

        for tag in tags:
            Tags.objects(pk=tag).update_one(
                set_on_insert__is_base=False,
                set_on_insert__created_by=g.user.id,
                set_on_insert__created_at=Tags().created_at,
                inc__usages=1,
                add_to_set__shreds=request.form["_id"],
                upsert=True)

        start = datetime.strptime(request.form["tagging_start"],
                                  '%Y-%m-%d %H:%M:%S.%f')
        end = datetime.utcnow()
        TaggingSpeed.objects.create(
            user=g.user.id,
            cluster=request.form["_id"],
            tags_count=len(tags),
            msec=(end - start).total_seconds() * 1000)

    cluster = Cluster.next_for_user(g.user, app.config['USERS_PER_SHRED'])

    auto_tags = cluster and cluster.get_auto_tags() or []
    return render_template(
        "_shred.html",
        cluster=cluster,
        auto_tags=auto_tags,
        all_tags=get_tags(),
        tagging_start=datetime.utcnow(),

        # TODO: move to context processor
        processed_per_session=session.get("processed", 0),
        processed_total=User.objects(id=g.user.id).first()["processed"],
        rating=list(User.objects.order_by(
            "-processed").values_list("id")).index(g.user.id) + 1
    )
开发者ID:kostyll,项目名称:unshred-tag,代码行数:56,代码来源:app.py

示例7: new_user

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import objects [as 别名]
def new_user(username, password, email, first_name, last_name, interest):
    if User.objects(Username=username).first():
        raise InvalidQueryError("User already exists.")
    if User.objects(Email=email).first():
        raise InvalidQueryError("User already exists.")

    try:
        user = User(Username=username, Password=password, Email=email,
                    First_name=first_name, Last_name=last_name, Interest=interest)
        user.save()
        return {"Success":True}
    except:
        raise InvalidQueryError("Error in creating user.")
开发者ID:pankaj22,项目名称:RecommenderApi,代码行数:15,代码来源:controllers.py

示例8: post

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import objects [as 别名]
 def post(self):
     if not request.json or 'name' not in request.json :
         abort(400)
     
     user = User.objects(email= request.json['email'])
     if len(user) > 0 :
         return jsonify(
                     ok=False,
                     errors=['Email already in use. Account creation failed']
                     ), 403
     
     new_user = User(name= request.json['name'],
                     email= request.json['email'],
                     alive=True
                     )
     
     new_user.description = request.json.get('description', None )
     new_user.location = request.json.get('location', None )
     new_user.phone = request.json.get('phone', None )
     new_user.public = True
     
     new_user.save()
     
     if 'password' in request.json :
         auth = Auth( user= new_user, password=request.json['password'], alive=False )
         
         auth.password = auth.hash_password(
                                 request.json['email'],
                                 request.json['password'])
         auth.save()
     
     return jsonify(ok=True, objects=[new_user.to_json()]), 201
开发者ID:DeprecatedCode,项目名称:yearplan,代码行数:34,代码来源:user.py

示例9: facebook_authorized

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import objects [as 别名]
def facebook_authorized(resp):
    if resp is None:
        return 'Access denied: reason=%s error=%s' % (
            request.args['error_reason'],
            request.args['error_description']
        )
    session['oauth_token'] = (resp['access_token'], '')
    me = facebook.get('/me')
    picture = "http://graph.facebook.com/"+me.data['id']+"/picture?type=large"

    user = User.objects(username = me.data['email']).first()

    if not user:
        user = User(username = me.data['email'], picture = picture, role = ROLE_USER, name = me.data['first_name'] + " " + me.data['last_name']) 
        user.save()
    else:
        user['picture'] = picture
        user['name'] = me.data['first_name'] + " " + me.data['last_name']
        user['first_name'] = me.data['first_name']
        user['last_name'] = me.data['last_name']
        user.save()
            
    login_user(user)

    return redirect(url_for('index'))
开发者ID:akosel,项目名称:mesh,代码行数:27,代码来源:views.py

示例10: photo_from_email

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import objects [as 别名]
def photo_from_email(email):
	u = User.objects(email = email)
	photo = u[0].profile_picture
	if photo is None:
		abort(404)
	url = photos.url(photo.image_path)
	return url 
开发者ID:csik,项目名称:OccuDopt,代码行数:9,代码来源:views.py

示例11: login

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import objects [as 别名]
def login():
	username=None
	password=None
	try:
		username=request.form['username']
		password=request.form['password']
	
	except Exception as e:
		print (e)
	 
	if username.replace(" ",'')== '':
		error="Please enter your username"

		flash(error)
		return render_template("Login.html")

	if password.replace(" ",'') == '':
		error="Please enter your password"
		flash(error)
		return render_template("Login.html")




	user=User.objects(Q(username=username) & Q (password=password) ).first()
	if user is None:
		error="It seems that the username or password you typed is wrong"
		flash(error)
		return render_template("Login.html")
	elif user.enabled == False:
		error="Sorry. Your account is not enabled yet by administrator"
		flash(error)
		return render_template("Login.html")
	else:
		return render_template("Profile.html",user=user)
开发者ID:akshaynathr,项目名称:ALCA_Website,代码行数:37,代码来源:views.py

示例12: login

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import objects [as 别名]
def login():
	"""
	Handle the login try of a user
	"""
	#In case the user is already logged in, we redirect to index
	if current_user.is_authenticated:
		return redirect(url_for('index'))

	form = LoginForm()
	try:
		if form.validate_on_submit():
			user_to_log = User.objects(username=form.username.data).first()
			login_user(user_to_log)
			user_to_log.handler_logging_successful()
			cust_logger.info("Logged on user {} successfully".format(user_to_log.username))
			flash('Logged in successfully.')

			#change the identity for permissions, raising the identity changed event :
			identity_changed.send(current_app._get_current_object(), 
													identity=Identity(current_user.get_id()))
			return redirect(url_for('index'))
	except Exception as e:
		cust_logger.exception(e)
		cust_logger.warning("Couldn't log on user, redirection to login page")
		flash('The server is experiencing troubles and failed to register you. Please retry '\
						'or contact our customer service if the problem persists')
		return render_template('login.html', form=form)
	#flash(form.errors)
	cust_logger.info("From failed to be validated")

	return render_template('login.html', form=form)
开发者ID:golgoth,项目名称:Webito,代码行数:33,代码来源:app.py

示例13: load_user

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import objects [as 别名]
def load_user(user_id):
	"""
	Callback to reload a user from a session, flask requirement.
	:param user_id: correspond to the email of a user in our case. 
	:return: None if no user exists with this user_id, or the user. 
	"""
	return User.objects(email=user_id).first()
开发者ID:golgoth,项目名称:Webito,代码行数:9,代码来源:app.py

示例14: callback

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import objects [as 别名]
def callback():
    if 'code' in request.args:
        # Step 2
        code = request.args.get('code')
        data = dict(code=code,
                    client_id=config.client_id,
                    client_secret=config.client_secret,
                    redirect_uri=config.redirect_uri,
                    grant_type='authorization_code')
        r = requests.post(config.token_uri, data=data)
        # Step 3
        access_token = r.json()['access_token']
        r = requests.get(config.profile_uri, params={'access_token': access_token})
        print r.json()
        user = User.objects(username = r.json()['email']).first()

        if not user:
            user = User(username = r.json()['email'], picture = r.json()['picture'], role = ROLE_USER, name = r.json()['name']) 
            user.save()
        else:
	    user['picture'] = r.json()['picture']
            user['first_name'] = r.json()['given_name']
            user['last_name'] = r.json()['family_name']
            user.save()
        login_user(user)
        return redirect(url_for('index'))
    else:
        return 'Oops, looks like the login failed.'
开发者ID:akosel,项目名称:mesh,代码行数:30,代码来源:views.py

示例15: get_visitor_lists

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import objects [as 别名]
def get_visitor_lists(request):
    if request.method == "POST":
        try:
            skip = int(request.POST.get('skip', 0))
        except (TypeError, ValueError) as e:
            skip = 0
        try:
            limit = int(request.POST.get('limit', 5))
        except (TypeError, ValueError) as e:
            limit = 5
        # 查看是否有坐标参数
        try:
            latitude = float(request.POST.get('latitude', None))
            longitude = float(request.POST.get('longitude', None))
        except:
            return JsonResponse(resultMsg['CoordinatesError'])
        coordinates = [longitude, latitude]     # 做成坐标组
        print coordinates
        visitors = User.objects(
            id__ne=request.session['currentUser']['_id'],
            status__in=['user', 'applyGuide'],
            location__near=coordinates,
            location__max_distance=10000
        ).only('id', 'realName', 'avatar', 'description').all()[skip: limit]
        visitors = json.loads(visitors.to_json())
        map(id_replace, visitors)
        return JsonResponse({"result": visitors})
    raise Http404
开发者ID:540871129,项目名称:AppBackend,代码行数:30,代码来源:views.py


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