예제 #1
0
파일: orders.py 프로젝트: Daiiyue/aijia
def save_order():
    user_id = g.user_id

    order_data = request.get_json()
    if not order_data:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    house_id = order_data.get("house_id")
    start_date_str = order_data.get("start_date")
    end_date_str = order_data.get("end_date")

    if not all((house_id, start_date_str, end_date_str)):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        start_date = datetime.datetime.strftime(start_date_str, "%Y-%m-%d")
        end_date = datetime.datetime.strftime(end_date_str, "%Y-%m-%d")
        assert start_date <= end_date
        days = (end_date - start_date).days + 1

    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.PARAMERR, errmsg="日期格式错误")

    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='获取房屋信息失败')
    if not house:
        return jsonify(errno=RET.NODATA, errmsg='房屋不存在')

    if user_id == house.user_id:
        return jsonify(errno=RET.ROLEERR, errmsg='不能预定自己的房屋')
예제 #2
0
def pic_info():
    """头像信息"""
    user = g.user
    if request.method == 'GET':
        context = {
            'user': user.to_dict() if user else None,
        }
        return render_template('news/user_pic_info.html', context=context)
    if request.method == 'POST':
        # 接收参数,校验参数
        avatar_file = request.files.get('avatar')
        try:
            avatar_data = avatar_file.read()
        except Exception as e:
            current_app.logger(e)
            return jsonify(errno=response_code.RET.PARAMERR, errmsg='参数错误')
        try:
            # 上传头像到存储平台
            key = upload_file(avatar_data)
        except Exception as e:
            return jsonify(errno=response_code.RET.THIRDERR, errmsg='上传失败')
        # 保存头像信息
        user.avatar_url = key
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            return jsonify(errno=response_code.RET.DBERR, errmsg='头像保存失败')
        # 响应上传的结果
        # 构造响应数据
        data = {'avatar_url': constants.QINIU_DOMIN_PREFIX + key}
        print(data)
        return jsonify(errno=response_code.RET.OK, errmsg='上传成功', data=data)
예제 #3
0
def get_img_code():
    """
    生成图片验证码并返回
    :return:
    """
    # 1:取到参数
    image_code_id = request.args.get("imageCodeId", None)
    # 2:判断参数是否为空
    if not image_code_id:
        return abort(403)
    # 3:从工具包中生成图片验证码,返回值是元组
    name, text, image = captcha.generate_captcha()
    print(text)

    # 4:将图片验证码保存到redis中
    try:
        redis_store.setex("ImageCodeId:" + image_code_id,
                          constants.IMAGE_CODE_REDIS_EXPIRES, text)
    except Exception as e:
        current_app.logger(e)
        abort(500)
    # 5:返回验证码图片到前端
    response = make_response(image)
    # 设置响应数据类型
    response.headers['Content-Type'] = "image/jpg"
    return response
예제 #4
0
def user_news_list():
    """用户发布新闻"""
    page = request.form.get("p", 1)

    # 判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger(e)
        page = 1

    user = g.user
    news_list = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(
            page, constants.USER_COLLECTION_MAX_NEWS, False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_review_dict())

    data = {
        "news_list": news_dict_list,
        "total_page": total_page,
        "current_page": current_page,
    }

    return render_template("news/user_news_list.html", data=data)
