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


Python User.get_or_create方法代码示例

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


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

示例1: facebook_authorized

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_or_create [as 别名]
def facebook_authorized(resp):
    next_url = request.args.get('next') or url_for('index')
    if resp is None or 'access_token' not in resp:
        return redirect(next_url)

    session['logged_in'] = True
    session['facebook_token'] = (resp['access_token'], '')
    data = facebook.get('/me').data
    session['data'] = data
    User.get_or_create(
        email=data['email'],
        name=data['name'],
        facebook_id=data['id'],
    )
    return redirect(url_for('index'))
开发者ID:maxgutman,项目名称:mkopo,代码行数:17,代码来源:app.py

示例2: verify_password

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_or_create [as 别名]
def verify_password(username_or_token, password):
    # first try to authenticate by token
    if password == "facebook":
        auth = fb.get_session(token=username_or_token)
        resp = auth.get('/me')
        if resp.status_code == 200:
            fb_user = resp.json()
            # user = User.query.filter_by(email=fb_user.get('email')).first()
            birthday = fb_user['birthday'][6:10] + fb_user['birthday'][0:2] + fb_user['birthday'][3:5]
            user = User.get_or_create(fb_user['email'], fb_user['name'], fb_user['id'], birthday)
        else:
            return False
    else:
        user = User.verify_auth_token(username_or_token)

    if not user:
        # try to authenticate with username/password
        user = User.query.filter_by(email = username_or_token).first()
        if not user:
            return False
        if user.password == None:
            return False
        if not user.verify_password(password):
            return False
    g.user = user
    return True
开发者ID:sunghoonma,项目名称:Dream,代码行数:28,代码来源:api.py

示例3: create

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_or_create [as 别名]
def create():
    context = get_context()
    context.update(dict(success=False))
    user = User.get_or_create(email=context['email'])
    all_users = User.get_all(exclude_user_id=user.id)
    context.update({'all_users': list(all_users)})
    if request.method == 'POST':
        group = Group.get_or_create(name=request.form['group_name'], status='Pending')
        UserGroup.get_or_create(
            user_id=user.id,
            group_id=group.id,
            loan_amount=request.form['loan_amount'],
            repaid_amount='0',
        )
        all_users = User.get_all(exclude_user_id=user.id)
        for _user in all_users:
            UserGroup.get_or_create(
                user_id=_user.id,
                group_id=group.id,
                loan_amount='0',
                repaid_amount='0',
            )

        context.update(dict(success=True))
    return render_template('create.html', **context)
开发者ID:maxgutman,项目名称:mkopo,代码行数:27,代码来源:app.py

示例4: login_required_dec

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_or_create [as 别名]
 def login_required_dec(*args, **kwargs):
     current_user = endpoints.get_current_user()
     if current_user is None:
         raise endpoints.UnauthorizedException('Invalid token')
     current_user_model = User.get_or_create(current_user.email())
     kwargs[DEC_KEYS.USER] = current_user_model
     return func(*args, **kwargs)
开发者ID:csarradet,项目名称:fsndp4,代码行数:9,代码来源:api.py

示例5: get_context

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_or_create [as 别名]
def get_context():
    data = session.get('data')
    if data:
        user = User.get_or_create(email=data['email'])
        invite_groups = user.get_invite_groups()

        if 'work' in data:
            employer = data['work'][0]['employer']['name']
            position = data['work'][0]['position']['name']
        else:
            employer = user.employer
            position = user.position

        if 'location' in data:
            location = data['location']['name']
        else:
            location = user.location

        return {
            'user': user,
            'email': user.email or data['email'],
            'name': user.name or data['name'],
            'employer': employer,
            'position': position,
            'location': location,
            'bio': user.bio,
            'data': data,
            'photo_url': 'https://graph.facebook.com/%s/picture' % data['id'],
        }
    return {}
开发者ID:maxgutman,项目名称:mkopo,代码行数:32,代码来源:app.py

示例6: create_test_data

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_or_create [as 别名]
    def create_test_data(self):
        user = User.get_or_create(123)
        User.get_or_create(12345)
        db.session.commit()

        team1 = Team.create(user, 'EnvyUs', 'fr', 'nv', ['76561198053858673'])
        team2 = Team.create(user, 'Fnatic', 'se', 'fntc',
                            ['76561198053858673'])
        server = GameServer.create(user, '127.0.0.1', '27015', 'password')
        server.in_use = True

        GameServer.create(user, '127.0.0.1', '27016', 'password')
        db.session.commit()

        Match.create(user, team1.id, team2.id, 1, False,
                     'Map {MAPNUMBER}', ['de_dust2', 'de_cache', 'de_mirage'], server.id)
        db.session.commit()
开发者ID:mattikus,项目名称:get5-web,代码行数:19,代码来源:get5_test.py

