PyKubeGrader 0.2.19__py3-none-any.whl → 0.2.21__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: PyKubeGrader
3
- Version: 0.2.19
3
+ Version: 0.2.21
4
4
  Summary: Add a short description here!
5
5
  Home-page: https://github.com/pyscaffold/pyscaffold/
6
6
  Author: jagar2
@@ -4,8 +4,8 @@ pykubegrader/telemetry.py,sha256=h8PPrXWGFgPWCcrChJo2woqd_XIPMFfYcxgLJ0CWpH8,536
4
4
  pykubegrader/utils.py,sha256=T3GYnLnTL9VXjTZNPr00sUgMgobQYsNTGwynMyXdvHk,696
5
5
  pykubegrader/validate.py,sha256=2KLSB3wfFZbBh1NGgmrOV073paKAgrQz4AgA6LmCIj4,11076
6
6
  pykubegrader/build/__init__.py,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
7
- pykubegrader/build/api_notebook_builder.py,sha256=FEaTj1fEsPAes7KNrPuhClEvKzLuOL3wG7Hgr7FQc-o,20083
8
- pykubegrader/build/build_folder.py,sha256=8RTyr6nTHAzbHGPqb9zcQmenOgPdF78ylPG6IRAfl3c,79735
7
+ pykubegrader/build/api_notebook_builder.py,sha256=bgTfN2EDwuCPBFQ258cGUYYwDYxjEHJ8kT2brOG_dZI,20308
8
+ pykubegrader/build/build_folder.py,sha256=nPuXqSYeHIK-ZwJLyF9Ku3bqps-wM9fZigppZd1eQ3s,81498
9
9
  pykubegrader/build/clean_folder.py,sha256=8N0KyL4eXRs0DCw-V_2jR9igtFs_mOFMQufdL6tD-38,1323
10
10
  pykubegrader/graders/__init__.py,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
11
11
  pykubegrader/graders/late_assignments.py,sha256=_2-rA5RqO0BWY9WAQA_mbCxxPKTOiJOl-byD2CYWaE0,1393
@@ -14,7 +14,7 @@ pykubegrader/log_parser/parse.ipynb,sha256=H1CUuqiUSE-tiZV1IS7VG6HAEvoopGd6i_5QM
14
14
  pykubegrader/log_parser/parse.py,sha256=YCs_OCnoxQKsL55MjTZWXBBBsehJL8PIB9ANnC-aE44,7379
15
15
  pykubegrader/submit/submit_assignment.py,sha256=p-v31479342q0AO3lJrd8Fwk7iJQUz183OeGeiNcXOY,3405
16
16
  pykubegrader/tokens/tokens.py,sha256=DorNwdrA5N5apB3LQjVGa2ABN5C1upkgglecaLHobr0,1260
17
- pykubegrader/tokens/validate_token.py,sha256=QV_xWKsWowBHzmLEAFe-D_gficYvg2jSBGEnBvpoL8c,2115
17
+ pykubegrader/tokens/validate_token.py,sha256=z2S86z48UxnVCIvjUT3_u5dErfCK2yRI2sDGugHPBtQ,4044
18
18
  pykubegrader/widgets/__init__.py,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
19
19
  pykubegrader/widgets/multiple_choice.py,sha256=NjD3-uXSnibpUQ0mO3hRp_O-rynFyl0Dz6IXE4tnCRI,2078
20
20
  pykubegrader/widgets/reading_question.py,sha256=y30_swHwzH8LrT8deWTnxctAAmR8BSxTlXAqMgUrAT4,3031
@@ -27,9 +27,9 @@ pykubegrader/widgets_base/__init__.py,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-
27
27
  pykubegrader/widgets_base/multi_select.py,sha256=Cl0IN21wXLZuFu-zC65aS9tD4jMfzCRJ2DPjHao5_Ak,4044