예제 #5
0
def get_areas():
    # 先从缓存中获取数据 如果没有再从数据库里查询
    try:
        area_dict_li = redis_store.get("Area")
        if area_dict_li:
            return jsonify(error=RET.OK, errmsg="ok", data=eval(area_dict_li))
    except Exception as e:
        current_app.logger(e)

    try:
        areas = Area.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR, errmsg="数据库查询失败")

    area_dict_li = []

    for area in areas:
        area_dict_li.append(area.to_dict())
    current_app.logger.debug(len(area_dict_li))
    # 缓存到redis里面 方面查询的时候使用
    try:
        redis_store.set("Area", area_dict_li, constants.AREA_INFO_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger(e)

    return jsonify(error=RET.OK, errmsg="OK", data=area_dict_li)
예제 #6
0
def analyze_graph():
    """This analyze page is coming from the Explore page"""
    current_app.logger.info('analyze_graph()')
    try:
        ui_api = UIAPI(current_app)

        # Load JSON formatted String from API.
        # This will be piped into Javascript as a JS Object accessible in that scope
        measurement_types_and_info = __get_all_measurement_info()
        if 'error' in measurement_types_and_info:
            current_app.logger(measurement_types_and_info['error'])
            raise Exception("Error processing API call for measurement types.")

        measurement_types_and_info_json = json.dumps(
            measurement_types_and_info)
        measurement_types = sorted(
            measurement_types_and_info['measurement_info'].keys())
        selected_systemIDs = map(
            lambda s: s.encode('ascii'),
            request.form.get('selectedSystems').strip("\"").split(','))
        systems_and_measurements = json.dumps(
            __get_systems_and_measurements(selected_systemIDs))

        return render_template("analyze.html", **locals())
    except:
        traceback.print_exc()
        return render_template("error.html"), 400
예제 #7
0
def get_latest():
    if request.method == 'GET':
        page_number = 0
    else:
        page_number = int(request.json.get('page', 0))
    begin_time = datetime.datetime.now() - datetime.timedelta(weeks=1)  # 一周以内
    dummy_id = ObjectId.from_datetime(begin_time)
    try:
        counts = mongo.db.industrial.count_documents(
            {'_id': {
                '$gte': dummy_id
            }})
        # FIXME the skip prference is versy pool
        cursor = mongo.db.industrial.find({
            '_id': {
                '$gte': dummy_id
            }
        }).skip(page_number * 10).limit(10)
    except Exception as e:
        current_app.logger(e)
        return to_json(500)
    return to_json(200,
                   data={
                       "items":
                       list(
                           filter(lambda item: item is not None,
                                  map(format_return_data, cursor))),
                       'page':
                       ceil(counts / 10)
                   })
예제 #8
0
파일: house.py 프로젝트: equalll/iHome-1
def get_area():
    """
    1.获取城区信息
    2.组织响应,返回数据
    :return: 
    """
    try:
        areas_json_str = redis_store.get('areas')
        if areas_json_str:
            areas_dict_li = json.loads(areas_json_str)
            return jsonify(errno=RET.OK, errmsg='OK', data=areas_dict_li)
    except Exception as e:
        current_app.logger.error(e)

    # 1.获取城区信息
    try:
        areas = Area.query.all()
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg='查询城区信息失败')
    # 2. 组织数据
    areas_dict_list = []
    for area in areas:
        areas_dict_list.append(area.to_dict())

    try:
        redis_store.set('areas', json.dumps(areas_dict_list),
                        constants.AREA_INFO_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)

    return jsonify(errno=RET.OK, errmsg='OK', data=areas_dict_list)
예제 #9
0
def login():
    req_obj = request.json
    password = req_obj.get('passport')
    mobile = req_obj.get('mobile')
    print([password, mobile])

    if not all([password, mobile]):
        return jsonify(errno=RET.DATAERR, errmsg='数据缺少')

    try:
        user_select = User.query.filter_by(mobile=mobile).first()

    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DATAERR, errmsg='数据库查询失败')

    if not user_select:
        return jsonify(errno=RET.DATAERR, errmsg='数据库查询不到')

    if not user_select.check_password(password):
        return jsonify(errno=RET.DATAERR, errmsg='用户名或者密码错误')

    session['user_id'] = user_select.id
    session['nick_name'] = user_select.nick_name
    session["mobile"] = user_select.mobile
    print(session["mobile"])

    print('登录成功')

    return jsonify(errno=RET.OK, errmsg='OK')