示例7: google_oauth

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_or_create [as 别名]
def google_oauth(token, session):
    """
    Authenticates with google using a short-lived token, and getting a long
    one in the process.
    The following will be stored in session:
    * user_id - Local ID of the user
    * username - Name of the user
    * access_token - Long lived token received from google
    * email - User's email
    * provider - The login provider (google)
    * gplus_id - ID of the user in google

    Returns: http response with "ok" in case of success, or an http error
             in the case of an error.
    """
    try:
        credentials = flow.step2_exchange(token)
    except FlowAExchangeError:
        return ('Failed to upgrade the authorization token (step2)', 401)

    # Check that the access token is valid
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'
           % access_token)
    answer = requests.get(url)
    result = answer.json()
    # If there was an error in the access token info, abort
    if result.get('error') is not None:
        return (result.get('error'), 500)

    # Verify that the access token is used for the intended user
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        return ("Token's used ID doesn't match given user", 401)

    # Verify that the access token is valid for this app.
    if result['issued_to'] != flow.client_id:
        return ("Token's client ID does not match app's", 401)

    stored_access_token = session.get('access_token')
    stored_gplus_id = session.get('gplus_id')
    if stored_access_token is not None and gplus_id == stored_gplus_id:
        return ('Current user is already connected', 200)

    session['access_token'] = credentials.access_token
    session['gplus_id'] = gplus_id

    # Get user info
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)
    data = answer.json()

    session['user_id'] = User.get_or_create(data['email']).id
    session['username'] = data['name']
    session['email'] = data['email']
    session['provider'] = 'google'
    return ('ok', 200)
开发者ID:diogovk,项目名称:fullstack-webdev-catalog,代码行数:60,代码来源:oauth.py

示例8: create

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_or_create [as 别名]
def create():
    context = get_context()
    context.update(dict(success=False))
    user = User.get_or_create(email=context['email'])
    all_users = User.get_all(exclude_user_id=user.id)
    context.update({'all_users': list(all_users)})
    if request.method == 'POST':
        context.update(dict(success=True))
    return render_template('create.html', **context)
开发者ID:renubora,项目名称:mkopo,代码行数:11,代码来源:app.py

示例9: create_or_login

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_or_create [as 别名]
def create_or_login(resp):
    match = _steam_id_re.search(resp.identity_url)
    steam_id = match.group(1)
    if (not steam_id) or ('WHITELISTED_IDS' in app.config and steam_id not in app.config['WHITELISTED_IDS']):
        return 'Sorry, you don\'t have access yet :)'

    g.user = User.get_or_create(steam_id)
    steamdata = steamid.get_steam_userinfo(
        g.user.steam_id, app.config['STEAM_API_KEY'])
    g.user.name = steamdata['personaname']
    db.session.commit()
    session['user_id'] = g.user.id
    return redirect(oid.get_next_url())
开发者ID:mattikus,项目名称:get5-web,代码行数:15,代码来源:__init__.py

示例10: create_or_login

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_or_create [as 别名]
def create_or_login(resp):
    match = _steam_id_re.search(resp.identity_url)
    steam_id = match.group(1)
    is_in_whitelist = (steam_id in config_setting('WHITELISTED_IDS'))
    if (not steam_id) or (config_setting('WHITELISTED_IDS') and not is_in_whitelist):
        return 'Sorry, you don\'t have access to this webpanel'

    g.user = User.get_or_create(steam_id)
    steamdata = steamid.get_steam_userinfo(
        g.user.steam_id, app.config['STEAM_API_KEY'])
    g.user.name = steamdata['personaname']
    db.session.commit()
    session['user_id'] = g.user.id
    return redirect(oid.get_next_url())
开发者ID:splewis,项目名称:get5-web,代码行数:16,代码来源:__init__.py

示例11: profile

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_or_create [as 别名]
def profile():
    context = get_context()
    context.update(dict(success=False))
    if request.method == 'POST':
        user = User.get_or_create(email=context['email'])
        user.employer = request.form['employer']
        user.position = request.form['position']
        user.location = request.form['location']
        user.bio = request.form['bio']
        user.save()
        context = get_context()
        context.update(dict(success=True))
        print request.form
    return render_template('profile.html', **context)
开发者ID:maxgutman,项目名称:mkopo,代码行数:16,代码来源:app.py

示例12: signup_start

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_or_create [as 别名]
    def signup_start(self, data):
        god_info = get_god_info(data["login"])
        if not god_info:
            self.send_error_msg("Unknown god name")
            return
        self.auth_name = god_info['godname']

        user, created = User.get_or_create(god_name=self.auth_name)
        if created or user.motto_login is None or len(user.motto_login) < MOTTO_LEN:
            motto = rnd_gen(MOTTO_LEN)
            user.motto_login = motto
        else:
            motto = user.motto_login
        user.save()

        self.send("sign", {"motto": motto})
