Example #1
0
def project_project_id_get(projectId):  # noqa: E501
    """返回一个Project的详细信息

    # noqa: E501

    :param projectId:
    :type projectId: int

    :rtype: Learner
    """

    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    validation_result = wxLogin.validateUser()
    if not validation_result["result"]:
        db_session.remove()
        return {"error": "Failed to validate access token"}, 401
    learner = db_session.query(orm.Learner_db).filter(
        orm.Learner_db.openid == validation_result["openid"]).one_or_none()
    if not learner.validated:
        db_session.remove()
        return {"error": "Learner not validated"}, 401
    project = db_session.query(
        orm.Project_db).filter(orm.Project_db.id == projectId).one_or_none()
    projectInfo = {
        "id": project.id,
        "name": project.name,
        "status": project.status,
        "createdTime": project.createdTime,
        "createdByID": project.createdByID,
        "createdBy": project.createdBy,
        "relatedCourseId": project.relatedCourseId,
        "relatedCourse": project.relatedCourse,
        "projectTerm": project.projectTerm,
        "projectTermLength": project.projectTermLength,
        "projectStartDate": project.projectStartDate,
        "averageIntendedCreditHourPerWeek":
        project.averageIntendedCreditHourPerWeek,
        "totalIntendedCreditHour": project.totalIntendedCreditHour,
        "projectMentorID": project.projectMentorID,
        "projectMentor": project.projectMentor,
        "averageGuidingHourPerWeek": project.averageGuidingHourPerWeek,
        "projectMeta": json.loads(project.projectMeta),
        "projectApprovalInfo": json.loads(project.projectApprovalInfo),
        "content": json.loads(project.content),
        "conclusionInfo": json.loads(project.conclusionInfo),
        "lastUpdatedTime": project.lastUpdatedTime,
        "coverImageURL": project.coverImageURL
    }
    db_session.remove()
    return projectInfo, 200, {
        "Authorization": validation_result["access_token"],
        "refresh_token": validation_result["refresh_token"]
    }
Example #2
0
def project_get():  # noqa: E501
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    validation_result = wxLogin.validateUser()
    if not validation_result["result"]:
        db_session.remove()
        return {"error": "Failed to validate access token"}, 401
    result_list = []
    query = db_session.query(orm.Project_db).all()
    for project in query:
        result_list.append({
            "id": project.id,
            "name": project.name,
            "createdTime": project.createdTime,
            "createdBy": project.createdBy,
            "createdByID": project.createdByID,
            "relatedCourse": project.relatedCourse,
            "projectMentorID": project.projectMentorID,
            "projectMentor": project.projectMentor,
            "status": project.status,
            "coverImageURL": project.coverImageURL
        })
    db_session.remove()
    return result_list, 200, {
        "Authorization": validation_result["access_token"],
        "refresh_token": validation_result["refresh_token"]
    }
Example #3
0
def learner_get():  # noqa: E501
    """返回所有Learner的全部信息

    # noqa: E501
    # 权限限定:mentor限定(未实装)


    :rtype: InlineResponse2001
    """
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    validation_result = wxLogin.validateUser()
    if not validation_result["result"]:
        return {"error": "Failed to validate access token"}, 401
    result_list = []
    query = db_session.query(orm.Learner_db).filter(orm.Learner_db.validated == True).all()
    for learner in query:
        result_list.append({
            "id": learner.id,
            "givenName": learner.givenName,
            "familyName": learner.familyName,
            "isMentor": learner.isMentor
        })
    db_session.remove()
    return result_list, 200, {"Authorization": validation_result["access_token"], "refresh_token": validation_result["refresh_token"]}
