Ejemplo n.º 1
0
def main():
    bb = BbRest(key, secret, bbURL)
    userName = '******'
    courseId = 'dev-bs'
    user = bb.GetUser(userId=userName).json()
    #     print(user.request.url)
    print(user)
    print(f"\nuser ID: {user['userName']} \
          email: {user['contact']['email']}")
    course = bb.GetCourse(courseId=courseId).json()
    print(f"course ID: {course['id']} \
          external ID: {course['externalId']}")
    memberships = bb.GetCourseMemberships(courseId=courseId).json()
    print('\nmemberships:', memberships)
    enrollments = bb.GetUserMemberships(userId=userName).json()
    print('\nuser enrollments:', enrollments)
    enrollment = bb.GetMembership(courseId=courseId, userId=userName).json()
    print('\ncourse user enrollment:', enrollment)

    new_user_data = {
        'externalId': 'devcon19_user',
        'userName': '******',
        'name': {
            'given': 'DevCon19',
            'family': 'User'
        },
        'password': '******',
        'contact': {
            'email': '*****@*****.**'
        }
    }
    user_name = new_user_data['userName']
    del_user = bb.DeleteUser(user_name)
    print(f'\nDeleted User: {del_user}')
    new_user = bb.CreateUser(payload=new_user_data)
    print('\n Created new user:', new_user.json())