开发者ID:Preveter,项目名称:gvd,代码行数:18,代码来源:server.py

示例13: parser_song

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_or_create [as 别名]
def parser_song(song_id, artist):
    tree = get_tree(SONG_URL.format(song_id))
    song = Song.objects.filter(id=song_id)
    r = post(COMMENTS_URL.format(song_id))
    if r.status_code != 200:
        print 'API Error: Song {}'.format(song_id)
        return
    data = r.json()
    if not song:
        for404 = tree.xpath('//div[@class="n-for404"]')
        if for404:
            return

        try:
            song_name = tree.xpath('//em[@class="f-ff2"]/text()')[0].strip()
        except IndexError:
            try:
                song_name = tree.xpath(
                    '//meta[@name="keywords"]/@content')[0].strip()
            except IndexError:
                print 'Fetch limit!'
                time.sleep(10)
                return parser_song(song_id, artist)
        song = Song(id=song_id, name=song_name, artist=artist,
                    comment_count=data['total'])
        song.save()
    else:
        song = song[0]
    comments = []
    for comment_ in data['hotComments']:
        comment_id = comment_['commentId']
        content = comment_['content']
        like_count = comment_['likedCount']
        user = comment_['user']
        if not user:
            continue
        user = User.get_or_create(id=user['userId'], name=user['nickname'],
                                  picture=user['avatarUrl'])
        comment = Comment.get_or_create(id=comment_id, content=content,
                                        like_count=like_count, user=user,
                                        song=song)
        comment.save()
        comments.append(comment)
    song.comments = comments
    song.save()
    time.sleep(1)
    return song
开发者ID:cxiaodian,项目名称:commentbox,代码行数:49,代码来源:parser.py

示例14: callback

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_or_create [as 别名]
def callback():
    """ Handles the home page rendering."""

    if request.data:
        data = json.loads(request.data)
    else:
        data = request.form

    email_from = data['from']
    name, email = parse_email(email_from) 
    
    user = User.get_or_create(name=name, email=email)
    subject = data['subject']

    reply_regex = re.compile('[Rr][Ee]\s*\:')
    fwd_regex = re.compile('[Ff][Ww][Dd]*\s*\:')

    subject = re.sub(reply_regex, '', subject).strip()
    subject = re.sub(fwd_regex, '', subject).strip()

    thread = Email.get_thread(subject)

    if 'time' in data:
        time = parse(data['time'])
    else:
        time = datetime.datetime.now()

    text = unquote(data['text'])

    if 'html' in data:
        html = unquote(data['html'])
    else:
        html = text

    email = Email(
            _from=user, 
            to=data['to'], 
            subject=subject,
            text=text,
            html=html,
            time=time,
            thread=thread,
        )

    email.save()
    return 'Thanks Swift'
开发者ID:v,项目名称:mailblog,代码行数:48,代码来源:app.py

示例15: verify_password

# 需要导入模块: from models import User [as 别名]
# 或者: from models.User import get_or_create [as 别名]
def verify_password(username_or_token, password):
    print "auth.verify_password"
    # first try to authenticate by token
    if password == "facebook":
        auth = fb.get_session(token=username_or_token)
        resp = auth.get('/me')
        if resp.status_code == 200:
            fb_user = resp.json()
            # user = User.query.filter_by(email=fb_user.get('email')).first()
            birthday = fb_user['birthday'][6:10] + fb_user['birthday'][0:2] + fb_user['birthday'][3:5]
            user = User.get_or_create(fb_user['email'], fb_user['name'], fb_user['id'], birthday)
            conn = httplib.HTTPSConnection("graph.facebook.com")
            params = urllib.urlencode({'redirect_uri':WISHB_SERVER_URI,
                                       'client_id':FB_CLIENT_ID,
                                       'client_secret':FB_CLIENT_SECRET,
                                       'grant_type':'fb_exchange_token',
                                       'fb_exchange_token':username_or_token})
            conn.request("GET","/oauth/access_token?"+ params)
            response = conn.getresponse()
            resp_body = response.read()

            longLivedAccessToken=resp_body.split('&')[0].split('=')[1]

            UserSocial.upsert_user(user.id, 'facebook', fb_user['id'], longLivedAccessToken)
            # c.gauge(gauge'Facebook_Login', 1, delta=True)

        else:
            return False
    else:
        user = User.verify_auth_token(username_or_token)

    if not user:
        # try to authenticate with username/password
        user = User.query.filter_by(email = username_or_token).first()
        if not user:
            return False
        if user.password == None:
            return False
        if not user.verify_password(password):
            return False
        # c.gauge('Email_Login', 1, delta=True)
        # logging_auth(user.id, "login", "email")

    g.user = user
    return True
开发者ID:masunghoon,项目名称:WishB_Backend,代码行数:47,代码来源:auth.py


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