예제 #10
0
def get_user_info():
    '''用户中心'''
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    if request.method == "GET":
        data = {'user_info': user.to_dict() if user else None}
        return render_template('news/user_base_info.html', data=data)
    if request.method == "POST":
        signature = request.json.get('signature')
        nick_name = request.json.get('nick_name')
        gender = request.json.get('gender')
        if gender not in (['MAN', 'WOMAN']):
            return jsonify(errno=RET.DATAERR, errmsg='数据错误')
        if not all([signature, nick_name, gender]):
            return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

        try:
            user = User.query.get(user.id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库错误')
        user.signature = signature
        user.nick_name = nick_name
        user.gender = gender

        try:
            db.session.commit()
        except Exception as e:
            current_app.logger(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg='数据库错误')
        return jsonify(errno=RET.OK, errmsg='提交成功')
예제 #11
0
def generate_image_code():
    '''
    生成图片验证码:获取参数-校验参数-业务处理-返回结果
    1. 获取参数,查询字符串形式,args
    2. 校验参数uuid是否存在,如果不存在,直接return
    3. 调用captcha生成图片验证码:name text image
    4. 在服务器redis数据库中存储图片验证码
    5. 返回图片本身,使用相应对象
    reponse = make_response
    reture response
    6. 修改相应的数据类型 image/jpg
    :return:
    '''

    # 获取前端传入的uuid,作为图片验证码的后缀名保存到redis数据库中
    image_code_id = request.args.get('image_code_id')
    # 判断获取结果
    if not image_code_id:
        return jsonify(errno=RET.PARAMERR, errmsg='参数缺失')
    # 调用captcha工具生成图片验证码
    name, text, image = captcha.generate_captcha()
    # 在redis数据库中储存text
    try:
        redis_store.setex('ImageCode' + image_code_id,
                          constants.IMAGE_CODE_REDIS_EXPIRES, text)
    except Exception as e:
        current_app.logger(errno=RET.DBERR, errmsg='保存图片验证码失败')
    else:
        # 返回图片给前端,使用make_response
        response = make_response(image)
        # 修改响应的数据类型
        response.headers['Content-Type'] = 'image/jpg'
        # 返回响应
        return response
예제 #12
0
def get_areas():
    """
    获取城区信息:
    """
    # 1. 从数据库中获取所有的城区信息
    # 先尝试从缓存中获取城区的信息,如果获取到,直接返回,如果获取不到,再去查询数据库
    try:
        area_json_str = redis_store.get("ares")
        if area_json_str:
            areas_dict_li = json.loads(area_json_str)
            return jsonify(errno=RET.OK, errmsg='OK', data=areas_dict_li)
    except Exception as e:
        current_app.logger.error(e)

    try:
        areas = Area.query.all()
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg='查询城区信息失败')

    # 2. 组织数据,返回应答
    areas_dict_li = []
    for area in areas:
        areas_dict_li.append(area.to_dict())

    # redis设置缓存
    try:
        redis_store.set("areas", json.dumps(areas_dict_li),
                        constants.AREA_INFO_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)

    return jsonify(errno=RET.OK, errmsg='OK', data=areas_dict_li)
예제 #13
0
def generate_image_code():
    """
    生成图片验证码
    1、获取参数,uuid,使用request.args查询字符串参数
    2、判断参数是否存在,如果不存在,直接return
    3、调用captcha工具,生成图片验证码
    name,text,image
    4、在redis数据库中存储图片验证码的text内容
    5、返回图片给前端
    """
    # 获取查询字符串形式的参数
    image_code_id=request.args.get("image_code_id")
    # 如果参数不存在,直接return
    if not image_code_id:
        return jsonify(errno=RET.PARAMERR,errmsg="参数缺失")
    # 调用captcha生成图片验证码
    name,text,image=captcha.generate_captcha()
    # 存储图片验证码的text到redis数据库中
    try:
        redis_instance.setex('ImageCode'+image_code_id,constants.IMAGE_CODE_REDIS_EXPIRES,text)
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg='保存数据失败')
        # 返回图片
    response=make_response(image)
    # 设置响应的类型为image/jpg
    response.headers['Content-Type'] = 'image/jpg'
    return response
예제 #14
0
def user_news_release():
    """新闻发布"""
    user = g.user_id
    if not user:
        return redirect("/")
    if request.method == "GET":
        category_list = []
        try:
            category_mode = Category.query.all()
        except Exception as e:
            current_app.logger(e)
            return jsonify(errno=RET.DBERR, errmsg="数据错误")
        for category in category_mode:
            category_list.append(category.to_dict())
        if category_list:
            category_list.pop(0)

        data = {"user": user.to_dict(), "categories": category_list}
        return render_template("news/user_news_release.html", data=data)
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")
    content = request.form.get("content")
    if not all([title, category_id, digest, index_image, content]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        index_image = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="图片错误")
    try:
        key = storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")

    new = News()
    new.category_id = category_id
    new.digest = digest
    new.content = content
    new.index_image_url = key
    new.title = title
    new.status = 1

    user.news_list.append(new)
    try:
        db.session.add(new)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库保存错误")
    return jsonify(errno=RET.OK, errmsg="ok")
예제 #15
0
def news_review_detail(news_id):
    new = None
    try:
        new = News.query.get(news_id)
    except Exception as e:
        current_app.logger(e)
    data = {"news": new.to_dict() if new else None}
    return render_template("admin/news_review_detail.html", data=data)
 def test_login(self, client):
     """ Attempt login of a user"""
     input = {'username' : 'Abhishek',
              'password' : 'foobar'}
     data = jsonify(input)
     response = client.post(url_for('AuthView:post'), data=data)
     current_app.logger('Got response {0}'.format(response))
     assert response.status_code == 200
