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


Python User.save方法代码示例

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


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

示例1: register

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import save [as 别名]
def register():
    form = RegistrationForm()

    if request.method == "GET":
        return render_template("register.html", form=form)
    elif request.method == "POST":
        if form.validate_on_submit():
            user = User()
            form.populate_obj(user)
            # overwrite the old password with a bcrypt-hash
            user.password = hash_password(user.password)
            try:
                user.save()
                app.logger.info("New user registered")
                flash("User registered successfully", "success")
            except IntegrityError as err:
                app.logger.warning("Could not register user: {0}".format(err))
                flash("User could not be registered, please try again", "error")
            except OperationalError as err:
                app.logger.warning("MySQL Error: {0!s}".format(err))
                flash("{0!s}".format(err))

            return redirect(url_for("show_index"))
        else:
            flash_errors(form)
        return render_template("register.html", form=form)
开发者ID:rnts08,项目名称:flask-boilerplate,代码行数:28,代码来源:webapp.py

示例2: feed

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import save [as 别名]
def feed(request, username):
    url = "https://twitrss.me/twitter_user_to_rss/?user=" + username
    dicc = feedparser.parse(url)
    out = ""

    for number in range(5):
        out += dicc.entries[number].title + "<br>"
        #Obtener las urls del tweet si hay
        urls = dicc.entries[number].title.split()
        for i in urls:
            if i.startswith("http://") or i.startswith("https://"):
                i = i.split('&')[0]
                out += "<li><a href=" + i + ">" + i + "</a></li>"
                #Obtener primer elemento <p>
                soup = BeautifulSoup(urllib.urlopen(i).read())
                out += str(soup.p).decode('utf8')
                #Obtener primer elemento <img>
                out += str(soup.img).decode('utf8') + "<br><br>"

        #Comprobar y guardar autor del tweet
        user = dicc.entries[number].title.split(':')[0]
        try:
            p = User.objects.get(name=user)
        except ObjectDoesNotExist:
            p = User(name=user)
            p.save()

        #Comprobar y guardar tweet
        try:
            t = Tweet.objects.get(content=dicc.entries[number].title)
        except ObjectDoesNotExist:
            t = Tweet(content=dicc.entries[number].title, url= dicc.entries[number].link, name=p)
            t.save()

    return HttpResponse(out)
开发者ID:RebeccaSaez,项目名称:X-Serv-15.12-Django-feedexpander,代码行数:37,代码来源:views.py

示例3: view_register

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import save [as 别名]
def view_register(request):
    #registerform = RegisterForm()
    error = None
    vista = "register"
    if request.POST:
    #registerform = RegisterForm(request.POST)
    #if registerform.is_valid():
        nombre = request.POST.get('nombre', -1)
        apellidos = request.POST.get("apellidos", -1)
        email = request.POST.get("email", -1)
        profiles = Profile.objects.all()
        passw = request.POST.get("password", -1)
        repassw = request.POST.get("repassw", -1)
        if repassw == passw and email != -1 and apellidos != -1 and nombre != -1:
            u = User(username=nombre, first_name=nombre, last_name=apellidos, email=email)
            u.set_password(repassw)
            u.save()
            Client.objects.create(user=u, profile=profiles[0])
            request.session['registrado'] = True
            return redirect(to="/register")
        else:
            if repassw == passw:
                error = "los password no son iguales"
            else:
                error = "Falta insertar datos"
    mostrar = 0

    if request.session.get('registrado'):
        mostrar = 1
        del request.session['registrado']
    print error
    return render_to_response("desktop/inicio.html", {"error": error, 'mostrar': mostrar, 'vista': vista},
        context_instance=RequestContext(request))
开发者ID:eyscode,项目名称:gestor-proyectos-ewm,代码行数:35,代码来源:views.py

