Esempio n. 1
0
def check_pay(request):
    # 创建用于进行支付宝支付的工具对象
    body = loads(request.body)
    order_id = body["order_id"]
    ali_url, alipay = kb_alipay()
    request_time = 0
    while True:
        # 调用alipay工具查询支付结果
        response = alipay.api_alipay_trade_query(order_id)  # response是一个字典

        # 判断支付结果
        code = response.get("code")  # 支付宝接口调用成功或者错误的标志
        trade_status = response.get("trade_status")  # 用户支付的情况

        if code == "10000" and trade_status == "TRADE_SUCCESS":
            # 表示用户支付成功
            # 返回前端json,通知支付成功
            return success({"code": 0, "message": "支付成功"})

        elif code == "40004" or (code == "10000"
                                 and trade_status == "WAIT_BUYER_PAY"):
            # 表示支付宝接口调用暂时失败,(支付宝的支付订单还未生成) 后者 等待用户支付
            # 继续查询
            print(code)
            print(trade_status)
            request_time += 1
            if request_time < 10:
                continue
            else:
                return error({"code": 0, "message": "支付失败"})
        else:
            # 支付失败
            # 返回支付失败的通知
            return success({"code": code, "message": trade_status})
Esempio n. 2
0
def check_charge(request):
    cs = ChargeInfo.objects.filter(status='pending',
                                   create_date__gt=add_minutes(now(), -5))
    if len(cs) > 0:
        return success({'hasCharge': True})
    else:
        return success({'hasCharge': False})
Esempio n. 3
0
def user_humidifier():
    data = request.json
    status = data["status"]

    if (status == 'ON'):
        GPIO.output(17, GPIO.HIGH)
        return success('ON')
    elif (status == 'OFF'):
        GPIO.output(17, GPIO.LOW)
        return success('OFF')

    return invalid_status()
Esempio n. 4
0
def route_boiler():
    data = request.json
    status = data["status"]

    if (status == 'ON'):
        GPIO.output(4, GPIO.HIGH)
        return success('ON')
    elif (status == 'OFF'):
        GPIO.output(4, GPIO.LOW)
        return success('OFF')

    return invalid_status()
Esempio n. 5
0
def export_resend_detail(request):
    body = loads(request.body)
    order_ids = body.get('orderIds', '')
    rows = []

    if order_ids != '':
        order_id_arry = order_ids.split(',')
        consumes = ConsumeInfo.objects.filter(
            order_id__in=order_id_arry).order_by('-update_date')
        for i, c in enumerate(consumes):
            row = [
                i + 1, c.user_id, c.ec_id, c.order_id, c.goods_name,
                c.receive_prov, c.receive_city, c.receive_county,
                c.receive_addr, c.receiver, c.receiver_tel,
                format_datetime(c.create_date, "%Y-%m-%d %H:%M:%S")
            ]
            rows.append(row)

    headers = [
        '序号', '账号', '淘宝订单号', '运单号', '包裹类型', '收件省份', '收件城市', '收件地区', '收件详细地址',
        '收件人姓名', '收件人电话', '创建时间'
    ]

    write_excel(f'/root/kbao/data/excel/{request.user.username}.xlsx', rows,
                headers)

    return success({'excel_url': f'/data/excel/{request.user.username}.xlsx'})
Esempio n. 6
0
def full_text_search(request):
    """
    # 可行方案
    keywords = request.GET.get("search", "")
    response = client.search(index="course", body={
        "query": {
            "multi_match": {
                "query": keywords,
                "fields": ["description"]
            }
        }
    })
    return success(response)
    """
    # 可行方案
    keywords = request.GET.get("search", "")
    response = client.search(index="blog",
                             body={
                                 "query": {
                                     "multi_match": {
                                         "query": keywords,
                                         "fields": ["description"]
                                     }
                                 }
                             })
    return success(response)