Ejemplo n.º 2
0
def enrollments(request):
    task = request.GET.get('task')
    searchBy = request.GET.get('searchBy')

    bb_json = request.session.get('bb_json')
    if (bb_json is None):
        bb = BbRest(KEY, SECRET, f"https://{LEARNFQDN}")
        bb_json = jsonpickle.encode(bb)
        print('pickled BbRest putting it on session')
        request.session['bb_json'] = bb_json
        request.session['target_view'] = 'whoami'
        return HttpResponseRedirect(reverse('get_auth_code'))
    else:
        print('got BbRest from session')
        bb = jsonpickle.decode(bb_json)
        if bb.is_expired():
            print('expired token')
            request.session['bb_json'] = None
            whoami(request)
        bb.supported_functions()  # This and the following are required after
        bb.method_generator()  # unpickling the pickled object.
        print(f'expiration: {bb.expiration()}')

    if (task == 'search'):
        #Process request...
        print(f"ENROLLMENTS REQUEST: ACTION {task}")
        searchValueCrs = request.GET.get('searchValueCrs')
        if (searchValueCrs is not None):
            searchValueCrs = searchValueCrs.strip()
        searchValueUsr = request.GET.get('searchValueUsr')
        if (searchValueUsr is not None):
            searchValueUsr = searchValueUsr.strip()
        print(f"ENROLLMENTS REQUEST: CRS: {searchValueCrs}")
        print(f"ENROLLMENTS REQUEST: USR: {searchValueUsr}")

        if (searchBy == 'byCrsUsr'):
            print("Process by Course AND User")
            crs = "externalId:" + searchValueCrs
            usr = "******" + searchValueUsr
            resp = bb.GetMembership(
                courseId=crs,
                userId=usr,
                params={
                    'expand':
                    'user',
                    'fields':
                    'id, user.userName, user.name.given, user.name.middle, user.name.family, user.externalId, user.contact.email, availability.available, user.availability.available, dataSourceId, created'
                },
                sync=True)
            if (resp.status_code == 200):
                member_json = resp.json()
                dskresp = bb.GetDataSource(
                    dataSourceId=member_json['dataSourceId'], sync=True)
                dsk_json = dskresp.json()
                member_json['dataSourceId'] = dsk_json['externalId']
                member_json['crsExternalId'] = searchValueCrs
                member_json['usrExternalId'] = searchValueUsr
                member_json['searchBy'] = searchBy
                dskresp = bb.GetDataSources(
                    params={'fields': 'id, externalId'}, sync=True)
                dsks_json = dskresp.json()
                print("DSKS:\n", dsks_json["results"])
                dsks = dsks_json["results"]
                dsks = sortDsk(dsks)
                print("SIZE OF DSK LIST:", len(dsks))

                context = {
                    'member_json': member_json,
                    'dsks_json': dsks,
                }
            else:
                error_json = resp.json()
                print(f"RESPONSE:\n", error_json)
                context = {
                    'error_json': error_json,
                }

            return render(request, 'enrollments.html', context=context)

        elif (searchBy == 'byCrs'):
            print("Process by Course Only")
            error_json = {
                'message': 'Searching by Course is not currently supported'
            }
            print(f"RESPONSE:\n", error_json)
            context = {
                'error_json': error_json,
            }
            return render(request, 'enrollments.html', context=context)

        elif (searchBy == 'byUsr'):
            print("Process by User Only")
            error_json = {
                'message': 'Searching by Course is not currently supported'
            }
            print(f"RESPONSE:\n", error_json)
            context = {
                'error_json': error_json,
            }
            return render(request, 'enrollments.html', context=context)

        else:
            print("Cannot process request")
            error_json = {'message': 'Cannot process request'}
            print(f"RESPONSE:\n", error_json)
            context = {
                'error_json': error_json,
            }
            return render(request, 'enrollments.html', context=context)

    elif (task == 'process'):
        # print incoming parameters and then afterward submit the patch request.

        if (searchBy == 'byCrsUsr'):
            print("processing by crsusr")
            print('Request:\n ')
            print(request)

            payload = {}
            if (request.GET.get('isAvailabilityUpdateRequired1')):
                if (request.GET.get('isAvailabilityUpdateRequired1') == 'true'
                    ):
                    payload = {
                        'availability': {
                            "available":
                            request.GET.get('selectedAvailability')
                        }
                    }
            if (request.GET.get('isDataSourceKeyUpdateRequired1')):
                if (request.GET.get('isDataSourceKeyUpdateRequired1') == 'true'
                    ):
                    payload["dataSourceId"] = request.GET.get(
                        'selectedDataSourceKey')

            print("PAYLOAD\n")
            for x, y in payload.items():
                print(x, y)

            # Build and make bb request...
            crs = "externalId:" + request.GET.get('crsExternalId')
            print("crs:", crs)
            usr = "******" + request.GET.get('usrExternalId')
            print("usr", usr)

            resp = bb.UpdateMembership(
                courseId=crs,
                userId=usr,
                payload=payload,
                params={
                    'expand':
                    'user',
                    'fields':
                    'id, user.userName, user.name.given, user.name.middle, user.name.family, user.externalId, user.contact.email, availability.available, user.availability.available, dataSourceId, created'
                },
                sync=True)
            if (resp.status_code == 200):
                result_json = resp.json()  #return actual error
                dskresp = bb.GetDataSource(
                    dataSourceId=result_json['dataSourceId'], sync=True)
                dsk_json = dskresp.json()
                result_json['dataSourceId'] = dsk_json['externalId']

                context = {
                    'result_json': result_json,
                }
            else:
                error_json = resp.json()
                print(f"RESPONSE:\n", error_json)
                context = {
                    'error_json': error_json,
                }

            return render(request, 'enrollments.html', context=context)

            # crs="externalId:" + searchValueCrs
            # usr="******" + searchValueUsr
            # resp = bb.UpdateMembership(courseId=crs, userId = usr, params = {'expand':'user', 'fields':'id, user.userName, user.name.given, user.name.middle, user.name.family, user.externalId, user.contact.email, availability.available, user.availability.available, dataSourceId, created'}, sync=True )
            # if (resp.status_code == 200):
            #     member_json = resp.json() #return actual error
            #     dskresp = bb.GetDataSource(dataSourceId = member_json['dataSourceId'], sync=True)
            #     dsk_json = dskresp.json()
            #     member_json['dataSourceId'] = dsk_json['externalId']
            #     member_json['crsExternalId'] = searchValueCrs
            #     member_json['searchBy'] = searchBy
            #     dskresp = bb.GetDataSources(params={'fields':'id, externalId'}, sync=True)
            #     dsks_json = dskresp.json()
            #     print ("DSKS:\n", dsks_json["results"])
            #     print ("SIZE OF DSK LIST:", len(dsks_json["results"]))

            #     context = {
            #       'member_json': member_json,
            #       'dsks_json': dsks_json["results"],
            #     }
            # else:
            #     error_json = resp.json()
            #     print (f"RESPONSE:\n", error_json)
            #     context = {
            #         'error_json': error_json,
            #     }

            #return render(request, 'enrollments.html', context=context)

        result_json = {"brand": "Ford", "model": "Mustang", "year": 1964}

        print(f"RESPONSE:\n", result_json)

        context = {
            'result_json': result_json,
        }

        return render(request, 'enrollments.html', context=context)

    else:
        return render(request, 'enrollments.html')