Exemplo n.º 1
0
def show_route_stops(route_id):
    """
    List all stops on route.
    """
    # TODO: add pagination

    cache_key = f'route_{route_id}'

    routes = redis.get('routes')

    if not routes:
        routes = transport.get_all_routes()
        # cache
        redis.set('routes', json.dumps(routes))
    else:
        routes = json.loads(routes.decode())

    route = routes.get(route_id)

    if cache_key.encode() in redis.keys():
        route_stops = json.loads(redis.get(cache_key).decode())
    else:
        route_stops = transport.get_route_stops(route_id)
        # store to cache
        redis.set(cache_key, json.dumps(route_stops))

    if current_user.is_authenticated:
        user_stops = [stop.code for stop in current_user.stops]
    else:
        user_stops = list()

    return render_template('route_stops.html',
                           route=route,
                           stops=route_stops,
                           user_stops=user_stops)
Exemplo n.º 2
0
def check_if_token_is_revoked(decrypted_token):
    jti = decrypted_token["jti"]
    entry = redis.get(jti)
    if entry is None:
        return False
    else:
        return entry == "true"
Exemplo n.º 3
0
    def validate(self, data, **kwargs):
        # 校验密码和确认密码

        if data["password"] != data["password2"]:
            raise ValidationError(message=Message.password_not_match,
                                  field_name="password")

        # 校验短信验证码
        code = redis.get("sms_%s" % data.get("mobile"))

        if code is None:
            raise ValidationError(message=Message.sms_code_expired,
                                  field_name="sms_code")
        sms_code = str(code, encoding='utf-8')
        if sms_code != data.get("sms_code"):
            raise ValidationError(message=Message.sms_code_error,
                                  field_name="sms_code")
        redis.delete("sms_%s" % data["mobile"])

        # 保存新密码
        user = User.query.filter(User.mobile == data["mobile"]).first()
        user.password = data["password"]
        db.session.commit()

        return data
Exemplo n.º 4
0
def tree_write(self):
    """允许浇水"""
    try:
        tree_list_water = redis.get("tree_list_water")
        if tree_list_water is None:
            return
        tree_list_water = tree_list_water.decode()
        tree_list = tree_list_water.split(",")[:-1]
        print(tree_list)
        for tree in tree_list:
            treeinfo = tree.split("_")
            query = {"_id": treeinfo[0]}
            user_info = mongo.db.user_info_list.find_one(query)
            user_tree_list = user_info.get("user_tree_list", [])
            # 是否允许浇水
            timer = redis.ttl("user_tree_water_%s" % tree)
            if timer == -2 and user_tree_list[int(
                    treeinfo[1])]['allow_water'] == False:
                user_tree_list[int(treeinfo[1])]['allow_water'] = True

            # 是否进入成长期
            timer = redis.ttl("user_tree_growup_%s" % tree)
            if timer == -2 and user_tree_list[int(treeinfo[1])]["status"] == 2:
                if user_tree_list[int(treeinfo[1])]['waters'] > 0:
                    user_tree_list[int(treeinfo[1])]["status"] = 3
                    # tree_list_water_str = "".join(tree_list_water.split(tree + ","))
                    # redis.set("tree_list_water", tree_list_water_str)
            mongo.db.user_info_list.update_one(
                query, {"$set": {
                    "user_tree_list": user_tree_list
                }})
    except Exception as exc:
        # 重新尝试执行失败任务
        print(exc)