Example #4
0
def learner_post(learner):  # noqa: E501
    """创建一个Learner

    # noqa: E501

    :param learner:
    :type learner: dict | bytes

    :rtype: InlineResponse201
    """
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    validation_result = wxLogin.validateUser()
    if not validation_result["result"]:
        return {"error": "Failed to validate access token"}, 401
    if connexion.request.is_json:
        learner = Learner.from_dict(connexion.request.get_json())  # noqa: E501
        learner_dict = connexion.request.get_json()
    # 获取unionid
    try:
        userInfo = requests.get("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s" % (validation_result["access_token"], connexion.request.headers['openid']))
        db_session.add(orm.Learner_db(
            validated=False,
            openid=connexion.request.headers['openid'],
            unionid=userInfo.json()['unionid'],
            sessionKey='0',
            openidWeApp='0',
            isAdmin=False,
            status=learner.status,
            isMentor=learner.is_mentor,
            givenName=learner.given_name,
            familyName=learner.family_name,
            nickname=learner.nickname,
            gender=learner.gender,
            ethnicity=learner.ethnicity,
            birthday=learner.birthday,
            mainPersonalIdType=learner.main_personal_id_type,
            mainPersonalId=learner.main_personal_id,
            dateOfRegistration=learner.date_of_registration,
            reasonOfRegistration=learner.reason_of_registration,
            previousStatus=learner.previous_status,
            custodianInfo=json.dumps(learner_dict["custodianInfo"]),
            emergentContact=json.dumps(learner_dict["emergentContact"]),
            contactInfo=json.dumps(learner_dict["contactInfo"]),
            medicalInfo=json.dumps(learner_dict["medicalInfo"]),
            notes=json.dumps(learner_dict["notes"]),
        ))
        db_session.commit()
    except Exception as e:
        db_session.remove()
        return {"error": str(e)}, 401, {"Authorization": validation_result["access_token"], "refresh_token": validation_result["refresh_token"]}
    db_session.remove()
    return {}, 201, {"Authorization": validation_result["access_token"], "refresh_token": validation_result["refresh_token"]}
def course_get():  # noqa: E501
    validation_result = wxLogin.validateUser()
    if not validation_result["result"]:
        return {"error": "Failed to validate access token"}, 401
    """返回所有Course

    # noqa: E501

    :param learnerId:
    :type learnerId: int

    :rtype: List[Course]
    """
    return 'do some magic!'
def booking_get():  # noqa: E501
    # 获取所有的房间信息
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    validation_result = wxLogin.validateUser()
    if not validation_result["result"]:
        db_session.remove()
        return {"error": "Failed to validate access token"}, 401
    response = []
    roomLists = db_session.query(orm.Config_db).filter(
        orm.Config_db.name == 'roomLists').one_or_none().value
    roomDescriptions = db_session.query(orm.Config_db).filter(
        orm.Config_db.name == 'roomDescriptions').one_or_none().value
    try:
        for roomList in roomLists:
            roomsEWS = GetRooms(protocol=account.protocol).call(
                roomlist=RoomList(email_address=roomList['email']))
            rooms = []
            for room in roomsEWS:
                roomCode = room.email_address.split("@")[0]
                rooms.append({
                    'name': room.name,
                    'roomCode': roomCode,
                    'email': room.email_address,
                    'description': roomDescriptions.get(roomCode, "")
                })
            entry = {'listname': roomList['name'], 'rooms': rooms}
            response.append(entry)
    except Exception as e:
        db_session.remove()
        return {
            "error": str(e)
        }, 400, {
            "Authorization": validation_result["access_token"],
            "refresh_token": validation_result["refresh_token"]
        }
    db_session.remove()
    return response, 200, {
        "Authorization": validation_result["access_token"],
        "refresh_token": validation_result["refresh_token"]
    }
def project_cover_post():  # noqa: E501

    ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'gif', 'GIF'])

    def allowed_file(filename):
        return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

    def create_uuid():  # 生成唯一的图片的名称字符串,防止图片显示时的重名问题
        nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S")  # 生成当前时间
        randomNum = random.randint(0, 100)  # 生成的随机整数n,其中0<=n<=100
        if randomNum <= 10:
            randomNum = str(0) + str(randomNum)
        uniqueNum = str(nowTime) + str(randomNum)
        return uniqueNum

    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    validation_result = wxLogin.validateUser()
    if not validation_result["result"]:
        db_session.remove()
        return {"error": "Failed to validate access token"}, 401, {"Authorization": validation_result["access_token"], "refresh_token": validation_result["refresh_token"]}
    learner = db_session.query(orm.Learner_db).filter(orm.Learner_db.openid == validation_result["openid"]).one_or_none()
    if not learner.validated:
        db_session.remove()
        return {"error": "Learner not validated"}, 401, {"Authorization": validation_result["access_token"], "refresh_token": validation_result["refresh_token"]}
    img = connexion.request.files.get('project_cover')
    extension = os.path.splitext(img.filename)[-1]
    uid = create_uuid()
    if not allowed_file(img.filename):
        db_session.remove()
        return {"error": "文件类型错误"}, 403, {"Authorization": validation_result["access_token"], "refresh_token": validation_result["refresh_token"]}
    path = os.path.join(os.environ["STORAGEURL"], str(learner.id))
    if not os.path.exists(path):
        os.makedirs(path)
    file_path = os.path.join(path, uid + extension)
    url = uid + extension
    img.save(file_path)
    db_session.remove()
    return {"url": url}, 201, {"Authorization": validation_result["access_token"], "refresh_token": validation_result["refresh_token"]}