28
28
  pykubegrader/widgets_base/reading.py,sha256=_vjUPynqmJe_R4vf-7hVhGnQR726S9GL6qT8bflBXBM,5383
29
29
  pykubegrader/widgets_base/select.py,sha256=Fw3uFNOIWo1a3CvlzSx23bvi6bSmA3TqutuRbhD4Dp8,2525
30
- PyKubeGrader-0.2.19.dist-info/LICENSE.txt,sha256=YTp-Ewc8Kems8PJEE27KnBPFnZSxoWvSg7nnknzPyYw,1546
31
- PyKubeGrader-0.2.19.dist-info/METADATA,sha256=wPPKPTXgCW6_bOgG8J7r9nFFi9SOCTPJAvJR5rk8DB4,2779
32
- PyKubeGrader-0.2.19.dist-info/WHEEL,sha256=A3WOREP4zgxI0fKrHUG8DC8013e3dK3n7a6HDbcEIwE,91
33
- PyKubeGrader-0.2.19.dist-info/entry_points.txt,sha256=UPMdTT46fQwTYJWtrUwIWIbXbwyOPfNQgBFRa0frWzw,138
34
- PyKubeGrader-0.2.19.dist-info/top_level.txt,sha256=e550Klfze6higFxER1V62fnGOcIgiKRbsrl9CC4UdtQ,13
35
- PyKubeGrader-0.2.19.dist-info/RECORD,,
30
+ PyKubeGrader-0.2.21.dist-info/LICENSE.txt,sha256=YTp-Ewc8Kems8PJEE27KnBPFnZSxoWvSg7nnknzPyYw,1546
31
+ PyKubeGrader-0.2.21.dist-info/METADATA,sha256=xp-GB2HwfV49LVDfRsp1cigdUqqSsLuti2FGsv6kdQg,2779
32
+ PyKubeGrader-0.2.21.dist-info/WHEEL,sha256=A3WOREP4zgxI0fKrHUG8DC8013e3dK3n7a6HDbcEIwE,91
33
+ PyKubeGrader-0.2.21.dist-info/entry_points.txt,sha256=UPMdTT46fQwTYJWtrUwIWIbXbwyOPfNQgBFRa0frWzw,138
34
+ PyKubeGrader-0.2.21.dist-info/top_level.txt,sha256=e550Klfze6higFxER1V62fnGOcIgiKRbsrl9CC4UdtQ,13
35
+ PyKubeGrader-0.2.21.dist-info/RECORD,,
@@ -14,6 +14,7 @@ class FastAPINotebookBuilder:
14
14
  notebook_path: str
15
15
  temp_notebook: Optional[str] = None
16
16
  assignment_tag: Optional[str] = ""
17
+ require_key: Optional[bool] = False
17
18
 
18
19
  def __post_init__(self):
19
20
  self.root_path, self.filename = FastAPINotebookBuilder.get_filename_and_root(
@@ -119,6 +120,11 @@ class FastAPINotebookBuilder:
119
120
  f"os.environ['TOTAL_POINTS_FREE_RESPONSE'] = str({self.total_points})\n"
120
121
  )
121
122
 
123
+ if self.require_key:
124
+ first_cell_header.append(
125
+ "from pykubegrader.submit.submit_assignment import validate_token\nvalidate_token()\n"
126
+ )
127
+
122
128
  short_filename = self.filename.split(".")[0].replace("_temp", "")
