Python flask实战订餐系统微信小程序-33通过数据库查询完善注册登录接口

wechat xuhss 510℃ 0评论

通过数据库查询完善注册登录接口

from common.models.member.Member import Member
from common.models.member.OauthMemberBind import OauthMemberBind
from common.libs.Helper import getCurrentDate

@route_api.route( "/member/login", methods = ['GET', 'POST'] )
def login():
    resp = {'code':200,'msg':'操作成功', 'data':{}}
    req = request.values
    #app.logger.info(req)

    code = req['code'] if 'code' in req else ''
    if not code or len(code)<1:
        resp['code'] = -1
        resp['msg'] = '需要code'
        return jsonify(resp)

    url = 'https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code'\
        .format(app.config['MINA_APP']['appid'],app.config['MINA_APP']['appkey'],code)

    r = requests.get(url)
    res = json.loads(r.text)
    openid =  res['openid']
    '''
    判断是否已经注册过,已注册直接返回信息
    '''
    bind_info = OauthMemberBind.query.filter_by(openid=openid,type=1).first()
    if not bind_info:
        nickname = req['nickname'] if 'nickname' in req else ''
        sex = req['gender'] if 'gender' in req else ''
        avatar = req['avatarUrl'] if 'avatarUrl' in req else ''

        model_name = Member()
        model_name.nickname = nickname
        model_name.sex = sex
        model_name.avatar = avatar
        model_name.salt = ''
        model_name.updated_time = model_name.created_time = getCurrentDate()
        db.session.add(model_name)
        db.session.commit()

        model_bind = OauthMemberBind()
        model_bind.member_id = model_name.id
        model_bind.type = 1
        model_bind.openid = openid
        model_bind.extra = ''
        model_bind.updated_time = model_bind.created_time = getCurrentDate()
        db.session.add(model_bind)
        db.session.commit()

        bind_info = model_bind

    member_info = Member.query.filter_by(id = bind_info.member_id).first()
    resp['data'] = {'nickname':member_info.nickname}
    app.logger.info(member_info.nickname)

    return jsonify(resp)        

转载请注明:xuhss » Python flask实战订餐系统微信小程序-33通过数据库查询完善注册登录接口

喜欢 (14)

您必须 登录 才能发表评论!