Пример #1
0
def get_access_token(wx):
    """
    获取微信access_token
    :param wx: [dict]
    :return:
    """
    app_id, app_secret = map(wx.get, ('app_id', 'app_secret'))
    if not (app_id and app_secret):
        return

    key = 'wx:%s:access_token' % app_id
    access_token = redis_client.get(key)
    if access_token:
        return access_token

    wx_url = 'https://api.weixin.qq.com/cgi-bin/token'
    params = {
        'grant_type': 'client_credential',
        'appid': app_id,
        'secret': app_secret
    }
    resp_json = requests.get(wx_url, params=params).json()
    access_token, expires_in = map(resp_json.get,
                                   ('access_token', 'expires_in'))
    if not (access_token and expires_in):
        return

    redis_client.set(key, access_token)
    redis_client.expire(key, int(expires_in) - 600)  # 提前10分钟更新access_token
    return access_token
Пример #2
0
def get_endpoint_specific_json(num):
    page = request.args.get('page', 1, type=int)
    # creating unique redis key for product id & page number
    cached_response_redis_key = f"result_{num}_{page}"
    # REDIS cache used
    # Trying to get data from cache with unique redis key
    result = redis_client.get(cached_response_redis_key)
    if result is None:
        print(
            "Could not find GET result in cache, REST API response served from PostgreSQL db"
        )
        # Getting data from the PostgreSQL db
        result = get_paginated_list(Products,
                                    '/get-endpoint-json/' + str(num),
                                    page=request.args.get('page', 1, type=int),
                                    per_page=app.config['REVIEWS_PER_PAGE'],
                                    limit=app.config['REVIEWS_MAX'],
                                    id=num)
        # Saving data to cache with unique identifier for product id & page number
        redis_client.set(cached_response_redis_key, json.dumps(result))
        redis_client.expire(cached_response_redis_key, timedelta(seconds=10))
    else:
        print("Found cached GET response, serving data from REDIS")
        result = json.loads(result)

    return jsonify(result)  # does not keep order, but beautified
Пример #3
0
def get_jsapi_ticket(wx):
    """
    获取微信jsapi_ticket
    :param wx: [dict]
    :return:
    """
    app_id, app_secret = map(wx.get, ('app_id', 'app_secret'))
    if not (app_id and app_secret):
        return

    key = 'wx:%s:jsapi_ticket' % app_id
    jsapi_ticket = redis_client.get(key)
    if jsapi_ticket:
        return jsapi_ticket

    access_token = get_access_token(wx)
    if not access_token:
        return

    wx_url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket'
    params = {'access_token': access_token, 'type': 'jsapi'}
    resp_json = requests.get(wx_url, params=params).json()
    jsapi_ticket, expires_in = map(resp_json.get, ('ticket', 'expires_in'))
    if not (jsapi_ticket and expires_in):
        return

    redis_client.set(key, jsapi_ticket)
    redis_client.expire(key, int(expires_in) - 600)  # 提前10分钟更新jsapi_ticket
    return jsapi_ticket
Пример #4
0
        def __decorated(*args, **kwargs):
            print(redis_key)

            response = redis_client.get(redis_key)

            # NOTE: This is a very hard cache. It doesn't look at any of the request params

            if response:
                return json.loads(response)
            else:
                response = f(*args, **kwargs)
                redis_client.set(redis_key, json.dumps(response))
                redis_client.expire(redis_key, 60)
                return response
Пример #5
0
def get_roles_from_redis(user):
    result = redis_client.hget("user_{user_id}".format(user_id=user.id),
                               "roles")
    if result:
        return json.loads(result.decode('utf-8'))
    roles = set()
    if user.roles:
        for role in user.roles:
            roles.add(role.name)
        redis_client.hset("user_{user_id}".format(user_id=user.id), "roles",
                          json.dumps(list(sorted(roles))))
        redis_client.expire("user_{user_id}".format(user_id=user.id),
                            current_app.config['JWT_ACCESS_TOKEN_EXPIRES'])
    return list(sorted(roles))
Пример #6
0
def get_permissions_from_redis(user_id):
    result = redis_client.hget("user_{user_id}".format(user_id=user_id),
                               "permissions")
    if result:
        return json.loads(result.decode('utf-8'))
    permissions = set()
    user = User.query.filter_by(id=user_id).first()
    if user.roles:
        for role in user.roles:
            for permission in role.permissions:
                permissions.add(permission.path)
    if permissions:
        redis_client.hset("user_{user_id}".format(user_id=user_id),
                          "permissions", json.dumps(list(sorted(permissions))))
        redis_client.expire("user_{user_id}".format(user_id=user_id),
                            current_app.config['JWT_ACCESS_TOKEN_EXPIRES'])
    return list(sorted(permissions))
Пример #7
0
def update_user(user_id):
    user = User.query.filter_by(id=user_id).first()
    if user:
        user.username = request.json.get("username", user.username)
        user.realname = request.json.get("realname", user.realname)
        user.email = request.json.get("email", user.email)
        user.status = request.json.get("status", user.status)
        try:
            db.session.add(user)
            db.session.commit()
            # 若禁用了,则不允许登录
            if user.status == 0:
                redis_client.set(
                    "user_token_expired_{id}".format(id=user_id),
                    'true',
                    ex=current_app.config['JWT_ACCESS_TOKEN_EXPIRES'])
                redis_client.expire("user_{id}".format(id=user_id), 1)
            return generate_response(data=user_schema.dump(user))
        except Exception as e:
            current_app.logger.error(str(e))
            db.session.rollback()
    return generate_response(code_msg=Code.UPDATE_USER_PROFILE_FAILED)
Пример #8
0
        return

    try:
        weixin_user_id = decrypt(token)
    except Exception, e:
        current_app.logger.error(e)
        return

    g.user = WeixinUser.query_by_id(weixin_user_id)
    if not g.user:
        return

    key = 'wx:user:%s:info' % g.user.id
    if redis_client.get(key) != 'off':
        redis_client.set(key, 'off')
        redis_client.expire(key, 28800)  # 每隔八小时更新微信用户基本信息
        info = get_user_info(current_app.config['WEIXIN'], g.user.openid)
        if info:
            g.user.update_weixin_user(**info)


def user_authentication():
    """
    用户身份认证
    :return:
    """
    g.user = None  # g.user
    token = request.environ.get('HTTP_AUTHORIZATION')
    if not token:
        return
Пример #9
0
def my_test():
    print('ok')
    dict = {"name": "张三", "age": 112}

    redis_client.expire('Round2', 1)  #设置0.01秒过期
    return jsonify(dict)
Пример #10
0
def persist_request(bid_id):
    # Persist stored bid longer for future collection.
    redis_client.expire(KEY_SPACE_BID + bid_id, PERSIST_LONG_SECONDS)
Пример #11
0
def store_request(bid_id, bid_request):
    # Store bid request for a short period.
    redis_client.hset(
        KEY_SPACE_BID + bid_id, 'request', json.dumps(bid_request))
    redis_client.expire(KEY_SPACE_BID + bid_id, PERSIST_SHORT_SECONDS)
    return bid_id