示例4: register

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import save [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

示例5: bind

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import save [as 别名]
def bind(request):
    if request.method == 'GET':
        # 跳转到绑定用户界面
        t = loader.get_template("bind.html")
        c = Context({'openid': request.GET.get('openID')})
        return HttpResponse(t.render(c))
    elif request.method == 'POST':
        # 检查数据库是否有此用户 如果没有则存入数据库
        exist = User.objects.filter(openid=request.POST['openid'])
        if exist.exists():
            return render(request, "bindRes.html", {'bindRes': '您已经绑定账号,无需重复绑定'})
        else:
            # 检查用户名密码是否合法
            j_username = request.POST['username']
            j_password = request.POST['password']
            grd = GrdmsRobot(j_username, j_password)
            if not grd.login_status:
                return render(request, "bindRes.html", {'bindRes': '用户名或密码错误,请返回重新绑定'})

            user = User()
            user.openid = request.POST['openid']
            user.j_username = request.POST['username']
            user.j_password = request.POST['password']
            user.save()
            t = loader.get_template("bindRes.html")
            c = Context({'bindRes': '绑定成功'})
            return HttpResponse(t.render(c))
开发者ID:RaulWei,项目名称:HowMuch,代码行数:29,代码来源:views.py

示例6: post_account

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import save [as 别名]
def post_account():
    print request.json

    username = request.json.get('accountUsername')
    password = request.json.get('accountPassword')
    email = request.json.get('accountEmail')
    token = request.json.get('signupToken')

    if email and password and token:
        print username, password
        user = User(
                username=username,
                email=email,
                password=password)
        user.save()

        session['user_id'] = str(user.id)

        # login in the user
        # g.user = user or whatever
    else:
        print "not all parameters have been set"
        # redirect to main home page

    return url_for('index')
开发者ID:mcherkassky,项目名称:listen,代码行数:27,代码来源:__init__.py

示例7: admin

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import save [as 别名]
def admin(username, is_admin):
    try:
        user = User.objects.get(name=username)
    except User.DoesNotExist:
        user = User(name=username)
    user.is_admin = is_admin
    user.save()
开发者ID:ojii,项目名称:checklists.ojii.ch,代码行数:9,代码来源:utils.py

示例8: register

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import save [as 别名]
def register(request):
    if request.method == 'POST':
        # 提交表单
        form = forms.RegisterForm(request.POST)
        if form.is_valid():
            register_date = datetime.now()
            default_avatar = {
                'big': 'user/avater/default.big',
                'mid': 'user/avater/default.mid',
                'small': 'user/avater/default.small'
            }
            # 保存用户信息
            user = User(
                gmt_create=register_date,
                gmt_modify=register_date,
                email=form.cleaned_data['email'].strip(),
                nickname=form.cleaned_data['nickname'].strip(),
                password=common.encode_password(form.cleaned_data['password'].strip()),  # encode passowrd
                avatar=json.dumps(default_avatar),
                status='enabled')
            user.save()
            # 写登录session
            session_id = _do_login(user.email)
            return_url = _get_return_url(request)
            response = HttpResponseRedirect(return_url)
            response.set_cookie('id', session_id)
            return response
        else:
            return render_to_response('register.htm', {'form': form})

    else:
        # 渲染页面
        return_url = urllib.urlencode({'return_url': _get_return_url(request)})
        register_action_url = '/register/?' + return_url
        return render_to_response('register.htm', {'register_action_url': register_action_url})
开发者ID:wylove,项目名称:djangoweb,代码行数:37,代码来源:views.py

示例9: oauth2_code_callback

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import save [as 别名]
def oauth2_code_callback(oauth_port):
    code = flask.request.args.get('code')
    oauth_adapter = OauthAdapter(
        oauth_port,
        flask.current_app.config['OAUTH2_CONFIG'],
        mock=MOCK_MODE
    )
    oauth_adapter.client.get_access_token(code)
    userinfo = oauth_adapter.client.get_userinfo()
    user = User.fetchone(
        oauth_id=userinfo.oauth_id,
        oauth_type=userinfo.oauth_type
    )

    if not user:
        user = User()
        user.oauth_id = userinfo.oauth_id
        user.oauth_type = userinfo.oauth_type

    user.nickname = userinfo.nickname
    user.avatar = userinfo.avatar
    user.oauth_id = userinfo.oauth_id
    user.oauth_type = userinfo.oauth_type
    user.save()
    session_token = account_signin(user.to_dict())
    response = flask.make_response(flask.redirect(flask.url_for('index')))
    response.set_cookie('session_token', session_token['token'])
    return response
开发者ID:jie,项目名称:sportsapp,代码行数:30,代码来源:app.py

示例10: regist

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import save [as 别名]
def regist(request):
	if request.method == 'POST':
		uf = UserForm(request.POST)

		if uf.is_valid():
			#username = uf.cleaned_data['username','']
			#password1 = uf.cleaned_data['password1','']
			# password2 = uf.cleaned_data['password2','']
			# email = uf.cleaned_data['email','']
			username = request.POST.get('username','')
			password1 = request.POST.get('password1','')
			password2 = request.POST.get('password2','')
			email = request.POST.get('email','')

			if password1 == password2:
				user =User(username = username, password = password1, email = email)
				user.save()
				return render_to_response('reg_ok.html')
			else:
				return render_to_response('reg_fail.html')
	else:
		uf = UserForm()
		#uf = forms.UserForm()

	return render_to_response('regist.html',{'uf':uf}, context_instance=RequestContext(request))
开发者ID:Sharonno,项目名称:learnJS,代码行数:27,代码来源:views.py

示例11: user_add

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import save [as 别名]
def user_add():
	import bcrypt
	PostForm = model_form(User)
	form = PostForm(request.form)
	if request.method == 'POST': #and form.validate():
		#the following is described in flask-uploads documentation
		filename = "" #store blank photo filename
		#initialize default user photo
		i = Image(image_path = 'default_image', is_profile=True) 
		if 'photo' in request.files:
			filename = photos.save(request.files['photo'])
			i = Image(image_path = filename, is_profile=True)
			flash("Photo saved.")
		i.save()
		#hash password stored in database so that it is not viewable by people in Romania
		hashed = bcrypt.hashpw(request.form["password"], bcrypt.gensalt())
		u = User(	email = request.form["email"], 
					first_name = request.form["first_name"], 
					last_name =request.form["last_name"], 
					password = hashed, 
					authenticated = False,
					philosophy = request.form['philosophy'],
					tags = request.form['tags'].split(','),
				)
		u.profile_picture= i
		u.save()
		return "done:" + request.form["email"] + " " + request.form["first_name"]+ " " + request.form["last_name"] + " " + '/_uploads/photos/'+i.image_path
	else:
		return render_template('add.html', form=form, cities = OccupyCity.objects.all())
开发者ID:csik,项目名称:OccuDopt,代码行数:31,代码来源:views.py

示例12: post

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import save [as 别名]
    def post(self, request):
        req_data = request.POST
        reqd_params = ['first_name', 'last_name', 'email_id', 
                      'mobile_no', 'password']
        
        is_valid, res_str = validate_params(req_data, reqd_params)
        if not is_valid:
            self.response["message"] = res_str
            return send_400(self.response)

        try:
            user = User.objects.get(email_id=req_data.get('email_id'))
        except User.DoesNotExist:
            user = User(
                user_id=uuid.uuid1(),
                first_name=req_data.get('first_name'),
                last_name=req_data.get('last_name'),
                middle_name=req_data.get('middle_name'),
                email_id=req_data.get('email_id'),
                mobile_no=req_data.get('mobile_no'),
                password=gen_password_hash(req_data.get('password'))
                )
            user.save()
            self.response["message"] = 'Registered successfully.'
            self.response["result"]["user_id"] = user.user_id
        else:
            self.response["message"] = "Email already registered.Try to login."
            return send_400(self.response)
        return send_200(self.response)
开发者ID:viveksyngh,项目名称:QuizApp,代码行数:31,代码来源:views.py

示例13: register

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import save [as 别名]
def register():
    if request.method == 'POST':
        logger.info('Registration POST: %s%s%s'\
                    % (request.form['email'], \
                       request.form['name'],\
                       request.form['tel']))
        user = User()
        user.name = request.form.get('name', None)
        user.email = request.form.get('email', None)
        user.tel = request.form.get('tel', None)
        user.msg = request.form.get('message', None)

        if not user.is_valid:
            logger.error('No valid form. Request:%s' % request)
            return jsonify(False)

        try:
            user.save()
        except:
            logger.error('Don\'t save in base. Request:%s' % request)
            return jsonify('Error')
        
        logger.info('Register:Done!')
        send_email(user)
        return jsonify(True)

    else:
        return jsonify(False)
开发者ID:shuric80,项目名称:photogallery,代码行数:30,代码来源:views.py

示例14: api_user_add

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import save [as 别名]
def api_user_add(request):
    response = {}
    email = get_param(request, "email")
    password = get_param(request, "password", strip=False)
    password_conf = get_param(request, "password_conf", strip=False)
    errors = {}
    if is_blank(email):
        errors["email"] = "Sorry! You need an e-mail address to sign up."
    elif not is_valid_email(email):
        errors["email"] = "Sorry! Please put a valid e-mail address."
    if is_blank(password):
        errors["password"] = "Sorry! You need a password to sign up."
    if is_blank(password_conf):
        errors["password_conf"] = "Please confirm your password."
    elif password != password_conf:
        errors["password_conf"] = "Oops! Your passwords do not match."
    try:
        User.objects.get(email=email)
        errors["email"] = "Sorry! This e-mail address is being used."
    except User.DoesNotExist:
        pass
    if len(errors.keys()) > 0:
        response["errors"] = errors
        return response, 200
    new_user = User(email=email)
    new_user.set_password(password)
    new_user.save()
    response["user"] = new_user.id
    user_login(request, new_user)
    return response, 201
开发者ID:elesant,项目名称:DjangoBase,代码行数:32,代码来源:views.py

示例15: add_endpoint

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import save [as 别名]
def add_endpoint():
    af = request.form.copy()
    user = User(current_user.id)

    existing_names = [p['name'] for p in user.profile['lrsprofiles']]

    # Make sure name doesn't exist already
    if not af['newname'] in existing_names:
        new_prof = {}
        default = False
        if 'newdefault' in af.keys():
            default = True

        new_prof['name'] = af['newname']
        new_prof['endpoint'] = af['newendpoint']
        new_prof['username'] = af['newusername']
        new_prof['password'] = af['newpassword']
        new_prof['auth'] = "Basic %s" % base64.b64encode("%s:%s" % (new_prof['username'], new_prof['password']))
        new_prof['default'] = default

        if default:
            for profile in user.profile['lrsprofiles']:
                profile['default'] = False

        user.profile['lrsprofiles'].append(new_prof)
        user.save()
    
    return redirect(url_for('me'))
开发者ID:adlnet,项目名称:xci,代码行数:30,代码来源:views.py


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