def delete_session():
    # 토큰의 uid와 입력된 uid가 일지하는지 검사한다.
    try:
        auth_token = request.headers['Authorization']
        decoded = session_token.decode(auth_token)
        uid = request.args.get('uid')
        if (decoded['uid'] != uid):
            return invalid_param('Invalid User')
        elif decoded['exp'] < int(time.time()):
            return session_exp()
    except KeyError:
        return invalid_session()

    # 세션 레코드를 삭제한다.
    connection = db.get_connection()
    try:
        result = session_model.delete(auth_token, connection)
        connection.commit()
    except IntegrityError as e:
        connection.rollback()
        return db_error.response(e)
    finally:
        connection.close()

    return success('OK')
def create_new_room():
    try:
        auth_token = request.headers['Authorization']
        decoded = session_token.decode(auth_token)
        if decoded == False:
            return invalid_session()
        elif decoded['exp'] < int(time.time()):
            return session_exp()
    except KeyError:
        return invalid_session()
    except jwt.exceptions.DecodeError:
        return invalid_session()

    params = get_room_info_from_request()

    connection = db.get_connection()
    try:
        room_id = room_model.create_room(params, connection)
        room_model.update_ip(room_id, params[1], connection)
        connection.commit()
        room_info = room_model.get_room(room_id, connection)
    except IntegrityError as e:
        connection.rollback()
        return db_error(e)
    finally:
        connection.close()

    return success(room_info)
Esempio n. 9
0
def _update_user(user_id):
    form = UserSchema().validate_or_400(request.get_json())
    user = User.get(user_id)
    user = user.update(form)
    if commit_to_db():
        return success(user.json())
    error(500, {"user": "******"})
Esempio n. 10
0
def add_send_org(request):
    body = loads(request.body)
    try:
        addr = AddressInfo.objects.get(addr_type='send',
                                       name=body.get('sender', ''),
                                       address=body.get('sendAddress', ''),
                                       prov=body.get('sendProv', ''),
                                       city=body.get('sendCity', ''),
                                       county=body.get('sendCounty', ''),
                                       tel=body.get('sendTel', ''),
                                       org_name=body.get('orgName', ''),
                                       postid=body.get('sendPostid', ''))

    except AddressInfo.DoesNotExist:
        AddressInfo.objects.all().update(is_default='0')
        AddressInfo.objects.create(addr_type='send',
                                   name=body.get('sender', ''),
                                   address=body.get('sendAddress', ''),
                                   prov=body.get('sendProv', ''),
                                   city=body.get('sendCity', ''),
                                   county=body.get('sendCounty', ''),
                                   tel=body.get('sendTel', ''),
                                   org_name=body.get('orgName', ''),
                                   postid=body.get('sendPostid', ''))

    return success()
Esempio n. 11
0
def sign_in(request):
    body = loads(request.body)
    userid = body.get('userid', '')
    password = body.get('passWord', '')
    vailate_id = body.get('vid', '')
    vailate_str = body.get('vstr', '')

    try:
        v = ValidateImg.objects.get(id=vailate_id)
        if vailate_str.upper() != v.validate_str:
            return error('03', '验证码错误!')
    except ValidateImg.DoesNotExist:
        return error('02', '验证码无效!请刷新重试!')

    user = authenticate(username=userid, password=password)
    if user is not None:
        login(request, user)
        u = UserInfo.objects.get(user_id=user.username)
        res_data = serialize(u)
        res_data['defaultAddr'] = dict()
        try:
            def_addr = AddressInfo.objects.get(addr_type='send',
                                               is_default='1')
            res_data['defaultAddr'] = serialize(def_addr)
        except AddressInfo.DoesNotExist:
            pass
        return success(res_data)
    else:
        return error('01', '用户名或密码错误!')