예제 #17
0
def get_sms_code():
    """
    获取参数 request.data json.loads(json)
    教研参数是否为空
    验证手机格式
    通过uuid取出图片中的验证码
    判断是否过期
    判断两个图片验证是否相等
    生成短信验证码
    调用云通讯发送(手机号,[验证码,有效期],模板id)
    保存到redis
    返回前端
    :return: 
    """
    # json_data = request.data
    # dict_data = json.loads(json_data)
    dict_data = request.json
    mobile = dict_data.get('mobile')
    image_code = dict_data.get('image_code')
    image_code_id = dict_data.get('image_code_id')

    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")

    # 验证手机号格式
    if not re.match(r"1[3456789]\d{9}", mobile):
        #  表示格式错误
        return jsonify(errno=RET.PARAMERR, errmsg="手机号格式错误")

    try:
        redis_store_code = redis_store.get('image_code:%s'%image_code_id)
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg="查找图片验证码失败")

    if not redis_store_code:
        return jsonify(errno=RET.NODATA,errmsg="验证码过期")

    if image_code.lower() != redis_store_code.lower():
        return jsonify(errno=RET.DATAERR,errmsg="验证码输入不正确")

    # 生成验证码
    sms_code = '%06d'%random.randint(0, 999999)
    # 调用云通讯发送
    print(sms_code)
    # ccp = CCP()
    # result = ccp.send_template_sms(mobile, [sms_code, 5], 1)

    # if result == -1:
        # return jsonify(errno=RET.THIRDERR, errmsg="验证码发送失败")

    try:
         redis_store.set('sms_code:%s'%mobile, sms_code, constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="短信保存失败")

    return jsonify(errno=RET.OK,errmsg="发送成功")
예제 #18
0
파일: views.py 프로젝트: malofeng1009/Malo
def register():
    '''
    1.获取参数
    2.校验参数
    3.取到服务器的真实短信验证码内容
    4.校验用户输入的短信验证码内容和真实的短信验证码内容是否一致
    5.如果一致,初始化 User 模型并且赋值属性
    6.将 User 模型添加数据库
    7.返回响应
    :return:
    '''

    # 1.获取参数
    param_dict = request.json
    mobile = param_dict.get('mobile')
    smscode = param_dict.get('smscode')
    password = param_dict.get('password')
    # 2.校验参数
    if not all([mobile, smscode, password]):
        return jsonify(error=RET.PARAMERR, errmsg='参数错误')
    if not re.match('1[35678]\\d{9}', mobile):
        return jsonify(error=RET.PARAMERR, errmsg='手机格式不正确')
    # 3.取到服务器的真实短信验证码内容
    try:
        real_sms_code = redis_store.get('SMS_' + mobile)
    except Exception as e:
        current_app.logger(e)
        return jsonify(error=RET.DBERR, errmsg='数据查询失败')
    if not real_sms_code:
        return jsonify(error=RET.NODATA, errmsg='图片验证码已经过期')
    # 4.校验用户输入的短信验证码内容和真实的短信验证码内容是否一致
    if real_sms_code != smscode:
        return jsonify(error=RET.DATAERR, errmsg='验证码错误')
    # 5.如果一致,初始化User模型并且赋值属性
    user = User()
    user.mobile = mobile
    # 展示没有昵称,用手机号替代
    user.nick_name = mobile
    # 记录用户最后一次登录时间
    user.last_login = datetime.now()
    # 对密码做加密处理
    user.password = password
    # 6.将User模型添加数据库
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(error=RET.DBERR, errmsg='数据保存失败')

    # 往 session 中保存数据表示当前已经登登录
    session['user_id'] = user.id
    session['mobile'] = user.mobile
    session['nick_name'] = user.nick_name
    # 7.返回响应
    return jsonify(error=RET.OK, errmsg='注册成功')
예제 #19
0
 def get_monitor_flag(parameters):
     parameters_dict = eval(parameters)
     current_app.logger.debug(str(parameters_dict))
     conf = dao.get_mysql_monitor_conf(parameters_dict['host_ip'])
     if conf:
         return conf
     else:
         current_app.logger("没有获取到服务器监控配置,需要先配置监控项")
         return None