Exemplo n.º 5
0
def sms(mobile):
    """发送短信验证码"""
    # 验证手机
    if not re.match("^1[3-9]\d{9}$", mobile):
        return {"errno": status.CODE_VALIDATE_ERROR, "errmsg": message.mobile_format_error}

    # 短信发送冷却时间
    ret = redis.get("int_%s" % mobile)
    if ret is not None:
        return {"errno": status.CODE_INTERVAL_TIME, "errmsg": message.sms_interval_time}

    # 生成验证码
    sms_code = "%06d" % random.randint(0, 999999)
    print(">>>>>>>>>>>>>>>>", sms_code)
    try:
        print(">>>>>>>>>>>>>>>>111>>>>>>>>>>>>>>>>")
        from mycelery.sms.tasks import send_sms
        # 异步发送短信
        send_sms.delay(mobile=mobile, sms_code=sms_code)
        print(">>>>>>>>>>>>>>>>222>>>>>>>>>>>>>>>>")
        # 返回结果
        return {"errno": status.CODE_OK, "errmsg": message.sms_is_send}
    except Exception as e:
        print(">>>>>>>>>>>>>>>>333>>>>>>>>>>>>>>>>")
        return {"errno": status.CODE_SMS_ERROR, "errmsg": message.sms_send_error}
 # todo
#  celery or websocket bug
Exemplo n.º 6
0
def logout():
    sid = request.cookies.get('sid', None)
    session = redis.get(sid)
    if session is not None:
        session = pickle.loads(session)
        user = session.get('user', None)
        if user:
            user['id'] = None
            redis.set(sid, pickle.dumps(session))
Exemplo n.º 7
0
def logout():
    sid = request.cookies.get('sid', None)
    session = redis.get(sid)
    if session is not None:
        session = pickle.loads(session)
        user = session.get('user', None)
        if user:
            user['id'] = None
            redis.set(sid, pickle.dumps(session))
Exemplo n.º 8
0
def get_user():
    if not g.get('user'):
        sid = request.cookies.get('sid', None)
        session = redis.get(sid)
        uid = None
        if session is not None:
            session = pickle.loads(session)
            uid = session.get('user', {}).get('id', None)
            touch(sid, session)
        g.user = User.get_by_id(uid) or AuthUser()
    return g.user
Exemplo n.º 9
0
def get_user():
    if not g.get('user'):
        sid = request.cookies.get('sid', None)
        session = redis.get(sid)
        uid = None
        if session is not None:
            session = pickle.loads(session)
            uid = session.get('user', {}).get('id', None)
            touch(sid, session)
        g.user = User.get_by_id(uid) or AuthUser()
    return g.user
Exemplo n.º 10
0
def monitor_stop(stop_code):
    """
    Get info about certain stop.
    """
    stops = redis.get('stops')

    if not stops:
        stops = transport.get_all_stops()
        redis.set('stops', json.dumps(stops))
    else:
        stops = json.loads(stops.decode())

    stop = stops.get(stop_code)
    stop_info = transport.monitor_stop(stop_code)

    return render_template('stop_info.html', stop=stop, stop_info=stop_info)
Exemplo n.º 11
0
def show_all_routes():
    """
    List all routes.
    """
    # TODO: add pagination

    routes = redis.get('routes')

    if not routes:
        routes = transport.get_all_routes()
        # cache
        redis.set('routes', json.dumps(routes))
    else:
        routes = json.loads(routes.decode())

    return render_template('routes.html', routes=routes)
Exemplo n.º 12
0
def clean_cache():
    """
    Clean Redis cache.
    """
    stops = redis.get('stops')

    if stops:
        redis.delete('stops')

    routes = [k for k in redis.keys() if b'route' in k]

    if routes:
        for r in routes:
            redis.delete(r)

    return jsonify(status='OK')
Exemplo n.º 13
0
def user_disconnect():
    """退出房间"""
    keys_list = redis.keys("*_%s" % request.sid)
    if len(keys_list) > 0:
        room_dict = keys_list[-1]
        uid = redis.get(room_dict).decode()
        room = "_".join(room_dict.decode().split("_")[:2])
        redis.delete(keys_list[-1].decode())
        message = user_log(room, uid, "%s退出了房间")
        socketio.emit("login_response",
                      message,
                      namespace="/mofang",
                      room=room)
        leave_room(room)
    else:
        print("用户%s退出了房间" % request.sid)