Esempio n. 12
0
def order_list(request):
    body = loads(request.body)
    order_status = body.get('orderStatus', '')
    order_id = body.get('orderId', '')
    tid = body.get('tid', '')
    flow_date = body.get('chargeDate')
    bgn_date = None
    end_date = None
    if flow_date[0] != '':
        bgn_date = parse_datetime(flow_date[0])
    if flow_date[1] != '':
        end_date = parse_datetime(flow_date[1])
    page_size = int(body.get('pageSize', 10))
    page = body.get('page', 1)

    consumes = ConsumeInfo.objects.filter(
        user_id=request.user.username).order_by('-update_date')
    if order_status != '':
        consumes = consumes.filter(status=order_status)
    if order_id != '':
        consumes = consumes.filter(order_id=order_id)
    if tid != '':
        consumes = consumes.filter(ec_id=tid)
    if all([bgn_date, end_date]):
        consumes = consumes.filter(create_date__gt=bgn_date,
                                   create_date__lt=end_date)

    res = dict()
    p = Paginator(consumes, page_size)
    res['total'] = p.count
    res['pageSize'] = page_size
    res['pageNum'] = page
    res['data'] = serialize(p.page(page).object_list)

    return success(res)
Esempio n. 13
0
def sign_up(request):
    body = loads(request.body)
    user_id = body.get('userid', '')
    password = body.get('passWord', '')
    tel = body.get('tel', '')
    qq = body.get('qq', '')
    email = body.get('email', '')
    vailate_id = body.get('vid', '')
    vailate_str = body.get('vstr', '')
    proxy_id = body.get('proxy', '')

    try:
        v = ValidateImg.objects.get(id=vailate_id)
        if vailate_str.upper() != v.validate_str:
            return error('03', '验证码错误!')
    except ValidateImg.DoesNotExist:
        return error('02', '验证码无效!请刷新重试!')

    try:
        User.objects.get(username=user_id)
        return error('01', '用户名已存在!')
    except User.DoesNotExist:
        if proxy_id != '':
            try:
                UserInfo.objects.get(user_id=proxy_id, role='proxy')
            except UserInfo.DoesNotExist:
                proxy_id = ''
        User.objects.create_user(user_id, '', password)
        UserInfo.objects.create(user_id=user_id,
                                tel=tel,
                                email=email,
                                reference=proxy_id,
                                qq=qq)
        return success()
Esempio n. 14
0
def charge_list(request):
    body = loads(request.body)
    user_id = body.get('userId')
    flow_date = body.get('chargeDate')
    bgn_date = None
    end_date = None
    if flow_date[0] != '':
        bgn_date = parse_datetime(flow_date[0])
    if flow_date[1] != '':
        end_date = parse_datetime(flow_date[1])
    flow_min_amt = body.get('chargeMinAmt', -1)
    flow_max_amt = body.get('chargeMaxAmt', -1)
    page_size = int(body.get('pageSize', 10))
    page = body.get('page', 1)
    charges = ChargeInfo.objects.filter(
        user_id__contains=user_id).order_by('-create_date')
    if all([bgn_date, end_date]):
        charges = charges.filter(create_date__gt=bgn_date,
                                 create_date__lt=end_date)
    if flow_min_amt != -1:
        charges = charges.filter(amt__gt=flow_min_amt)
    if flow_max_amt != -1:
        charges = charges.filter(amt__lt=flow_max_amt)

    res = dict()
    p = Paginator(charges, page_size)
    res['total'] = p.count
    res['pageSize'] = page_size
    res['pageNum'] = page
    res['data'] = serialize(p.page(page).object_list)
    return success(res)
Esempio n. 15
0
def question_info(request):
    print('api:question_info')
    try:
        mongo_conn = MongoDBBase(config=MONGODB_CONFIG)
        data = QuestionForm(request).validate()
        question_content = QuestionInfoColl.all_sub_questions(conn=mongo_conn,
                                                              uid=data.uid,
                                                              pid=data.pid,
                                                              tid=data.tid,
                                                              qid=data.qid)

        question = QuestionColl.one_question(conn=mongo_conn,
                                             uid=data.uid,
                                             pid=data.pid,
                                             tid=data.tid,
                                             qid=data.qid)
        url, info = question['url'], question['info']
    except (CommonError, ValidationError) as e:
        return fail(sc=e.sc, msg=e.msg)
    return success(data=dict(uid=data.uid,
                             pid=data.pid,
                             tid=data.tid,
                             qid=data.qid,
                             url=url,
                             info=info,
                             content=question_content))