def connectToMicrosoft(connectToMicrosoftBody):
    MICROSOFT_CLIENT_ID: str = os.environ['MICROSOFT_CLIENT_ID']
    MICROSOFT_CLIENT_SECRET: str = os.environ['MICROSOFT_CLIENT_SECRET']
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    connectToMicrosoftBody_dict = connexion.request.get_json()
    validation_result = wxLogin.validateUser()
    if not validation_result["result"]:
        db_session.remove()
        return {"error": "Failed to validate access token"}, 401
    learner = db_session.query(orm.Learner_db).filter(orm.Learner_db.openid == validation_result["openid"]).one_or_none()
    if not learner.validated:
        db_session.remove()
        return {"error": "Learner not validated"}, 401
    try:
        tokenPostBody = {
            "client_id": MICROSOFT_CLIENT_ID,
            "scope": "offline_access openid profile https://graph.microsoft.com/calendars.readwrite https://graph.microsoft.com/user.readwrite",
            "code": connectToMicrosoftBody_dict["code"],
            "redirect_uri": "http://localhost:8000/connectToMicrosoft",  # TODO: 此处redirect_uri应当存入config
            "grant_type": "authorization_code",
            "client_secret": MICROSOFT_CLIENT_SECRET
        }
        tokenResponse = requests.post("https://login.microsoftonline.com/common/oauth2/v2.0/token", data=tokenPostBody)
        microsoftAccessToken = tokenResponse.json()["access_token"]
        microsoftRefreshToken = tokenResponse.json()["refresh_token"]
        learner.microsoftAccessToken = microsoftAccessToken
        learner.microsoftRefreshToken = microsoftRefreshToken
        me = graphAPI.getMe(microsoftAccessToken)
        learner.microsoftId = me['id']
        learner.microsoftUserPrincipalName = me['userPrincipalName']
        db_session.commit()
    except Exception as e:
        db_session.remove()
        return {'error': str(e)}, 400
    db_session.remove()
    return {"message": "成功写入Microsoft账号相关信息", "microsoftId": me['id']}, 200
def course_post(course):  # noqa: E501
    """创建一个Learner

    # noqa: E501

    :param learner:
    :type learner: dict | bytes

    :rtype: InlineResponse201
    """
    validation_result = wxLogin.validateUser()
    if not validation_result["result"]:
        return {"error": "Failed to validate access token"}, 401
    if connexion.request.is_json:
        course = Course.from_dict(connexion.request.get_json())
    return {}, 201, {
        "Authorization": validation_result["access_token"],
        "refresh_token": validation_result["refresh_token"]
    }
def config_get():
    # 获取基本设置。没有加密,切勿放置敏感信息。
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    validation_result = wxLogin.validateUser()
    if not validation_result["result"]:
        db_session.remove()
        return {"error": "Failed to validate access token"}, 401, {"Authorization": validation_result["access_token"], "refresh_token": validation_result["refresh_token"]}
    config = db_session.query(orm.Config_db).all()
    response = []
    for item in config:
        response.append({
            item.name: item.value
        })
    db_session.remove()
    return response, 200, {"Authorization": validation_result["access_token"], "refresh_token": validation_result["refresh_token"]}
def course_cover_get(coverImageURL):  # noqa: E501
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    validation_result = wxLogin.validateUser()
    if not validation_result["result"]:
        db_session.remove()
        return {"error": "Failed to validate access token"}, 401, {"Authorization": validation_result["access_token"], "refresh_token": validation_result["refresh_token"]}
    learner = db_session.query(orm.Learner_db).filter(orm.Learner_db.openid == validation_result["openid"]).one_or_none()
    if not learner.validated:
        db_session.remove()
        return {"error": "Learner not validated"}, 401, {"Authorization": validation_result["access_token"], "refresh_token": validation_result["refresh_token"]}
    img_local_path = os.path.join(os.environ["STORAGEURL"], "courseCover", coverImageURL)
    img_stream = ''
    with open(img_local_path, 'rb') as img_f:
        img_stream = img_f.read()
        img_stream = base64.b64encode(img_stream)
    db_session.remove()
    return {"courseCover": img_stream.decode("utf-8")}, 200, {"Authorization": validation_result["access_token"], "refresh_token": validation_result["refresh_token"]}