예제 #20
0
def send_sms_code():
    """
    # 接收前端发送的手机号,图片验证码,uuid
    # 校验三个值是否都存在
    # 校验手机号,正则
    # 检查图片验证码是否正确,与redis中保存的验证码比较正确
    # 定义随机验证码,用于向容联云发送
    # 向容联云发送生成验证码
    # 将验证码保存到redis中
    # 如果发送成功返回给前端提示
    """
    # 传入格式是json,需转换为字典格式
    # return jsonify(errno=RET.OK, errmsg="短信发送成功")
    params_dict = request.json
    # 接收三个数据 mobile,image_code,image_code_id
    mobile = params_dict.get("mobile")
    print(mobile)
    image_code = params_dict.get("image_code")
    print(image_code)
    image_code_id = params_dict.get("image_code_id")
    print(image_code_id)
    # 判断三个值是否都存在
    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 判断手机号书写是否正确
    if not re.match(r"1[35678]\d{9}", mobile):
        return jsonify(errno=RET.DATAERR, errmsg="手机号格式不正确")

    # 从redis中取出真实的图片验证码
    real_image_id = redis_store.get("ImageCodeId:" + image_code_id)
    print(real_image_id)
    # 与用户输入的图片验证码进行比较,不正确则提示
    if real_image_id.upper() != image_code.upper():
        return jsonify(errno=RET.DATAERR, errmsg="验证码输入错误")

    # 定义随机验证码
    sms_code_str = "%06d" % random.randint(0, 999999)
    # 将验证码保存到log日志中
    current_app.logger.debug("短信验证码为:%s" % sms_code_str)

    # # 像容联云发送数据,数据发送失败提示报错误
    # result = CCP().send_template_sms(mobile, [sms_code_str, constants.SMS_CODE_REDIS_EXPIRES], 1)
    # if result != 0:
    #     return jsonify(errno=RET.DATAERR, errmsg="数据发送失败")

    # 将验证码保存到redis
    try:
        redis_store.setex("SMS_" + mobile, constants.SMS_CODE_REDIS_EXPIRES,
                          sms_code_str)
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg="短信验证码保存错误")

    # 向前端发送信息提示短信发送成功
    return jsonify(errno=RET.OK, errmsg="短信发送成功")
예제 #21
0
 def get(self):
     file_path = request.json.get('filename', '')
     # print(file_path)
     file_path = os.path.join(CLIENT_UPDATE_PATH + 'DELIVERY/', file_path)
     if not os.path.exists(file_path):
         # print('文件不存在。。。。。', file_path)
         current_app.logger('客户端更新文件不存在:{}'.format(file_path))
         return jsonify({'message': '文件不存在'}), 400
     else:
         return send_file(file_path)
예제 #22
0
파일: github.py 프로젝트: stevendiaz/idb
 def repo_info(self):
     try:
         self._commits(self._send_commits_request())
         self._issues(self._send_issues_request())
         report = {
             'teammates': self.teammates,
             'total_issues': self.total_issues,
             'total_commits': self.total_commits
         }
         return report
     except Exception:
         current_app.logger('Error processing Github request')
예제 #23
0
def get_house_detail(house_id):
    """获取房屋详情"""
    # 判断用户是否登录,登录则返回user_id,没有则返回-1
    user_id = session.get("user_id", "-1")
    # 校验参数
    if not house_id:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不存在")

    # 尝试从redis中取出缓存
    try:
        ret = redis_store.get("house_info_%s" % house_id)
    except Exception as e:
        current_app.logger.errno(e)
        # 无缓存则设置为None
        ret = None

    # 判断是否有缓存
    if ret:
        current_app.logger.info("hit house info redis")
        return '{"errno":0,"errmsg":"OK","data":{"user_id":%s,"house":%s}}' % (user_id, ret), 200, \
               {"Content-Type": "application/json"}

    # 从数据库中获取数据
    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    # 判断houses是否有数据
    if not house:
        return jsonify(errno=RET.NODATA, errmsg="无数据")
    # 将详细数据转为字典数据
    try:
        house_data = house.to_full_dict()
    except Exception as e:
        current_app.logger.errno(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据出错误")
    # 将详情数据转为json类型
    json_house = json.dumps(house_data)
    # 将数据存入redis
    try:
        redis_store.setex("house_info_%s" % house_id,
                          constants.HOUSE_DETAIL_REDIS_EXPIRE_SECOND,
                          json_house)
    except Exception as e:
        current_app.logger.errno(e)

    # 返回数据,获取房屋详情成功
    return '{"errno":0,"errmsg":"OK","data":{"user_id":%s,"house":%s}}' % (
        user_id, json_house), 200, {
            "Content-Type": "application/json"
        }
예제 #24
0
def login():
    """
      用户登录
      1、获取参数,post请求,json数据,mobile,password
      2、检查参数的完整性
      3、检查手机号的格式
      4、根据手机号查询mysql,确认用户已注册
      5、判断查询结果
      6、判断密码是否正确
      7、保存用户登录时间,当前时间
      8、提交数据到mysql数据库
      9、缓存用户信息,注意:登录可以执行多次,用户有可能修改昵称,也有可能不改。
      session['nick_name'] = user.nick_name
      10、返回结果

      :return:
      """

    # 1、获取参数,post请求,json数据,mobile,password
    mobile = request.json.get('mobile')
    password = request.json.get('password')
    # 2、检查参数的完整性
    if not all([mobile, password]):
        return jsonify(erron=RET.PARAMERR, erromsg='参数信息不完整')
    # 3、检查手机号的格式
    if not re.match(r'1[3456789]\d{9}$', mobile):
        return jsonify(erron=RET.PARAMERR, errmsg='手机号格式错误')
    # 4、根据手机号查询mysql,确认用户已注册
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger(e)
        return jsonify(erron=RET.DBERR, errmsg='查询用户数据失败')
    # 4、根据手机号查询mysql,确认用户已注册
    if user is None or not user.check_password(password):
        return jsonify(errno=RET.DATAERR, errmsg='用户名或密码错误')
    # 保存用户登录时间,当前时间
    user.last_login = datetime.now()
    #提交数据到数据库
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        #保存数据失败进行回滚操作
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存数据失败')
    #session缓存
    session['user_id'] = user.id
    session['nick_name'] = user.nick_name
    session['mobile'] = user.mobile
    return jsonify(errno=RET.OK, errmsg='OK')
예제 #25
0
def news_release_info():
    '''新闻发布'''
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    if request.method == "GET":
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库错误")
        category_list = []
        for category in categories:
            category_list.append(category.to_dict())
        category_list.pop(0)
        data = {
            'user_info': user.to_dict() if user else None,
            'category_list': category_list
        }
        return render_template('news/user_news_release.html', data=data)
    title = request.form.get('title')
    category_id = request.form.get('category_id')
    digest = request.form.get('digest')
    index_image = request.files.get('index_image')
    content = request.form.get('content')

    if not all([title, category_id, digest, index_image, content]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不全')
    try:
        data = index_image.read()
        path = storage(data)
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.IOERR, errmsg='数据读取错误')
    news = News()
    news.title = title
    news.source = '个人'
    news.category_id = category_id
    news.digest = digest
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + path
    news.content = content
    news.user_id = user.id
    news.status = 1  # 0通过/1审核中/-1未用过

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据库错误')
    return jsonify(errno=RET.OK, errmsg='添加成功')
예제 #26
0
def get_uer_profile():
    """获取个人信息"""
    user_id = g.user_id
    # 查询数据库获取个人信息
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg="获取用户信息失败")

    if user is None:
        return jsonify(errno=RET.NODATA, errmsg="无效操作")

    return jsonify(errno=RET.OK, errmsg="OK", data=user.to_dict())
