Exemplo n.º 1
0
    def __init__(self, base_url, access_token):
        """
        :param base_url: The base URL of the Canvas instance's API.
        :type base_url: str
        :param access_token: The API key to authenticate requests with.
        :type access_token: str
        """
        new_url = get_institution_url(base_url)

        if 'api/v1' in base_url:
            warnings.warn(
                "`base_url` no longer requires an API version be specified. "
                "Rewriting `base_url` to {}".format(new_url),
                DeprecationWarning)

        if 'http://' in base_url:
            warnings.warn(
                "Canvas may respond unexpectedly when making requests to HTTP "
                "URLs. If possible, please use HTTPS.", UserWarning)

        if not base_url.strip():
            warnings.warn(
                "Canvas needs a valid URL, please provide a non-blank `base_url`.",
                UserWarning)

        if '://' not in base_url:
            warnings.warn(
                "An invalid `base_url` for the Canvas API Instance was used. "
                "Please provide a valid HTTP or HTTPS URL if possible.",
                UserWarning)

        base_url = new_url + '/api/v1/'

        self.__requester = Requester(base_url, access_token)
Exemplo n.º 2
0
    def prepare_canvas(self):

        # Canvas API URL
        self.API_URL = "https://canvas.ucsd.edu"
        # Canvas API key
        self.API_KEY = os.getenv("CANVAS_API_KEY")

        # Ensure that the user-supplied access token and base_url contain no leading or
        # trailing spaces that might cause issues when communicating with the API.
        #access_token = access_token.strip()
        #base_url = get_institution_url(base_url)

        self._requester = Requester(self.API_URL, self.API_KEY)
        # production account
        self.UCSD_PROD_ACCOUNT = 1

        # 115753: testacct3
        # only used in test_submit_file - TODO confirm required
        self.USER_ID = 115753
        # test caliper events course (pjamason and testacct1 teachers)
        self.COURSE_ID = 20774
        self.ASSIGNMENT_ID = 192792  # week 1 assignment
        self.TESTACCT444_NUMERIC_ID = 122382

        # Initialize a new Canvas object
        self.canvas = Canvas(self.API_URL, self.API_KEY)

        self.requester = self.canvas._Canvas__requester
        self.course = self.canvas.get_course(self.COURSE_ID)
        self.account = self.canvas.get_account(self.UCSD_PROD_ACCOUNT)

        # TODO add a cleanup here so we don't have to test for/delete pages

        yield
        self.canvas = False
Exemplo n.º 3
0
def UpdateScoreAndComments(token, assessment_item):
    domain = api.GetDomain(token.domain.url)
    requester = Requester(domain, token.token)
    sd = assessment_item.submission_datum
    shi = sd.submission_history_item
    quiz = Quiz.objects.get(assignment=shi.submission.assignment)
    attributes = {
        "course_id": quiz.assignment.course.course_id,
        "quiz_id": quiz.quiz_id,
        "id": shi.submission_history_id,
    }
    qs = QuizSubmission(requester, attributes)
    questions = {
        sd.quiz_question.question_id: {
            "score": assessment_item.score,
            "comment": assessment_item.comment,
        }
    }
    data = {
        "quiz_submissions": [{
            "attempt": 1,
            "questions": questions,
        }]
    }
    qs.update_score_and_comments(**data)
Exemplo n.º 4
0
def get_course_stream(course_id: int, base_url, access_token, **kwargs):
    """
    Parameters
    ----------
    course_id : `int`
        Course id

    base_url : `str`
        Base URL of the Canvas instance's API

    access_token : `str`
        API key to authenticate requests with

    Returns
    -------
    `dict`
        JSON response for course activity stream
    """

    access_token = access_token.strip()
    base_url = get_institution_url(base_url)
    requester = Requester(base_url, access_token)
    response = requester.request(
        "GET",
        "courses/{}/activity_stream".format(course_id),
        _kwargs=combine_kwargs(**kwargs)
    )
    return response.json()
Exemplo n.º 5
0
    def __init__(self, path, include_file = ".canvas-include.yml"):
        """
        Creates a CanvasAssignment object that will handle submissions of this
        assignment to Canvas. 'path' should be the path to an assignment 
        directory.

        :param path: path to the assignment directory
        :param include_file: the configuration file to look for in the 
                             assignment directory.
        """

        config, file_list, zip_file_list = ConfigReader(path, 
                                                        include_file).read()
        #   Add files
        self.file_list = file_list
        self.zip_file_list = zip_file_list

        #   Add configuration stuff
        self.assignment_id = config[ConfigOptions.AID.value]
        self.course_id = config[ConfigOptions.CID.value]
        url = config[ConfigOptions.URL.value]
        key = config[ConfigOptions.API_KEY.value]

        #   Add canvas stuff
        self._canvas = Canvas(url, key)
        self._requester = Requester(url, key)

        #   Add user ID stuff
        self.user_id = self._canvas.get_current_user().id
        print(self.user_id)
Exemplo n.º 6
0
 def __init__(self, base_url, access_token):
     """
     :param base_url: The base URL of the Canvas instance's API.
     :type base_url: str
     :param access_token: The API key to authenticate requests with.
     :type access_token: str
     """
     self.__requester = Requester(base_url, access_token)