Esempio n. 16
0
def report_measurement(room_id):
    # 토큰의 uid와 입력된 uid가 일치하는지 검사한다.
    try:
        access_token = request.headers['Authorization']
    except KeyError:
        return invalid_session()

    connection = db.get_connection()
    try:
        room_info = room_model.get_room(room_id, connection)

        if access_key.valid(access_token, room_info['ip'],
                            room_info['id']) == False:
            return invalid_session()

        data = request.json
        datetime = data["datetime"]
        temperature = data["temperature"]
        humidity = data["humidity"]

        measurement_model.insert((room_id, datetime, temperature, humidity),
                                 connection)
        connection.commit()
    except IntegrityError as e:
        connection.rollback()
        return db_error(e)
    except KeyError:
        connection.rollback()
        return invalid_param()
    finally:
        connection.close()

    return success('OK')
Esempio n. 17
0
def create_session():
    connection = db.get_connection()

    data = request.json
    email = data["email"]
    passwd = data["password"]

    # 사용자 패스워드 조회
    try:
        result = user_model.get_password(email, connection)

        if (result):
            if password.valid(result[1], passwd):
                token = session_token.encode(result[0])
                session_model.insert(token, connection)
                connection.commit()
                return success({'uid': result[0], 'token': token})
            else:
                return invalid_password()
    except IntegrityError as e:
        connection.rollback()
        return db_error.response(e)
    finally:
        connection.close()

    return no_user()
Esempio n. 18
0
def proxy_list(request):
    body = loads(request.body)
    proxy_id = body.get('proxyId', '')
    users = UserInfo.objects.all().order_by('-create_date')
    proxy_bal_sum = dict()
    proxy_data = []
    for user in users:
        if user.reference != '':
            if proxy_bal_sum.get(user.reference) is None:
                proxy_bal_sum[user.reference] = 0
            proxy_bal_sum[user.reference] += user.bal

    for user in users:
        if user.role == 'proxy':
            if proxy_id != '' and proxy_id != user.user_id:
                continue
            proxy_data.append({
                'user_id': user.user_id,
                'bal': user.bal,
                'price': user.price,
                'qq': user.qq,
                'email': user.email,
                'create_date': user.create_date,
                'bal_summ': proxy_bal_sum.get(user.user_id, 0),
            })
    return success(proxy_data)
Esempio n. 19
0
def update_session():
    # 토큰의 uid와 입력된 uid가 일지하는지 검사한다.
    try:
        auth_token = request.headers['Authorization']
        decoded = session_token.decode(auth_token)
        data = request.json
        uid = data['uid']
        if (decoded['uid'] != uid):
            return invalid_param('Invalid User')
        elif decoded['exp'] < int(time.time()):
            return session_exp()
    except KeyError:
        return invalid_session()
    except jwt.exceptions.DecodeError:
        return invalid_session()

    # 새로운 토근을 발급한다
    connection = db.get_connection()
    try:
        new_token = session_token.encode(uid)
        session_model.update(auth_token, new_token, connection)
        connection.commit()
    except IntegrityError as e:
        connection.rollback()
        return db_error.response(e)
    finally:
        connection.close()

    return success({'uid': uid, 'token': new_token})
Esempio n. 20
0
def add_worker(request):
    print('api:add_worker')
    try:
        data = WorkerAddForm(request).validate()
    except (ValidationError) as e:
        return fail(sc=e.sc, msg=e.msg)
    return success(dict(mobile=data.mobile, uid=data.worker_id))