예제 #27
0
def login():
    """用户登录
    参数:手机号、密码 json
    """
    #获取参数
    req_dict = request.get_json()
    mobile = req_dict.get("mobile")
    password = req_dict.get("password")
    #校验参数
    #参数有没有完整的校验
    if not all([mobile,password]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不完整")

    #手机号格式是否正确
    if not re.match(r"1[34578]\d{9}",mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机格式错误")

    #判断错误次数是否超过限制,如果超过限制,则返回
    #redis记录:"access_nums_请求的ip":次数
    user_ip = request.remote_addr #用户的ip地址
    try:
        access_nums = redis_store.get("access_nums_%s" % user_ip)
    except Exception as e:
        current_app.logger.error(e)
    else:
        if access_nums is not None and int(access_nums) >= constants.LOGIN_ERROR_MAX_TIMES:
            return jsonify(errno=RET.REQERR,errmsg="错误次数过多,请稍后重试")
    #从数据库中根据手机号查询用户的数据对象
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取用户信息失败")
    # 用数据库的密码与用户填写的密码进行对比验证
    if user is None or not user.check_password(password):
        # 如果验证失败,记录错误次数,返回信息
        try:
            redis_store.incr("access_nums_%s" % user_ip)
            redis_store.expire("access_nums_%s" % user_ip,constants.LOGIN_ERROR_FORBID_TIME)
        except Exception as e:
            current_app.logger(e)
        return jsonify(errno=RET.DATAERR, errmsg="用户名或密码错误")

    #如果验证相同成功,保存登录状态,在session中
    session["name"] = user.name
    session["mobile"] = user.mobile
    session["user_id"] = user.id

    return jsonify(errno=RET.OK,errmsg="登录成功")
예제 #28
0
def logtest():
    current_app.logger.debug("我是 debug 级别")
    current_app.logger.info("我是 info 级别")
    current_app.logger.warning("我是 warning 级别")
    current_app.logger.error("我是 error 级别")
    current_app.logger.critical("我是 critical 级别")

    try:
        num = 1 / 0
    except ZeroDivisionError as e:
        current_app.logger.error("除数为 0")
    except Exception as e:
        current_app.logger("未知原因报错")

    return '愿世界一切安好,程序永无BUG!!!'
예제 #29
0
def get_house_index():
    """获取主页幻灯片展示的房屋基本信息"""
    # 从缓存中尝试获取数据
    try:
        ret = redis_store.get("home_page_data")
    except Exception as e:
        current_app.logger(e)
        ret = None

    if ret:
        current_app.logger.error("hit house index info redis")
        # 因为redis中保存的是json字符串,所以直接进行字符串拼接返回
        #     响应体                             状态码          响应头
        return "{'errno':0,'errmsg':'OK','data':%s}" % ret, 200, {
            "Content-Type": "application/json"
        }
    else:
        try:
            # 查询数据库,返回房屋订单数目最多的5条数据
            houses = House.query.order_by(House.order_count.desc()).limit(
                constants.HOME_PAGE_MAX_HOUSES)

        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="查询数据失败")

        if not houses:
            return jsonify(errno=RET.NODATA, errmsg="查询无数据")

        houses_list = []
        for house in houses_list:
            # 如果房屋未设置主图片,则跳过
            if not house.index_image_url:
                continue  # 跳出此次判断继续执行下面的代码
            houses_list.append(house.to_basic_dict())

        # 将数据转换为json,并保存到redis缓存
        json_houses = json.dumps(houses_list)
        try:
            redis_store.setex("home_page_data",
                              constants.HOME_PAGE_DATA_REDIS_EXPIRES,
                              json_houses)
        except Exception as e:
            current_app.logger.error(e)
            return "{'errno':0,'errmsg':'OK','data':%s}" % json_houses, 200, {
                "Content-Type": "application/json"
            }
예제 #30
0
def sms_code():
    #     获取手机号
    # 获取验证码
    # 第一次不用存手机号
    # 验证码对比失败,应该是验证码的值取的不对,检查获取的验证码是否正确,检查从server中获取的值是否正确
    json_dict = request.json
    mobile = json_dict.get("mobile")
    image_code_client = json_dict.get("image_code")
    image_code_id = json_dict.get("image_code_id")
    print('id1-----------------------', image_code_id)
    # 从客户端获取的验证码应该和从服务器获取的验证码一致,在前端在获取值的时候,会绑定uuid
    # 校验参数是否存在
    if not all([mobile, image_code, image_code_client]):
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='缺少参数')
# 判断手机格式是否正确
    if not re.match(r'^1[345678][0-9]{9}$', mobile):
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='手机号格式错误')
# 校验手机验证码是否和redis中的匹配,在这之前先判断在服务器中是否存在这个验证码?,(不存在的原因是已经失效了)如果不存在就不用往下判断了
    try:
        image_code_id_server = redis_store.get('ImageCode:' + image_code_id)
        print('id------------------------', image_code_id_server)
    #     这是空的
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=response_code.RET.DBERR, errmsg='查询图片验证码失败')
        # 如果数据库中获取失败,给客户友好提示
    if not image_code_id_server:
        return jsonify(errno=response_code.RET.DBERR, errmsg='查询图片验证码失败')
    if image_code_client.lower() != image_code_id_server.lower():
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='输入验证码有误')
# 如果存在,给手机号发送短信
    sms_code = '%06d' % random.randint(0, 99999)
    result = CCP().send_template_sms(mobile, [sms_code, 5], 1)
    if result != 0:
        # if not result:
        return jsonify(errno=response_code.RET.THIRDERR, errmsg='发送短信验证码失败')