Exemplo n.º 14
0
def show_all_stops():
    """
    List all stops.
    """
    # TODO: add pagination

    stops = redis.get('stops')

    if not stops:
        stops = transport.get_all_stops()
        redis.set('stops', json.dumps(stops))
    else:
        stops = json.loads(stops.decode())

    if current_user.is_authenticated:
        user_stops = [stop.code for stop in current_user.stops]
    else:
        user_stops = list()

    return render_template('stops.html', stops=stops, user_stops=user_stops)
Exemplo n.º 15
0
def translate_video_title(what):
	to_language = g.lang_code

	if to_language == "en":
		return what

	key = "{0}_{1}".format(what, to_language)

	translation = redis.get(key)

	if translation:
		return translation

	translator = Translator(to_lang=to_language)
	
	try:
		translation = translator.translate(what)
		redis.set(key, translation)
	except:
		translation = what

	return translation
Exemplo n.º 16
0
    def validate(self, data, **kwargs):
        # 校验密码和确认密码
        if data["password"] != data["password2"]:
            raise ValidationError(message=Message.password_not_match,
                                  field_name="password")

        # 校验短信验证码
        # 1. 从redis中提取验证码
        redis_sms_code = redis.get("sms_%s" % data["mobile"])
        if redis_sms_code is None:
            raise ValidationError(message=Message.sms_code_expired,
                                  field_name="sms_code")
        redis_sms_code = redis_sms_code.decode()
        # 2. 从客户端提交的数据data中提取验证码
        sms_code = data["sms_code"]
        # 3. 字符串比较,如果失败,则抛出异常,否则,直接删除验证码
        if sms_code != redis_sms_code:
            raise ValidationError(message=Message.sms_code_error,
                                  field_name="sms_code")

        redis.delete("sms_%s" % data["mobile"])

        return data
Exemplo n.º 17
0
def list_friend(ticket, randstr, old_mobile, new_mobile, sms_code):
    # 校验防水墙验证码
    params = {
        "aid": current_app.config.get("CAPTCHA_APP_ID"),
        "AppSecretKey": current_app.config.get("CAPTCHA_APP_SECRET_KEY"),
        "Ticket": ticket,
        "Randstr": randstr,
        "UserIP": request.remote_addr,
    }
    # 把字典数据转换成地址栏的查询字符串格式

    params = urlencode(params)
    url = current_app.config.get("CAPTCHA_GATEWAY")
    f = requests.get(url, params=params)
    res = f.json()
    if int(res.get("response")) != 1:
        # 验证失败
        return {
            "errno": status.CODE_CAPTCHA_ERROR,
            "errmsg": message.captcaht_no_match
        }

    # 查询当前登录用户
    current_user_id = get_jwt_identity()
    user = User.query.get(current_user_id)
    # print(">>>>", user)     # <User: 17319006603>
    # print(">>>>", user.mobile, type(user.mobile))   # 17319006603 <class 'str'>

    if user is None:
        return {
            "errno": status.CODE_NO_USER,
            "errmsg": message.user_not_exists,
        }
    if old_mobile == new_mobile:
        return {
            "errno": status.CHANGE_PASSWD_ERROR,
            "errmsg": message.password_change_error,
        }
    elif user.mobile != old_mobile:
        return {
            "errno": status.CODE_NO_ACCOUNT,
            "errmsg": message.mobile_is_null,
        }

    # 校验短信验证码
    # 1. 从redis中提取验证码
    redis_sms_code = redis.get("sms_%s" % old_mobile)
    if redis_sms_code is None:
        raise ValidationError(message=message.sms_code_expired,
                              field_name="sms_code")
    redis_sms_code = redis_sms_code.decode()
    # 2. 从客户端提交的数据data中提取验证码
    sms_code = sms_code
    # 3. 字符串比较,如果失败,则抛出异常,否则,直接删除验证码
    if sms_code != redis_sms_code:
        raise ValidationError(message=message.sms_code_error,
                              field_name="sms_code")

    redis.delete("sms_%s" % old_mobile)

    user.mobile = new_mobile
    db.session.commit()

    return {
        "errno": status.CODE_OK,
        "errmsg": message.ok,
        "mobile": new_mobile
    }