def booking_roomCode_get(roomCode, monthToLoad):  # noqa: E501
    # 按房间信息和月份(query中)获取所有的预约信息
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    responseList = []
    validation_result = wxLogin.validateUser()
    if not validation_result["result"]:
        db_session.remove()
        return {"error": "Failed to validate access token"}, 401
    try:
        room_account = Account(primary_smtp_address=('*****@*****.**' %
                                                     roomCode),
                               credentials=credentials,
                               config=config)
    except Exception as e:
        db_session.remove()
        return {
            "error": str(e)
        }, 400, {
            "Authorization": validation_result["access_token"],
            "refresh_token": validation_result["refresh_token"]
        }
    monthToLoad_year = int(monthToLoad.split("-")[0])
    monthToLoad_month = int(monthToLoad.split("-")[1])
    if monthToLoad_month == 1:
        start = room_account.default_timezone.localize(
            EWSDateTime(monthToLoad_year - 1, 12, 1))
    else:
        start = room_account.default_timezone.localize(
            EWSDateTime(monthToLoad_year, monthToLoad_month - 1, 1))
    if monthToLoad_month == 11:
        end = room_account.default_timezone.localize(
            EWSDateTime(monthToLoad_year + 1, 1, 1))
    elif monthToLoad_month == 12:
        end = room_account.default_timezone.localize(
            EWSDateTime(monthToLoad_year + 1, 2, 1))
    else:
        end = room_account.default_timezone.localize(
            EWSDateTime(monthToLoad_year, monthToLoad_month + 2, 1))
    try:
        for item in room_account.calendar.view(
                start=start, end=end).all().order_by('start'):
            notes = db_session.query(orm.BookingNotes_db).filter(
                orm.BookingNotes_db.changekey == item.changekey).one_or_none()
            localizedStart = item.start.astimezone(get_localzone())
            localizedEnd = item.end.astimezone(get_localzone())
            bookedByID = getattr(notes, "bookedByID", 0)
            bookedByName = getattr(notes, "bookedByName", "")
            responseList.append({
                'startDate': ("%d-%0*d-%0*d" %
                              (localizedStart.year, 2, localizedStart.month, 2,
                               localizedStart.day)),
                'endDate':
                ("%d-%0*d-%0*d" % (localizedEnd.year, 2, localizedEnd.month, 2,
                                   localizedEnd.day)),
                'startTime':
                ("%0*d:%0*d" %
                 (2, localizedStart.hour, 2, localizedStart.minute)),
                'endTime':
                ("%0*d:%0*d" % (2, localizedEnd.hour, 2, localizedEnd.minute)),
                'subject':
                item.subject,
                'changekey':
                item.changekey,
                'bookedByID':
                bookedByID,
                'bookedByName':
                bookedByName,
                'description':
                '' if not getattr(item, 'text_body') else getattr(
                    item, 'text_body'),
                'type':
                'appointment'
            })
    except Exception as e:
        db_session.remove()
        return {
            "error": str(e)
        }, 400, {
            "Authorization": validation_result["access_token"],
            "refresh_token": validation_result["refresh_token"]
        }
    db_session.remove()
    return responseList, 200, {
        "Authorization": validation_result["access_token"],
        "refresh_token": validation_result["refresh_token"]
    }