Esempio n. 21
0
def tmp_pull_one_question(request):
    print('api:tmp_pull_one_question')
    try:
        mongo_conn = MongoDBBase(config=MONGODB_CONFIG)
        data = TmpQuestionForm(request).validate()
        qid = QuestionInfoColl.choose_one_subquestion_by_type(conn=mongo_conn,
                                                              uid=data.uid,
                                                              pid=data.pid,
                                                              tid=data.tid,
                                                              type=data.type)

        question = QuestionColl.one_question(conn=mongo_conn,
                                             uid=data.uid,
                                             pid=data.pid,
                                             tid=data.tid,
                                             qid=qid)
        url, info = question['url'], question['info']
        content = [dict(id="0", info={}, content={"nodes": [], "lines": []})]

    except (CommonError, ValidationError) as e:
        return fail(sc=e.sc, msg=e.msg)
    return success(data=dict(uid=data.uid,
                             pid=data.pid,
                             tid=data.tid,
                             qid=qid,
                             url=url,
                             info=info,
                             content=content))
Esempio n. 22
0
def change_password(request):
    body = loads(request.body)
    user = User.objects.get(username=request.user.username)
    user.set_password(body.get('newPassWord'))
    user.save()
    logout(request)
    return success()
Esempio n. 23
0
def charge(request):
    body = loads(request.body)
    ChargeInfo.objects.create(user_id=request.user.username,
                              charge_type=body.get('chartType'),
                              order_id=body.get('orderId'),
                              amt=body.get('amt'))
    return success()
Esempio n. 24
0
def ali_callback(request):
    print("支付宝扫码支付")
    method_param = getattr(request, request.method)
    print("支付金额", method_param['buyer_pay_amount'])
    print("支付状态", method_param['trade_status'])
    print("订单号", method_param['out_trade_no'])

    return success()
Esempio n. 25
0
def update_notice(request):
    body = loads(request.body)
    n = PublicNotice.objects.get(id=body.get('id'))
    n.content = body.get('content', '')
    if body.get('speakTo', '') != '':
        n.speak_to = body.get('speakTo')
    n.save()
    return success()
Esempio n. 26
0
def update_kf(request):
    body = loads(request.body)
    for kf_id in body:
        kf = QQServiceInfo.objects.get(id=kf_id)
        kf.name = body[kf_id].get('name', '')
        kf.qq = body[kf_id].get('qq', '')
        kf.valid = body[kf_id].get('valid', '')
        kf.save()
    return success()
Esempio n. 27
0
def excel_save(request):
    file = request.FILES['file']
    xls = ExcelList.objects.create(excel=file)
    xls_data = read_excel(xls.excel.path, skiprow=1)
    for x in xls_data:
        if x[0] is None or x[0] == '' or x[1] is None or x[1] == '':
            continue
        ExpressOrderInfo.objects.create(express_type=x[0], order_id=x[1])
    return success(xls_data)
Esempio n. 28
0
def update_task(request):
    print('api:update_task')
    try:
        mongo_conn = MongoDBBase(config=MONGODB_CONFIG)
        data = TaskUpdateForm(request).validate()
        TaskColl.update_task(conn=mongo_conn, uid=data.uid, info=data.info)
    except (CommonError, ValidationError) as e:
        return fail(sc=e.sc, msg=e.msg)
    return success(data=dict())
Esempio n. 29
0
def delete_label(request):
    print('api:delete_label')
    try:
        mongo_conn = MongoDBBase(config=MONGODB_CONFIG)
        data = LabelDeleteForm(request).validate()
        LabelColl.delete_label(conn=mongo_conn, pid=data.pid, lid=data.lid)
    except (CommonError, ValidationError) as e:
        return fail(sc=e.sc, msg=e.msg)
    return success()
Esempio n. 30
0
def reset_password(request):
    body = loads(request.body)
    user = User.objects.get(username=body.get('userId'))
    characters = string.digits + string.ascii_uppercase

    random_str = ''.join([random.choice(characters) for j in range(8)])
    user.set_password(random_str)
    user.save()
    return success({'new_password': random_str})