#     反之发送成功,成功后将手机号作为建,将手机验证码存储到redis中
    try:
        redis_store.set("SMS" + mobile, sms_code,
                        constants.SMS_CODE_REDIS_EXPIRES)
#         将手机号以建的方式存储验证码
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=response_code.RET.DBERR, errmsg='保存短信验证码失败')

# 7.响应短信验证码发送的结果
    return jsonify(errno=response_code.RET.OK, errmsg='发送短信验证码成功')
예제 #31
0
def import_taxis(filename='/tmp/taxis.tar.gz'):
    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "X-VERSION": 2
    }

    pathname = mkdtemp()
    tar = tarfile.TarFile.open(filename, 'r:gz')
    tar.extractall(path=pathname)

    users_dict = None
    with open(os.path.join(pathname, 'users.json')) as f:
        users_dict = json.loads(f.read())

    users_apikey = dict([(id_, user_datastore.find_user(email=email).apikey)
        for (id_, email) in users_dict.items()])

    dirs = [d for d in os.listdir(pathname) if os.path.isdir(os.path.join(pathname, d))]
    i = 1
    for d_name in dirs:
        dir_name = os.path.join(pathname, d_name)
        files = [f for f in os.listdir(dir_name)\
                if os.path.isfile(os.path.join(dir_name, f))]
        vehicles = [f for f in files if f.startswith('vehicle')]
        vehicle_id = None
        for vehicle in vehicles:
            user = vehicle.split('_')[2][:-len('.json')]
            headers['X-API-KEY'] = users_apikey[user]
            with open(os.path.join(dir_name, vehicle)) as f:
                r = requests.post(url_for('api.vehicle', _external=True),
                    headers=headers, data=f.read())
                vehicle_id = r.json()['data'][0]['id']
                licence_plate = r.json()['data'][0]['licence_plate']
                if r.status_code != 201:
                    current_app.logger.error(r.content)
                    current_app.logger(d_name)
                    current_app.logger('vehicle: {}'.format(f))
                    return

        with open(os.path.join(pathname, d_name, 'ads.json')) as f:
            ads = json.loads(f.read())
            ads['data'][0]['vehicle_id'] = vehicle_id

            r = requests.post(url_for('api.ads', _external=True),
                    headers=headers, data=json.dumps(ads))
            if r.status_code != 201:
                current_app.logger.error(r.content)
                current_app.logger.error(d_name)
                return

        with open(os.path.join(pathname, d_name, 'driver.json')) as f:
            driver = json.loads(f.read())
            r = requests.post(url_for('api.drivers', _external=True),
                    headers=headers, data=json.dumps(driver))
            if r.status_code != 201:
                current_app.logger.error(r.content)
                current_app.logger.error(d_name)
                return

        r = requests.post(url_for('api.taxi_list', _external=True),
                headers=headers, data=json.dumps(
                    {"data": [
                        {
                            "ads": {
                                "insee": ads['data'][0]['insee'],
                                "numero": ads['data'][0]['numero']
                                },
                            "driver": {
                                "departement": driver['data'][0]['departement']['numero'],
                                "professional_licence": driver['data'][0]['professional_licence']
                                },
                            "vehicle": {
                                "licence_plate": licence_plate
                                },
                            "id": d_name
                        }
                        ]}
                    ))
        if r.status_code != 201:
            current_app.logger.error(r.content)
            current_app.logger.error(d_name)
            return
        current_app.logger.info('Taxi {}/{} added'.format(i, len(dirs)))
        i += 1