def booking_roomCode_delete(roomCode, monthToLoad, deleteInfo):  # noqa: E501
    # 按照月份、changekey、房间号删除预约信息
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    validation_result = wxLogin.validateUser()
    changekey = deleteInfo['changekey']
    if not validation_result["result"]:
        db_session.remove()
        return {"error": "Failed to validate access token"}, 401
    validation_result = wxLogin.validateUser()
    if not validation_result["result"]:
        db_session.remove()
        return {"error": "Failed to validate access token"}, 401
    learner = db_session.query(orm.Learner_db).filter(
        orm.Learner_db.openid == validation_result["openid"]).one_or_none()
    try:
        room_account = Account(primary_smtp_address=('*****@*****.**' %
                                                     roomCode),
                               credentials=credentials,
                               config=config)
    except Exception as e:
        db_session.remove()
        return {
            "error": str(e)
        }, 400, {
            "Authorization": validation_result["access_token"],
            "refresh_token": validation_result["refresh_token"]
        }
    start_year = int(monthToLoad.split("-")[0])
    start_month = int(monthToLoad.split("-")[1])
    start = room_account.default_timezone.localize(
        EWSDateTime(start_year, start_month, 1))
    if start_month == 12:
        end = room_account.default_timezone.localize(
            EWSDateTime(start_year + 1, 1, 1))
    else:
        end = room_account.default_timezone.localize(
            EWSDateTime(start_year, start_month + 1, 1))
    try:
        for item in room_account.calendar.filter(
                start__range=(start, end)).all().order_by('start'):
            if item.changekey == changekey:
                notes = db_session.query(orm.BookingNotes_db).filter(
                    orm.BookingNotes_db.changekey ==
                    item.changekey).one_or_none()
                if notes.bookedByID == learner.id:
                    item.delete()
    except Exception as e:
        db_session.remove()
        return {
            "error": str(e)
        }, 400, {
            "Authorization": validation_result["access_token"],
            "refresh_token": validation_result["refresh_token"]
        }
    db_session.remove()
    return {
        'message': 'success'
    }, 201, {
        "Authorization": validation_result["access_token"],
        "refresh_token": validation_result["refresh_token"]
    }
def booking_roomCode_post(roomCode, appointment):  # noqa: E501
    # 添加预约信息
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    validation_result = wxLogin.validateUser()
    if not validation_result["result"]:
        db_session.remove()
        return {"error": "Failed to validate access token"}, 401
    learner = db_session.query(orm.Learner_db).filter(
        orm.Learner_db.openid == validation_result["openid"]).one_or_none()
    if not learner.validated:
        db_session.remove()
        return {"error": "Learner not validated"}, 401
    room_account = Account(primary_smtp_address=('*****@*****.**' %
                                                 roomCode),
                           credentials=credentials,
                           config=config)
    startDateTime = room_account.default_timezone.localize(
        EWSDateTime(appointment['startYear'], appointment['startMonth'],
                    appointment['startDay'], appointment['startHour'],
                    appointment['startMinute']))
    endDateTime = room_account.default_timezone.localize(
        EWSDateTime(appointment['endYear'], appointment['endMonth'],
                    appointment['endDay'], appointment['endHour'],
                    appointment['endMinute']))
    try:
        item = CalendarItem(
            account=room_account,
            folder=room_account.calendar,
            start=startDateTime,
            end=endDateTime,
            subject=appointment['subject'],
            body=appointment['description'],
        )
        item.save(send_meeting_invitations=SEND_TO_ALL_AND_SAVE_COPY)
        db_session.add(
            orm.BookingNotes_db(changekey=item.changekey,
                                bookedByID=learner.id,
                                bookedByName=learner.familyName +
                                learner.givenName))
        db_session.commit()
    except Exception as e:
        db_session.remove()
        return {
            "error": str(e)
        }, 400, {
            "Authorization": validation_result["access_token"],
            "refresh_token": validation_result["refresh_token"]
        }
    db_session.remove()
    return {
        'message': 'success'
    }, 201, {
        "Authorization": validation_result["access_token"],
        "refresh_token": validation_result["refresh_token"]
    }
Example #15
0
def project_post(project):  # noqa: E501
    """创建一个Learner

    # noqa: E501

    :param learner:
    :type learner: dict | bytes

    :rtype: InlineResponse201
    """
    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    validation_result = wxLogin.validateUser()
    if not validation_result["result"]:
        db_session.remove()
        return {"error": "Failed to validate access token"}, 401
    learner = db_session.query(orm.Learner_db).filter(
        orm.Learner_db.openid == validation_result["openid"]).one_or_none()
    if not learner.validated:
        db_session.remove()
        return {"error": "Learner not validated"}, 401
    if connexion.request.is_json:
        project = Project.from_dict(connexion.request.get_json())
    project_dict = connexion.request.get_json()
    try:
        db_session.add(
            orm.Project_db(
                name=project.name,
                status="未提交",
                createdTime=datetime.date.today().strftime('%Y-%m-%d'),
                createdByID=learner.id,
                createdBy=learner.familyName + learner.givenName,
                relatedCourseId=project.related_course_id,
                relatedCourse=project.related_course,
                projectTerm=project.project_term,
                projectTermLength=project.project_term_length,
                projectStartDate=project.project_start_date,
                averageIntendedCreditHourPerWeek=project.
                average_intended_credit_hour_per_week,
                totalIntendedCreditHour=project.total_intended_credit_hour,
                projectMentorID=project.project_mentor_id,
                projectMentor=project.project_mentor,
                averageGuidingHourPerWeek=project.
                average_guiding_hour_per_week,
                projectMeta=json.dumps(project_dict["projectMeta"]),
                projectApprovalInfo=json.dumps(
                    project_dict["projectApprovalInfo"]),
                conclusionInfo=json.dumps(project_dict["conclusionInfo"]),
                content='[]',
                coverImageURL=project_dict["coverImageURL"]))
        db_session.commit()
    except Exception as e:
        db_session.remove()
        return {"error": str(e)}, 401
    db_session.remove()
    return {}, 201, {
        "Authorization": validation_result["access_token"],
        "refresh_token": validation_result["refresh_token"]
    }