Exemplo n.º 7
0
    def __init__(self):
        self.API_URL = "https://test.instructure.com"
        self.API_KEY = "your_apikey"

        self.account_id = 6681700
        self.requester = Requester(self.API_URL, self.API_KEY)
        self.canvas = Canvas(self.API_URL, self.API_KEY)
        self.account = self.canvas.get_user(self.account_id)

        self.timezone = pytz.timezone('America/New_York')
Exemplo n.º 8
0
    def __init__(self, base_url, access_token):
        """
        :param base_url: The base URL of the Canvas instance's API.
        :type base_url: str
        :param access_token: The API key to authenticate requests with.
        :type access_token: str
        """
        new_url = get_institution_url(base_url)

        if 'api/v1' in base_url:
            warnings.warn(
                "`base_url` no longer requires an API version be specified. "
                "Rewriting `base_url` to {}".format(new_url),
                DeprecationWarning)
        base_url = new_url + '/api/v1/'

        self.__requester = Requester(base_url, access_token)
Exemplo n.º 9
0
    def __init__(self, base_url, access_token):
        """
        :param base_url: The base URL of the Canvas instance's API.
        :type base_url: str
        :param access_token: The API key to authenticate requests with.
        :type access_token: str
        """
        new_url = get_institution_url(base_url)

        if "api/v1" in base_url:
            warnings.warn(
                "`base_url` no longer requires an API version be specified. "
                "Rewriting `base_url` to {}".format(new_url),
                DeprecationWarning,
            )

        if "http://" in base_url:
            warnings.warn(
                "Canvas may respond unexpectedly when making requests to HTTP "
                "URLs. If possible, please use HTTPS.",
                UserWarning,
            )

        if not base_url.strip():
            warnings.warn(
                "Canvas needs a valid URL, please provide a non-blank `base_url`.",
                UserWarning,
            )

        if "://" not in base_url:
            warnings.warn(
                "An invalid `base_url` for the Canvas API Instance was used. "
                "Please provide a valid HTTP or HTTPS URL if possible.",
                UserWarning,
            )

        # Ensure that the user-supplied access token contains no leading or
        # trailing spaces that may cause issues when communicating with
        # the API.
        access_token = access_token.strip()

        base_url = new_url + "/api/v1/"

        self.__requester = Requester(base_url, access_token)
Exemplo n.º 10
0
    def __init__(self, base_url, access_token):
        """
        :param base_url: The base URL of the Canvas instance's API.
        :type base_url: str
        :param access_token: The API key to authenticate requests with.
        :type access_token: str
        """
        if "api/v1" in base_url:
            raise ValueError(
                "`base_url` should not specify an API version. Remove trailing /api/v1/"
            )

        if "http://" in base_url:
            warnings.warn(
                "Canvas may respond unexpectedly when making requests to HTTP "
                "URLs. If possible, please use HTTPS.",
                UserWarning,
            )

        if not base_url.strip():
            warnings.warn(
                "Canvas needs a valid URL, please provide a non-blank `base_url`.",
                UserWarning,
            )

        if "://" not in base_url:
            warnings.warn(
                "An invalid `base_url` for the Canvas API Instance was used. "
                "Please provide a valid HTTP or HTTPS URL if possible.",
                UserWarning,
            )

        # Ensure that the user-supplied access token and base_url contain no leading or
        # trailing spaces that might cause issues when communicating with the API.
        access_token = access_token.strip()
        base_url = get_institution_url(base_url)

        self.__requester = Requester(base_url, access_token)
Exemplo n.º 11
0
    default=default_api_url)
parser.add_argument(
    "-at",
    "--api-token",
    type=str,
    metavar="TOKEN",
    required="CANVAS_SUBMIT_API_TOKEN" not in environ,
    help=
    "A valid API token. Can also be passed through CANVAS_SUBMIT_API_TOKEN.",
    default=default_api_token)

# Read arguments from the parser
args = parser.parse_args()

# Requester necessary for uploading files
requester = Requester(args.api_url, args.api_token)

# Canvas for API calls
canvas = Canvas(args.api_url, args.api_token)


# Method that uploads files and returns a JSON file descriptor
def upload_file(file_path):
    f = open(file_path, "rb")
    tmp_file = None
    tmp_dir = None

    if args.strip is not None and file_path.endswith(".java"):
        f = open(file_path, "r", encoding="utf-8")
        lines = f.readlines()
# ASSIGNMENT_ID = 7454623

### You may wish to change this
# your file name of choice
FILE = "submission.zip"
### Everything below is unlikely to change

# Canvas API URL
API_URL = "https://canvas.upenn.edu/api/v1/"
# Canvas API key
API_KEY = config.API_KEY
#596 course id
COURSE_ID = 1488863

# Initialize a new Requester
requester = Requester(API_URL, API_KEY)

# Make an Assignment for this course and this assignment
assignment = Assignment(requester, {
    'course_id': COURSE_ID,
    'id': ASSIGNMENT_ID
})
# print(assignment.to_json())

#if you go into the plain REST api, you'll see the python library is combining two steps:
#   1) upload a file named whatever you named yours
#   2) submit the assignment using the id of canvas id for the uploaded file in 1
response = assignment.submit({
    'submission_type': 'online_upload',
}, filename)