예제 #32
0
def authenticate_login(email, password):
    """

    :param email: Users email address
    :type email: string
    :param password: Users password
    :type password: string
    :return: The user object, if the user is authenticated, otherwise None
    :rtype: User object
    """
    # print "USE_LDAP:"+ str(current_app.config['USE_LDAP'])
    if current_app.config['USE_LDAP']:
        # print "USE_LDAP"
        # print("Use LDAP: %s" % current_app.config['USE_LDAP'])
        # # Setup the LDAP Options
        if current_app.config['LDAP_USE_TLS']:
            # Sets up TLS for LDAP connection
            ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT,
                            ldap.OPT_X_TLS_NEVER)
        if current_app.debug:
            # Sets up verbose logging for LDAP debugging
            ldap.set_option(ldap.OPT_DEBUG_LEVEL, 255)

        # Create the LDAP Context
        ctx = ldap.initialize('%s:%s' % (current_app.config['LDAP_SERVER'], current_app.config[
            'LDAP_PORT']))
        if current_app.config['LDAP_USE_TLS']:
            # Provide the certificate for LDAP, if required
            ctx.set_option(ldap.OPT_X_TLS_CACERTFILE, current_app.config['LDAP_CERT_PATH'])
        # Bind to LDAP Server
        try:
            ctx.bind_s(current_app.config['LDAP_SA_BIND_DN'], current_app.config[
                'LDAP_SA_PASSWORD'])
        except ldap.LDAPError as e:
            current_app.logger("Failed to bind to LDAP: %s", e)
            return None

        # check if user exists in LDAP
        user_dn = ctx.search_s(current_app.config['LDAP_BASE_DN'], ldap.SCOPE_SUBTREE,
                               'mail=%s' % email)
        if user_dn and len(user_dn) == 1:
            # Bind as the user with the provided password
            try:
                user_dn, attributes = user_dn[0]
                authenticated = ctx.bind_s(user_dn, password)
                # print "USER IS IN LDAP: " + str(email)
                # print "AUTHENTICATED:"+ str(authenticated)
                return authenticated
            except ldap.INVALID_CREDENTIALS as e:
                # print("User: %s failed to authenticate", email)
                return None
        else:
            user = User.query.filter_by(email=email).first()
            # print("User: %s not found", user)
            return None
        return None
    else:
        user = User.query.filter_by(email=email).first()
        if user and (user.is_staff or user.is_admin()):
            if user.check_password(password):
                return user
            if user.password == password:  # Hash it
                user.set_password(password)
                db.session.add(user)
                db.session.commit()
            return user
        return None