Example #16
0
def project_project_id_patch(projectId):  # noqa: E501
    """返回一个Project的详细信息

    # noqa: E501

    :param projectId:
    :type projectId: int

    :rtype: Learner
    """

    db_session = None
    if "DEVMODE" in os.environ:
        if os.environ["DEVMODE"] == "True":
            db_session = orm.init_db(os.environ["DEV_DATABASEURI"])
        else:
            db_session = orm.init_db(os.environ["DATABASEURI"])
    else:
        db_session = orm.init_db(os.environ["DATABASEURI"])
    validation_result = wxLogin.validateUser()
    if not validation_result["result"]:
        db_session.remove()
        return {"error": "Failed to validate access token"}, 401
    learner = db_session.query(orm.Learner_db).filter(
        orm.Learner_db.openid == validation_result["openid"]).one_or_none()
    if not learner.validated:
        db_session.remove()
        return {"error": "Learner not validated"}, 401
    project = db_session.query(
        orm.Project_db).filter(orm.Project_db.id == projectId).one_or_none()
    if connexion.request.is_json:
        patch = Project.from_dict(connexion.request.get_json())
    patchDict = {
        "name":
        patch.name,
        "status":
        patch.status,
        "projectTerm":
        patch.project_term,
        "projectTermLength":
        patch.project_term_length,
        "projectStartDate":
        patch.project_start_date,
        "averageIntendedCreditHourPerWeek":
        patch.average_intended_credit_hour_per_week,
        "totalIntendedCreditHour":
        patch.total_intended_credit_hour,
        "projectMentorID":
        patch.project_mentor_id,
        "projectMentor":
        patch.project_mentor,
        "averageGuidingHourPerWeek":
        patch.average_guiding_hour_per_week,
        "projectMeta":
        json.dumps(connexion.request.get_json()["projectMeta"] if patch.
                   project_meta is not None else None),
        "projectApprovalInfo":
        json.dumps(connexion.request.get_json()["projectApprovalInfo"]
                   if patch.project_approval_info is not None else None),
        "content":
        json.dumps(connexion.request.get_json()["content"] if patch.
                   content is not None else None),
        "conclusionInfo":
        json.dumps(connexion.request.get_json()["conclusionInfo"] if patch.
                   conclusion_info is not None else None),
        "coverImageURL":
        connexion.request.get_json().get("coverImageURL", ""),
    }
    patchDict = {k: v for k, v in patchDict.items() if v is not None}
    # patchMapper = {
    #     "name": project.name,
    #     "status": project.status,
    #     "projectTerm": project.projectTerm,
    #     "projectTermLength": project.projectTermLength,
    #     "projectStartDate": project.projectStartDate,
    #     "averageIntendedCreditHourPerWeek": project.averageIntendedCreditHourPerWeek,
    #     "totalIntendedCreditHour": project.totalIntendedCreditHour,
    #     "projectMentorID": project.projectMentorID,
    #     "projectMentor": project.projectMentor,
    #     "averageGuidingHourPerWeek": project.averageGuidingHourPerWeek,
    #     "projectMeta": project.projectMeta,
    #     "projectApprovalInfo": project.projectApprovalInfo,
    #     "content": project.content,
    #     "conclusionInfo": project.conclusionInfo,
    #     "lastUpdatedTime": project.lastUpdatedTime,
    # }
    try:
        for item, value in patchDict.items():
            setattr(project, item, value)
        db_session.commit()
    except Exception as e:
        db_session.remove()
        return {"error": str(e)}, 401
    db_session.remove()
    return {}, 200, {
        "Authorization": validation_result["access_token"],
        "refresh_token": validation_result["refresh_token"]
    }