123
129
  first_cell_header.extend(
124
130
  [
@@ -46,6 +46,7 @@ class NotebookProcessor:
46
46
  solutions_folder: str = field(init=False)
47
47
  verbose: bool = False
48
48
  log: bool = True
49
+ require_key: bool = False
49
50
 
50
51
  def __post_init__(self):
51
52
  """
@@ -559,11 +560,22 @@ class NotebookProcessor:
559
560
  "you should see your score."
560
561
  )
561
562
 
562
- # Define the Code cell
563
- code_cell = nbformat.v4.new_code_cell(
564
- "from pykubegrader.submit.submit_assignment import submit_assignment\n\n"
565
- f'submit_assignment("week{self.week_num}-{self.assignment_type}", "{os.path.basename(notebook_path).replace(".ipynb", "")}")'
566
- )
563
+ if self.require_key:
564
+ # Add an additional line for validate_token()
565
+ validate_token_line = "from pykubegrader.submit.submit_assignment import validate_token\nvalidate_token()\n"
566
+
567
+ # Define the Code cell
568
+ code_cell = nbformat.v4.new_code_cell(
569
+ f"{validate_token_line}\n\n" # Add the validate_token() line
570
+ "from pykubegrader.submit.submit_assignment import submit_assignment\n\n"
571
+ f'submit_assignment("week{self.week_num}-{self.assignment_type}", "{os.path.basename(notebook_path).replace(".ipynb", "")}")'
572
+ )
573
+ else:
574
+ # Define the Code cell without validate_token()
575
+ code_cell = nbformat.v4.new_code_cell(
576
+ "from pykubegrader.submit.submit_assignment import submit_assignment\n\n"
577
+ f'submit_assignment("week{self.week_num}-{self.assignment_type}", "{os.path.basename(notebook_path).replace(".ipynb", "")}")'
578
+ )
567
579
 
568
580
  # Make the code cell non-editable and non-deletable
569
581
  code_cell.metadata = {"editable": False, "deletable": False}
@@ -607,7 +619,9 @@ class NotebookProcessor:
607
619
  shutil.copy("./keys/.server_public_key.bin", server_public_key)
608
620
 
609
621
  out = FastAPINotebookBuilder(
610
- notebook_path=temp_notebook_path, assignment_tag=self.assignment_tag
622
+ notebook_path=temp_notebook_path,
623
+ assignment_tag=self.assignment_tag,
624
+ require_key=self.require_key,
611
625
  )
612
626
 
613
627
  debug_notebook = os.path.join(
@@ -632,7 +646,10 @@ class NotebookProcessor:
632
646
  )
633
647
 
634
648
  NotebookProcessor.add_initialization_code(
635
- student_notebook, self.week, self.assignment_type
649
+ student_notebook,
650
+ self.week,
651
+ self.assignment_type,
652
+ require_key=self.require_key,
636
653
  )
637
654
 
638
655
  NotebookProcessor.replace_temp_in_notebook(
@@ -659,7 +676,10 @@ class NotebookProcessor:
659
676
  return student_notebook, out.total_points
660
677
  else:
661
678
  NotebookProcessor.add_initialization_code(
662
- temp_notebook_path, self.week, self.assignment_type
679
+ temp_notebook_path,
680
+ self.week,
681
+ self.assignment_type,
682
+ require_key=self.require_key,
663
683
  )
664
684
  NotebookProcessor.replace_temp_no_otter(
665
685
  temp_notebook_path, temp_notebook_path
@@ -691,11 +711,19 @@ class NotebookProcessor:
691
711
  nbformat.write(notebook, f)
692
712
 
693
713
  @staticmethod
694
- def add_initialization_code(notebook_path, week, assignment_type):
714
+ def add_initialization_code(
715
+ notebook_path, week, assignment_type, require_key=False
716
+ ):
695
717
  # finds the first code cell
696
718
  index, cell = find_first_code_cell(notebook_path)
697
719
  cell = cell["source"]
698
- import_text = "from pykubegrader.initialize import initialize_assignment\n"
720
+ import_text = "# You must make sure to run all cells in sequence using shift + enter or you might encounter errors\n"
721
+ import_text += "from pykubegrader.initialize import initialize_assignment\n"
722
+ if require_key:
723
+ import_text += (
724
+ "from pykubegrader.token.validate_token import validate_token\n"
725
+ )
726
+ import_text += "validate_token('type the key provided by your TA here')\n"
699
727
  import_text += f'\nresponses = initialize_assignment("{os.path.splitext(os.path.basename(notebook_path))[0]}", "{week}", "{assignment_type}" )\n'
700
728
  cell = f"{import_text}\n" + cell
701
729
  replace_cell_source(notebook_path, index, cell)
@@ -1740,7 +1768,9 @@ def generate_mcq_file(data_dict, output_file="mc_questions.py"):
1740
1768
  )
1741
1769
  f.write(" def __init__(self):\n")
1742
1770
  f.write(" super().__init__(\n")
1743
- f.write(f' title=f"{q_value['question_text']}",\n')
1771
+ f.write(
1772
+ f' title=f"Question{q_value['question number']}: {q_value['title']}",\n'
1773
+ )
1744
1774
  f.write(" style=MCQ,\n")
1745
1775
  f.write(
1746
1776
  f" question_number={q_value['question number']},\n"
@@ -1811,7 +1841,9 @@ def generate_select_many_file(data_dict, output_file="select_many_questions.py")
1811
1841
  )
1812
1842
  f.write(" def __init__(self):\n")
1813
1843
  f.write(" super().__init__(\n")
1814
- f.write(f' title=f"{q_value['question_text']}",\n')
1844
+ f.write(
1845
+ f' title=f"Question{q_value['question number']}: {q_value['title']}",\n'
1846
+ )
1815
1847
  f.write(" style=MultiSelect,\n")
1816
1848
  f.write(
1817
1849
  f" question_number={q_value['question number']},\n"
@@ -1888,7 +1920,9 @@ def generate_tf_file(data_dict, output_file="tf_questions.py"):
1888
1920
  )
1889
1921
  f.write(" def __init__(self):\n")
1890
1922
  f.write(" super().__init__(\n")
1891
- f.write(f' title=f"{q_value['question_text']}",\n')
1923
+ f.write(
1924
+ f' title=f"Question{q_value['question number']}: {q_value['title']}",\n'
1925
+ )
1892
1926
  f.write(" style=TFStyle,\n")
1893
1927
  f.write(
1894
1928
  f" question_number={q_value['question number']},\n"
@@ -2060,9 +2094,18 @@ def main():
2060
2094
  default="Reading-Week-X",
2061
2095
  )
2062
2096
 
2097
+ parser.add_argument(
2098
+ "--require-key",
2099
+ type=bool,
2100
+ help="Require a key to be generated for the assignment",
2101
+ default=False,
2102
+ )
2103
+
2063
2104
  args = parser.parse_args()
2064
2105
  processor = NotebookProcessor(
2065
- root_folder=args.root_folder, assignment_tag=args.assignment_tag
2106
+ root_folder=args.root_folder,
2107
+ assignment_tag=args.assignment_tag,
2108
+ require_key=args.require_key,
2066
2109
  )
2067
2110
  processor.process_notebooks()
2068
2111
 
@@ -1,5 +1,12 @@
1
- import requests
2
1
  import os
2
+ import base64
3
+ import httpx
4
+ import asyncio
5
+ import nest_asyncio
6
+
7
+ # Apply nest_asyncio for environments like Jupyter
8
+ nest_asyncio.apply()
9
+
3
10
 
4
11
  class TokenValidationError(Exception):
5
12
  """
@@ -16,9 +23,25 @@ class TokenValidationError(Exception):
16
23
  super().__init__(message)
17
24
 
18
25
 
19
- def validate_token(token = None):
26
+ def get_credentials():
27
+ """
28
+ Fetch the username and password from environment variables.
29
+
30
+ Returns:
31
+ dict: A dictionary containing 'username' and 'password'.
32
+ """
33
+ username = os.getenv("user_name_student")
34
+ password = os.getenv("keys_student")
35
+ if not username or not password:
36
+ raise ValueError(
37
+ "Environment variables 'user_name_student' or 'keys_student' are not set."
38
+ )
39
+ return {"username": username, "password": password}
40
+
41
+
42
+ async def async_validate_token(token: str) -> None:
20
43
  """
21
- Validate a token by making a GET request to the validation endpoint.
44
+ Asynchronously validate a token by making a GET request to the validation endpoint.
22
45
 
23
46
  Args:
24
47
  token (str): The token to validate.
@@ -29,7 +52,7 @@ def validate_token(token = None):
29
52
  Returns:
30
53
  None: If the token is valid, the function will pass silently.
31
54
  """
32
- # sets the token in the environment variable
55
+
33
56
  if token is not None:
34
57
  os.environ["TOKEN"] = token
35
58
 
@@ -39,26 +62,70 @@ def validate_token(token = None):
39
62
  if token is None:
40
63
  raise TokenValidationError("No token provided")
41
64
 
42
- # Define the validation endpoint
43
- endpoint = f"https://engr-131-api.eastus.cloudapp.azure.com/validate-token/{token}"
65
+ # Fetch the endpoint URL
66
+ base_url = os.getenv("DB_URL")
67
+ if not base_url:
68
+ raise ValueError("Environment variable 'DB_URL' is not set.")
69
+ endpoint = f"{base_url}validate-token/{token}"
44
70
 
45
- try:
46
- response = requests.get(endpoint, timeout=10)
47
-
48
- if response.status_code == 200:
49
- # If the response is 200, the token is valid
50
- return # Pass silently
51
- elif response.status_code == 404:
52
- # If the response is 404, the token is invalid
53
- raise TokenValidationError(response.json().get("detail", "Token not found"))
54
- else:
55
- # Handle unexpected status codes
56
- raise TokenValidationError(
57
- f"Unexpected response code: {response.status_code}"
71
+ # Get credentials
72
+ credentials = get_credentials()
73
+ username = credentials["username"]
74
+ password = credentials["password"]
75
+
76
+ # Encode credentials for Basic Authentication
77
+ auth_header = (
78
+ f"Basic {base64.b64encode(f'{username}:{password}'.encode()).decode()}"
79
+ )
80
+
81
+ # Make the GET request
82
+ async with httpx.AsyncClient() as client:
83
+ try:
84
+ response = await client.get(
85
+ endpoint, headers={"Authorization": auth_header}, timeout=10
58
86
  )
59
- except requests.RequestException as e:
60
- # Raise an exception for connection errors or timeout
61
- raise TokenValidationError(f"Request failed: {e}")
87
+
88
+ if response.status_code == 200:
89
+ # If the response is 200, the token is valid
90
+ return # Pass silently
91
+ elif response.status_code == 404:
92
+ # If the response is 404, the token is invalid
93
+ detail = response.json().get("detail", "Token not found")
94
+ raise TokenValidationError(detail)
95
+ else:
96
+ # Handle unexpected status codes
97
+ raise TokenValidationError(
98
+ f"Unexpected response code: {response.status_code}"
99
+ )
100
+ except httpx.RequestError as e:
101
+ raise TokenValidationError(f"Request failed: {e}")
102
+ except Exception as e:
103
+ raise TokenValidationError(f"An unexpected error occurred: {e}")
104
+
105
+
106
+ def validate_token(token: str) -> None:
107
+ """
108
+ Synchronous wrapper for the `async_validate_token` function.
109
+
110
+ Args:
111
+ token (str): The token to validate.
112
+
113
+ Raises:
114
+ TokenValidationError: If the token is invalid or if there is an error in the validation process.
115
+
116
+ Returns:
117
+ None: If the token is valid, the function will pass silently.
118
+ """
119
+
120
+ # Get the current event loop or create one
121
+ try:
122
+ loop = asyncio.get_event_loop()
123
+ except RuntimeError:
124
+ loop = asyncio.new_event_loop()
125
+ asyncio.set_event_loop(loop)
126
+
127
+ # Run the async function in the event loop
128
+ loop.run_until_complete(async_validate_token(token))
62
129
 
63
130
 
64
131
  # Example usage