Ejemplo n.º 1
0
def get_code():
    data = request.get_json()
    if not data:
        return bad_request('ERROR DATA AT CODE')

    email = data.get('email')
    if not email:
        return bad_request('Email is required')

    if not re.match(
            r'^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$',
            email):
        return bad_request('107 Email format error')

    db = get_db()
    if db.execute('SELECT idUser FROM User WHERE email = ?',
                  (email, )).fetchone() is not None:
        return bad_request('108 Email {} is already registered.'.format(email))
    # 邮箱真实性验证,有点慢,不知道是否真的需要

    code = random.randint(100000, 999999)
    # 使用sqlite数据库的情况:
    db.execute(
        'REPLACE INTO Verification VALUES (?,?,?)',
        (email, code, datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
    db.commit()
    # 使用redis情况的代码如下:
    # try:
    #     redis_db.set('Email:'+email, code, 1800)    # 有效期半小时
    # except Exception as e:
    #     current_app.logger.debug(e)
    #     return bad_request('Redis storing error '+str(e))

    send_verification_code(email, code)
    return created('Generate and send token successfully')
Ejemplo n.º 2
0
def update_notification():
    """更新通知已读状态
    """
    data = request.get_json()  # {notification: [{“n_id”:123,”has_read”:True}, ...]}
    if not data:
        return bad_request('ERROR DATA AT GET NOTIFICATION')

    type_n = data.get("type") # 0:update 1:delete

    if type_n == 0:
        notifications = data.get("notification")

        db = get_db()

        for notification in notifications:
            db.execute(
                'UPDATE Notification SET has_read = ? WHERE n_id = ?',
                (notification["has_read"], notification["n_id"])
            )
            db.commit()

        return ok('Update the state of notifications successfully')
    elif type_n == 1:
        notification = data.get("notification")
        db = get_db()
        for n_id in notification:
            db.execute(
                'UPDATE Notification SET has_deleted = ? WHERE n_id = ?',
                (1, n_id)
            )
            db.commit()

        return ok('Delete notification successfully')

    return bad_request('ERROR WRONG TYPE_N')
Ejemplo n.º 3
0
def get_avatar_url():
    db = get_db()
    avatar = db.execute('SELECT avatar FROM User WHERE idUser = ?',
                        (g.user['idUser'], )).fetchone()
    if avatar['avatar']:
        return ok('Get user avatar successfully',
                  data={'avatar': avatar['avatar']})
    else:
        return bad_request('110 User avatar is not available')
Ejemplo n.º 4
0
def change_password():
    data = request.get_json()
    if not data:
        return bad_request('ERROR DATA AT CHANGING PASSWORD')

    old_password = data.get('old_password')
    new_password = data.get('new_password')
    if not old_password:
        return bad_request('Old password is required')
    elif not new_password:
        return bad_request('New password is required')

    if not check_password_hash(g.user['password'], old_password):
        return bad_request('112 Old password wrong')

    db = get_db()
    db.execute('UPDATE User SET password = ? WHERE idUser = ?',
               (generate_password_hash(new_password), g.user['idUser']))
    db.commit()
    return ok('Change password successfully')
Ejemplo n.º 5
0
def login():
    data = request.get_json()
    if not data:
        return bad_request('ERROR DATA AT LOGIN')

    username_or_email = data.get('username_or_email')
    password = data.get('password')
    db = get_db()

    if not username_or_email:
        return bad_request('Username or email is required')
    elif not password:
        return bad_request('Password is required')

    user = db.execute('SELECT * FROM User WHERE username = ?',
                      (username_or_email, )).fetchone()
    if user is None:
        user = db.execute('SELECT * FROM User WHERE email = ?',
                          (username_or_email, )).fetchone()

    if user is None:
        return bad_request('105 Incorrect username or email')
    elif not check_password_hash(user['password'], password):
        return bad_request('106 Incorrect password')

    # 新增通知功能,需要在登录时检查该用户有没有已发布的过期任务,如果有则在通知表生成新的表项????????????????待完成
    # 然后查通知表获取所有该用户的未读表项的数目,然后再response.body返回

    # 登录成功,服务器生成token并返回给用户端
    s = Serializer(current_app.config['SECRET_KEY'], expires_in=3600)
    return created('Login successfully',
                   data={
                       'token':
                       s.dumps({
                           'idUser': user['idUser'],
                           'email': user['email'],
                           'randnum': random.randint(0, 1000000)
                       }).decode('utf-8'),
                       'notification_num':
                       get_unread_num(user['idUser'])
                   })
Ejemplo n.º 6
0
def change_avatar():
    # 先得到文件
    file = request.files['image']
    print(file)
    print(file.name)

    if file and allowed_file(file.filename):
        filename = file.filename
        extention = filename.rsplit('.', 1)[1]

        file.save(
            os.path.join(current_app.config['UPLOAD_FOLDER'],
                         str(g.user['idUser']) + '.' + extention))
        avatar = os.path.join(current_app.config['BASE_STATIC_URL'],
                              str(g.user['idUser']) + '.' + extention)
        db = get_db()
        db.execute('UPDATE User SET avatar = ? WHERE idUser = ?',
                   (avatar, g.user['idUser']))
        db.commit()
        return ok('change avatar successfully', data={'avatar': avatar})
    elif file is None:
        bad_request('111 file is None')
    else:
        return bad_request('111 file is supposed to be jpg or png')
Ejemplo n.º 7
0
def update_info():
    data = request.get_json()
    if not data:
        return bad_request('ERROR DATA AT UPDATE')

    username = data.get('username')
    realname = data.get('realname', '')
    id_card_num = data.get('id_card_num', '')
    university = data.get('university', '')
    school = data.get('school', '')
    grade = data.get('grade', '')
    gender = data.get('gender', -1)
    phone = data.get('phone', '')
    qq = data.get('qq', '')
    wechat = data.get('wechat', '')

    db = get_db()

    if not username:
        return bad_request('Username is required')
    elif db.execute(
            'SELECT idUser FROM User WHERE username = ? AND username != ?', (
                username,
                g.user['username'],
            )).fetchone() is not None:
        return bad_request(
            '109 User {} is already registered.'.format(username))

    db.execute(
        'UPDATE User SET username = ?, realname = ?, id_card_num = ?, university = ?, school = ?, grade = ?, gender = ?, phone = ?, qq = ?, wechat = ?'
        ' WHERE idUser = ?',
        (username, realname, id_card_num, university, school, grade, gender,
         phone, qq, wechat, g.user['idUser']))
    db.commit()

    return ok('Update user info successfully')
Ejemplo n.º 8
0
def register():
    # 这里返回code 400 表示bad request,请求失败
    data = request.get_json()
    if not data:
        return bad_request('ERROR DATA AT REGISTERING')

    username = data.get('username')
    password = data.get('password')
    email = data.get('email')
    sid = data.get('sid')
    code = data.get('code')

    db = get_db()

    if not username:
        return bad_request('Username is required')
    elif not password:
        return bad_request('Password is required')
    elif not email:
        return bad_request('Email is required')
    elif not sid:
        return bad_request('Sid is required')
    elif not code:
        return bad_request('Verification code is required')
    elif db.execute('SELECT idUser FROM User WHERE username = ?',
                    (username, )).fetchone() is not None:
        return bad_request(
            '100 User {} is already registered.'.format(username))
    elif db.execute('SELECT idUser FROM User WHERE email = ?',
                    (email, )).fetchone() is not None:
        return bad_request('101 Email {} is already registered.'.format(email))
    elif db.execute('SELECT idUser FROM User WHERE sid = ?',
                    (sid, )).fetchone() is not None:
        return bad_request('102 Sid {} is already registered.'.format(sid))
    # 检查验证码,使用redis时是这样的
    # elif redis_db.get('Email:'+email).decode('utf-8') != str(code):
    #     return bad_request('Verification code is not correct')
    # 检查验证码,使用sqlite数据库是这样的
    else:
        code_info = db.execute(
            'SELECT code, send_time FROM Verification WHERE email = ?',
            (email, )).fetchone()
        if code_info['code'] != str(code):
            return bad_request('103 Verification code is not correct')
        elif abs(
                datetime.datetime.strptime(code_info['send_time'],
                                           '%Y-%m-%d %H:%M:%S') -
                datetime.datetime.now()).seconds > 1800:
            return bad_request('104 Verification code is out of time')

    db.execute(
        'INSERT INTO User (username, password, email, sid) VALUES (?, ?, ?, ?)',
        (username, generate_password_hash(password), email, sid))
    db.commit()

    user_id = db.execute('select last_insert_rowid() from User').fetchone()
    # notification
    create_notification_register(user_id[0])

    return created('Register successfully')
Ejemplo n.º 9
0
def create_order():
    data = request.get_json()
    # 得到json Data
    if not data:
        return bad_request('ERROR PARAM AT CREATING ORDER')
    # 得到任务ID
    mission_id = data.get('mission_id')
    # modified by ousx
    qq = data.get('qq')
    wechat = data.get('wechat')
    phone = data.get('phone')
    other_way = data.get('other_way')
    # end modified

    db = get_db()
    mission = db.execute('SELECT * FROM MissionInfo WHERE idMissionInfo = ?',
                         (mission_id, )).fetchone()
    # id不存在

    if (mission is None):
        return bad_request('mission_id is invalid')

    if (mission['publisher_id'] == g.user['idUser']):
        return bad_request('305 Can not receive mission created by your self')

    if int(mission['type']) == 1 and (not qq) and (not wechat) and (
            not phone) and (not other_way):
        return bad_request('Missing contact info')

    # 已经结束
    if (mission['state'] != 0):
        return bad_request('301 Mission is closed')

    order = db.execute(
        'SELECT * FROM MissionOrder WHERE order_state != 2 AND mission_id = ? AND receiver_id = ?',
        (
            mission_id,
            g.user['idUser'],
        )).fetchone()

    if order is not None:
        return bad_request('304 you have received this mission')

    # 达最大接单数
    rcv_num = mission['rcv_num']
    max_num = mission['max_num']
    deadline = mission['deadline']
    # 达最大接收量

    if (rcv_num >= max_num):
        db.execute('UPDATE MissionInfo SET state = ? WHERE idMissionInfo = ?',
                   (1, mission_id))
        db.commit()
        return bad_request('302 mission reached its max rcv num')
    # 时间过期

    # if(datetime.datetime.now() > datetime.datetime.strptime(deadline, '%Y-%m-%d %H:%M:%S')):
    #     db.execute(
    #     'UPDATE MissionInfo SET state = ? WHERE idMissionInfo = ?',
    #         (1,mission_id)
    #     )
    #     db.commit()
    #     return bad_request('mission reached its dealine')

    # 任务正常关闭
    state = 1 if rcv_num + 1 == max_num else 0

    db.execute(
        'UPDATE MissionInfo SET state = ? , rcv_num = ? WHERE idMissionInfo = ?',
        (state, rcv_num + 1, mission_id))

    # 添加订单
    db.execute(
        'INSERT INTO MissionOrder (mission_id, receiver_id, receive_time, qq, wechat, phone, other_way) VALUES (?, ?, ?, ?, ?, ?, ?)',
        (mission_id, g.user['idUser'],
         datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), qq, wechat,
         phone, other_way))

    # 得到订单id
    order_id = db.execute(
        'select last_insert_rowid() from MissionOrder').fetchone()
    db.commit()

    obj = {'order_id': order_id[0]}

    # notification
    if mission['type'] != 0:  # 对于非问卷类任务
        create_notification_type_3(mission['idMissionInfo'])

    return created('Create order successfully', data=obj)
Ejemplo n.º 10
0
def confirm_order():
    data = request.get_json()
    if not data:
        return bad_request('ERROR DATA AT CREATE MISSION')

    db = get_db()

    order_id = data.get('order_id')
    mission_id = data.get('mission_id')
    # 快递发布者通过mission_id确认
    if mission_id and order_id is None:
        order_info = db.execute(
            'SELECT mission_id, receiver_id, order_state, idMissionOrder FROM MissionOrder WHERE order_state != 2 AND mission_id = ?',
            (mission_id, )).fetchone()
    # 问卷领取者通过order_id确认
    elif order_id and mission_id is None:
        order_info = db.execute(
            'SELECT mission_id, receiver_id, order_state, idMissionOrder FROM MissionOrder WHERE order_state != 2 AND idMissionOrder = ?',
            (order_id, )).fetchone()
    else:
        return bad_request('you should pass either mission_id or order_id')
    # if order_id is not None
    # # try:
    # #     order_id = int(order_id)
    # # except Exception:
    # #     return bad_request('Parse order id error')
    # order_info = db.execute(
    #     'SELECT mission_id, receiver_id, order_state FROM MissionOrder WHERE idMissionOrder = ?', (order_id,)
    # ).fetchone()
    if not order_info:
        return bad_request('No such mission')

    mission_info = db.execute(
        'SELECT publisher_id, type, bounty, max_num FROM MissionInfo WHERE idMissionInfo = ?',
        (order_info['mission_id'], )).fetchone()

    # 确认过的/过期的 订单不能再确认,防止再次生成答案表
    if order_info['order_state'] != 0:
        return bad_request('The order has been confirmed')

    # 分成两类,问卷由接收人确认即可,其他任务由发布人确认
    if mission_info['type'] == 0:
        if order_info['receiver_id'] != g.user['idUser']:
            return forbidden('You can not submit for other receivers')
        answers = data.get('answers')
        if type(answers) != list:
            answers = json.loads(answers)
        problem_ids = db.execute(
            'SELECT idProblem FROM Problem WHERE mission_id = ?',
            (order_info['mission_id'], )).fetchall()
        try:
            for i in range(0, len(answers)):
                db.execute(
                    'INSERT INTO Answer (order_id, problem_id, result) VALUES (?, ?, ?)',
                    (order_id, problem_ids[i]['idProblem'],
                     json.dumps(answers[i])))
            db.commit()
        except Exception:
            return bad_request('Parse answers error')
    elif mission_info['type'] == 1:
        if mission_info['publisher_id'] != g.user['idUser']:
            return forbidden('You can not submit for other publishers')

    # 为接单人发钱
    get_by_confirm(
        mission_info['bounty'] / mission_info['max_num'], g.user['idUser']
        if mission_info['type'] == 0 else order_info['receiver_id'])

    # 更新其它表
    db.execute(
        'UPDATE MissionOrder SET publisher_confirm = ?, receiver_confirm = ?, order_state = ?, finish_time = ? WHERE idMissionOrder = ?',
        (
            1,
            1,
            1,
            datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            order_info['idMissionOrder'],
        ))
    db.execute(
        'UPDATE User SET mission_fin_num = mission_fin_num + 1 WHERE idUser = ?',
        (order_info['receiver_id'], ))
    db.execute(
        'UPDATE MissionInfo SET fin_num = fin_num + 1 WHERE idMissionInfo = ?',
        (order_info['mission_id'], ))
    db.commit()
    db.execute(
        'UPDATE MissionInfo SET state = 2, finish_time = datetime(CURRENT_TIMESTAMP,"localtime") WHERE idMissionInfo = ? AND fin_num==max_num',
        (order_info['mission_id'], ))
    db.commit()

    # notification
    if mission_info['type'] == 0:
        create_notification_type_1(order_info['mission_id'])
    elif mission_info['type'] == 1:
        create_notification_type_4(order_info['mission_id'])

    return ok('Confirm order successfully')
Ejemplo n.º 11
0
def cancel_mission():
    data = request.get_json()
    if not data:
        return bad_request('ERROR DATA AT CANCEL MISSION')

    db = get_db()
    mission_id = data.get('mission_id')
    if (mission_id is None):
        return bad_request('Mission_id is required')
    mission_info = db.execute(
        'SELECT * FROM MissionInfo WHERE idMissionInfo = ?',
        (mission_id, )).fetchone()
    if (mission_info is None):
        return bad_request('Mission_id is invalid')

    rcv_num = mission_info['rcv_num']
    max_num = mission_info['max_num']
    # 问卷
    # 发布者可以取消
    if (mission_info['type'] == 0):
        if (mission_info['publisher_id'] == g.user['idUser']):
            db.execute(
                'UPDATE MissionInfo SET state = ? WHERE idMissionInfo = ?',
                (3, mission_id))
            db.commit()
            # 订单取消,发布人获得退款
            refund_by_cancel(mission_info['bounty'] / mission_info['max_num'],
                             mission_info['max_num'] - mission_info['rcv_num'])
            return ok('cancel successfully')
        else:
            # 这段代码有问题,所幸永远不会使用,不然必出错,因为接单人是一个list,而不是fetchone能完成的
            order_info = db.execute(
                'SELECT * FROM MissionOrder WHERE mission_id = ?',
                (mission_id, )).fetchone()
            if order_info['receiver_id'] == g.user['idUser']:
                # 如果问卷原本是满人了,就重新开放
                if rcv_num == max_num:
                    db.execute(
                        'UPDATE MissionInfo SET state = ? WHERE idMissionInfo = ?',
                        (0, mission_id))
                # 修改接单人数
                db.execute(
                    'UPDATE MissionInfo SET rcv_num = ? WHERE idMissionInfo = ?',
                    (rcv_num - 1, mission_id))
                # 订单取消
                db.execute(
                    'UPDATE MissionOrder SET order_state = ? WHERE mission_id = ?',
                    (2, mission_id))
                db.commit()
                return ok('cancel successfully')
            else:
                return error_response(403, 'The operation is forbidden')
    # 取快递
    # 没人接,发布者可以取消
    # 领取者主动放弃
    elif (mission_info['type'] == 1):
        if (mission_info['publisher_id'] == g.user['idUser']):
            if rcv_num != 0:
                return error_response(
                    400, 'Should not cancel a mission already received')
            else:
                db.execute(
                    'UPDATE MissionInfo SET state = ? WHERE idMissionInfo = ?',
                    (3, mission_id))
                db.commit()
                # 订单取消,发布人获得退款
                refund_by_cancel(
                    mission_info['bounty'] / mission_info['max_num'],
                    mission_info['max_num'] - mission_info['rcv_num'])
                return ok('cancel successfully')
        else:
            order_info = db.execute(
                'SELECT * FROM MissionOrder WHERE order_state == 0 AND mission_id = ?',
                (mission_id, )).fetchone()
            if order_info['receiver_id'] == g.user['idUser']:
                db.execute(
                    'UPDATE MissionInfo SET rcv_num = ?, state = ? WHERE idMissionInfo = ?',
                    (rcv_num - 1, 0, mission_id))
                # 订单取消
                db.execute(
                    'UPDATE MissionOrder SET order_state = ? WHERE mission_id = ?',
                    (2, mission_id))
                db.commit()

                # notification
                create_notification_type_8(
                    mission_id=mission_info['idMissionInfo'],
                    receiver_id=order_info['receiver_id'],
                    cancel_time=datetime.datetime.now())

                return ok('cancel successfully')
            else:
                return error_response(403, 'The operation is forbidden')

    else:
        return error_response(500, 'Server Internal error')
Ejemplo n.º 12
0
def create_mission():
    data = request.get_json()
    if not data:
        return bad_request('ERROR DATA AT CREATE MISSION')

    mission_type = data.get('type')
    deadline = data.get('deadline',
                        datetime.datetime.now() + datetime.timedelta(days=3))
    title = data.get('title')
    description = data.get('description')
    qq = data.get('qq')
    wechat = data.get('wechat')
    phone = data.get('phone')
    other_way = data.get('other_way')
    bounty = data.get('bounty')
    max_num = data.get('max_num', 1)
    problems = data.get('problems')

    # 检查传参,bounty等于0也会报错Missing some necessary parameter
    if (not mission_type and mission_type != 0) or (not title) or (
            not description) or (not bounty):
        return bad_request('Missing some necessary parameter')
    elif int(mission_type) == 1 and (not qq) and (not wechat) and (
            not phone) and (not other_way):
        return bad_request('Missing contact info')
    elif int(bounty) <= 0:  # 实际使用时改成<=0
        return bad_request('bounty should bigger than 0')
    elif not re.match(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}', deadline):
        return bad_request('Deadline format error')
    elif datetime.datetime.now() > datetime.datetime.strptime(
            deadline, '%Y-%m-%d %H:%M:%S'):
        return bad_request('Deadline should be in future')

    try:
        mission_type = int(mission_type)
        bounty = float(bounty)
        max_num = int(max_num)
    except Exception:
        return bad_request('Parse parameter error')
    deadline = datetime.datetime.strptime(deadline, '%Y-%m-%d %H:%M:%S')

    # 插入任务,并获取新插入元组的id
    db = get_db()
    db.execute(
        'INSERT INTO MissionInfo (publisher_id, type, deadline, title, description, qq, wechat, phone, other_way, bounty, max_num) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
        (g.user['idUser'], mission_type, deadline, title, description, qq,
         wechat, phone, other_way, bounty, max_num))
    db.commit()
    # 这里可以通过type(fetchone())来查看列值;通过fetchone().keys()查看列名
    mission_id = db.execute(
        'SELECT last_insert_rowid() FROM MissionInfo').fetchone()[0]

    # 该用户发布任务数量+1
    db.execute(
        'UPDATE User SET mission_pub_num=mission_pub_num+1 WHERE idUser = ?',
        (g.user['idUser'], ))

    # 创建任务之前检查金额,金额足够才能创建并扣钱
    if db.execute('SELECT idUser FROM User WHERE idUser = ? AND balance >= ?',
                  (g.user['idUser'], bounty)).fetchone():
        pay_for_create(bounty)
    else:
        return bad_request('Money not enough')

    # 对于问卷任务需要处理问题信息
    if mission_type == 0:
        if not problems:
            return bad_request('Questionare should have problems')
        if type(problems) != list:
            problems = json.loads(problems)
        # 建议debug的时候注释掉这些try,便于看到错误
        try:
            for problem in problems:
                db.execute(
                    'INSERT INTO Problem (mission_id, type, problem_stem, problem_detail) VALUES (?, ?, ?, ?)',
                    (mission_id, int(problem['type']), problem['question'],
                     json.dumps(problem.get('choices', ''))))
        except Exception:
            return bad_request('Parse problems error')

    db.commit()
    return created('Create mission successfully',
                   data={'mission_id': mission_id})
Ejemplo n.º 13
0
def get_mission():
    limit = request.args.get('limit')
    mission_type = request.args.get('type')
    return_problems = request.args.get('return_problems')
    return_statistics = request.args.get('return_statistics')

    bounty = request.args.get('bounty')
    create_time = request.args.get('create_time')
    if not bounty:
        bounty = 0.0
    if not create_time:
        create_time = '3000-01-01 00:00:00'

    personal = request.args.get('personal')
    mission_id = request.args.get('mission_id')

    db = get_db()
    mission_array = []
    col_name = [
        name_list[1] for name_list in db.execute(
            'PRAGMA table_info(MissionInfo)').fetchall()
    ]
    col_name.remove('phone')
    col_name.remove('qq')
    col_name.remove('wechat')
    col_name.remove('other_way')

    # 若missionid不为空,说明是通过missionid查询特定订单信息,不需要提供任何其他信息
    if mission_id or mission_id == 0:
        try:
            mission_id = int(mission_id)
        except Exception:
            return bad_request('Parse mission id error')

        mission_info = db.execute(
            'SELECT * FROM MissionInfo WHERE idMissionInfo = ?',
            (mission_id, )).fetchone()
        if not mission_info:
            return bad_request('No such mission')

        if mission_info['type'] == 1 and mission_info[
                'rcv_num'] == 1 and g.user['idUser'] == db.execute(
                    'SELECT receiver_id FROM MissionOrder WHERE order_state != 2 AND mission_id = ?',
                    (mission_id, )).fetchone()['receiver_id']:
            col_name.append('phone')
            col_name.append('qq')
            col_name.append('wechat')
            col_name.append('other_way')

        mission_json = {}
        for item in col_name:
            mission_json[item] = mission_info[item]
        mission_array.append(mission_json)
    elif personal or personal == 0:
        try:
            create_time = datetime.datetime.strptime(create_time,
                                                     '%Y-%m-%d %H:%M:%S')
            bounty = float(bounty)
            personal = int(personal)
        except Exception:
            return bad_request('Parse create_time, bounty or personal error')
        # personal为0时表示广场查询,为1时表示私人查询,广场查询只返回state=0的任务
        if personal == 0:
            mission_info = db.execute(
                'SELECT * FROM MissionInfo WHERE bounty > ? AND create_time < ? AND state == 0',
                (bounty, create_time)).fetchall()
        elif personal == 1:
            mission_info = db.execute(
                'SELECT * FROM MissionInfo WHERE publisher_id = ? AND bounty > ? AND create_time < ?',
                (g.user['idUser'], bounty, create_time)).fetchall()
        for row in mission_info:
            mission_json = {}
            for item in col_name:
                mission_json[item] = row[item]
            mission_json['href'] = '#'
            mission_array.append(mission_json)
    else:

        return bad_request('Personal or mission_id are required')

    # 根据mission_type筛选
    if mission_type or mission_type == 0:
        try:
            mission_type = int(mission_type)
        except Exception:
            return bad_request('Parse mission type error')
        mission_temp = []
        for item in mission_array:
            if item['type'] == mission_type:
                mission_temp.append(item)
        mission_array = mission_temp

    # if len(mission_array) == 0:
    #     return bad_request('No search result for the param')

    # 使用问题表完善missioninfo信息
    for item in mission_array:
        item['problems'] = ''
        if item['type'] == 0 and return_problems and int(return_problems):
            problem_info = db.execute(
                'SELECT * FROM Problem WHERE mission_id = ?',
                (item['idMissionInfo'], )).fetchall()
            problems = []
            for row in problem_info:
                problem_json = {}
                problem_json['type'] = row['type']
                problem_json['question'] = row['problem_stem']
                problem_json['choices'] = json.loads(row['problem_detail'])
                problems.append(problem_json)
            item['problems'] = problems
            # 如果问卷任务还需要返回答案统计信息
            if item['publisher_id'] != g.user['idUser'] or (
                    not return_statistics) or (not int(return_statistics)):
                continue
            for num in range(0, len(problems)):
                item['problems'][num]['answer'] = statistics_ana(
                    problem_info[num]['type'],
                    problem_info[num]['problem_detail'],
                    problem_info[num]['idProblem'])

    # 使用订单表完善missioninfo信息,如果是其他任务需要先检查任务是否被接受,如果是那么就需要返回接收人任务人信息
    for item in mission_array:
        # item['receiver_id'] = ''
        # item['receiver_time'] = ''
        item['receiver_name'] = ''
        item['receiver_avatar'] = ''
        item['receiver_qq'] = ''
        item['receiver_wechat'] = ''
        item['receiver_phone'] = ''
        item['receiver_other_way'] = ''
        user_info = db.execute(
            'SELECT username, avatar FROM User WHERE idUser = ?',
            (item['publisher_id'], )).fetchone()
        item['avatar'] = user_info['avatar']
        item['username'] = user_info['username']
        # 暂时只考虑快递任务,如果有人接单且查询人是发布者,返回接单人信息
        if item['type'] == 1 and item['rcv_num'] == 1 and item[
                'publisher_id'] == g.user['idUser']:
            mission_order = db.execute(
                'SELECT * FROM MissionOrder WHERE order_state != 2 AND mission_id = ?',
                (item['idMissionInfo'], )).fetchone()
            receiver_info = db.execute(
                'SELECT username, avatar FROM User WHERE idUser = ?',
                (mission_order['receiver_id'], )).fetchone()
            # item['receiver_id'] = mission_order['receiver_id']
            # item['receiver_time'] = mission_order['receive_time']
            item['receiver_name'] = receiver_info['username']
            item['receiver_avatar'] = receiver_info['avatar']
            item['receiver_qq'] = mission_order['qq']
            item['receiver_wechat'] = mission_order['wechat']
            item['receiver_phone'] = mission_order['phone']
            item['receiver_other_way'] = mission_order['other_way']

    # 选出后limit个
    if limit and int(limit) < len(mission_array):
        limit = int(limit)
        mission_array = mission_array[len(mission_array) -
                                      limit:len(mission_array)]

    # notification
    return ok('Get missions successfully', data={'missions': mission_array})