Skip to content

Commit 4db0d1d

Browse files
authored
Fixed Linting
@costowell fixed linting.
2 parents 019a7b6 + 48f1a33 commit 4db0d1d

File tree

10 files changed

+97
-79
lines changed

10 files changed

+97
-79
lines changed

packet/context_processors.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,9 +62,9 @@ def get_rit_image(username: str) -> str:
6262
for addr in addresses:
6363
url = 'https://gravatar.com/avatar/' + hashlib.md5(addr.encode('utf8')).hexdigest() + '.jpg?d=404&s=250'
6464
try:
65-
gravatar = urllib.request.urlopen(url)
66-
if gravatar.getcode() == 200:
67-
return url
65+
with urllib.request.urlopen(url) as gravatar:
66+
if gravatar.getcode() == 200:
67+
return url
6868
except:
6969
continue
7070
return 'https://www.gravatar.com/avatar/freshmen?d=mp&f=y'

packet/ldap.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,11 @@
1313

1414
class MockMember:
1515

16-
def __init__(self, uid: str, groups: list = None, cn: str = None, room_number: int = None):
16+
def __init__(self,
17+
uid: str,
18+
groups: Optional[list] = None,
19+
cn: Optional[str] = None,
20+
room_number: Optional[int] = None):
1721
self.uid = uid
1822
self.groups = groups if groups else list()
1923
if room_number:
@@ -37,7 +41,7 @@ def __repr__(self) -> str:
3741

3842
class LDAPWrapper:
3943

40-
def __init__(self, cshldap: CSHLDAP = None, mock_members: list[MockMember] = None):
44+
def __init__(self, cshldap: Optional[CSHLDAP] = None, mock_members: Optional[list[MockMember]] = None):
4145
self.ldap = cshldap
4246
self.mock_members = cast(list[MockMember], mock_members)
4347
if self.ldap:

packet/mail.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import TypedDict
1+
from typing import TypedDict, List, Union, cast
22

33
from flask import render_template
44
from flask_mail import Mail, Message
@@ -15,10 +15,10 @@ class ReportForm(TypedDict):
1515

1616
def send_start_packet_mail(packet: Packet) -> None:
1717
if app.config['MAIL_PROD']:
18-
recipients = ['<' + packet.freshman.rit_username + '@rit.edu>']
18+
recipients = ['<' + str(packet.freshman.rit_username) + '@rit.edu>']
1919
msg = Message(subject='CSH Packet Starts ' + packet.start.strftime('%A, %B %-d'),
2020
sender=app.config.get('MAIL_USERNAME'),
21-
recipients=recipients)
21+
recipients=cast(List[Union[str, tuple[str, str]]], recipients))
2222

2323
template = 'mail/packet_start'
2424
msg.body = render_template(template + '.txt', packet=packet)
@@ -31,7 +31,7 @@ def send_report_mail(form_results: ReportForm, reporter: str) -> None:
3131
recipients = ['<[email protected]>']
3232
msg = Message(subject='Packet Report',
3333
sender=app.config.get('MAIL_USERNAME'),
34-
recipients=recipients)
34+
recipients=cast(List[Union[str, tuple[str, str]]], recipients))
3535

3636
person = form_results['person']
3737
report = form_results['report']

packet/routes/admin.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from typing import Dict, Any
12
from flask import render_template
23

34
from packet import app
@@ -13,7 +14,7 @@
1314
@admin_auth
1415
@before_request
1516
@log_time
16-
def admin_packets(info=None):
17+
def admin_packets(info: Dict[str, Any]) -> str:
1718
open_packets = Packet.open_packets()
1819

1920
# Pre-calculate and store the return values of did_sign(), signatures_received(), and signatures_required()
@@ -35,7 +36,7 @@ def admin_packets(info=None):
3536
@admin_auth
3637
@before_request
3738
@log_time
38-
def admin_freshmen(info=None):
39+
def admin_freshmen(info: Dict[str, Any]) -> str:
3940
all_freshmen = Freshman.get_all()
4041

4142
return render_template('admin_freshmen.html',

packet/routes/api.py

Lines changed: 39 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
"""
22
Shared API endpoints
33
"""
4-
from datetime import datetime
4+
from datetime import datetime, date
55
from json import dumps
6+
from typing import Dict, Any, Union, Tuple
67

78
from flask import session, request
89

@@ -18,15 +19,15 @@
1819

1920

2021
class POSTFreshman:
21-
def __init__(self, freshman):
22-
self.name = freshman['name'].strip()
23-
self.rit_username = freshman['rit_username'].strip()
24-
self.onfloor = freshman['onfloor'].strip() == 'TRUE'
22+
def __init__(self, freshman: Dict[str, Any]) -> None:
23+
self.name: str = freshman['name'].strip()
24+
self.rit_username: str = freshman['rit_username'].strip()
25+
self.onfloor: bool = freshman['onfloor'].strip() == 'TRUE'
2526

2627

2728
@app.route('/api/v1/freshmen', methods=['POST'])
2829
@packet_auth
29-
def sync_freshman():
30+
def sync_freshman() -> Tuple[str, int]:
3031
"""
3132
Create or update freshmen entries from a list
3233
@@ -40,19 +41,21 @@ def sync_freshman():
4041
"""
4142

4243
# Only allow evals to create new frosh
43-
username = str(session['userinfo'].get('preferred_username', ''))
44+
username: str = str(session['userinfo'].get('preferred_username', ''))
4445
if not ldap.is_evals(ldap.get_member(username)):
4546
return 'Forbidden: not Evaluations Director', 403
4647

47-
freshmen_in_post = {freshman.rit_username: freshman for freshman in map(POSTFreshman, request.json)}
48+
freshmen_in_post: Dict[str, POSTFreshman] = {
49+
freshman.rit_username: freshman for freshman in map(POSTFreshman, request.json)
50+
}
4851
sync_freshman_list(freshmen_in_post)
4952
return dumps('Done'), 200
5053

5154

5255
@app.route('/api/v1/packets', methods=['POST'])
5356
@packet_auth
5457
@log_time
55-
def create_packet():
58+
def create_packet() -> Tuple[str, int]:
5659
"""
5760
Create a new packet.
5861
@@ -69,13 +72,15 @@ def create_packet():
6972
"""
7073

7174
# Only allow evals to create new packets
72-
username = str(session['userinfo'].get('preferred_username', ''))
75+
username: str = str(session['userinfo'].get('preferred_username', ''))
7376
if not ldap.is_evals(ldap.get_member(username)):
7477
return 'Forbidden: not Evaluations Director', 403
7578

76-
base_date = datetime.strptime(request.json['start_date'], '%m/%d/%Y').date()
79+
base_date: date = datetime.strptime(request.json['start_date'], '%m/%d/%Y').date()
7780

78-
freshmen_in_post = {freshman.rit_username: freshman for freshman in map(POSTFreshman, request.json['freshmen'])}
81+
freshmen_in_post: Dict[str, POSTFreshman] = {
82+
freshman.rit_username: freshman for freshman in map(POSTFreshman, request.json['freshmen'])
83+
}
7984

8085
create_new_packets(base_date, freshmen_in_post)
8186

@@ -85,9 +90,9 @@ def create_packet():
8590
@app.route('/api/v1/sync', methods=['POST'])
8691
@packet_auth
8792
@log_time
88-
def sync_ldap():
93+
def sync_ldap() -> Tuple[str, int]:
8994
# Only allow evals to sync ldap
90-
username = str(session['userinfo'].get('preferred_username', ''))
95+
username: str = str(session['userinfo'].get('preferred_username', ''))
9196
if not ldap.is_evals(ldap.get_member(username)):
9297
return 'Forbidden: not Evaluations Director', 403
9398
sync_with_ldap()
@@ -97,14 +102,14 @@ def sync_ldap():
97102
@app.route('/api/v1/packets/<username>', methods=['GET'])
98103
@packet_auth
99104
@before_request
100-
def get_packets_by_user(username: str, info=None) -> dict:
105+
def get_packets_by_user(username: str, info: Dict[str, Any]) -> Union[Dict[int, Dict[str, Any]], Tuple[str, int]]:
101106
"""
102107
Return a dictionary of packets for a freshman by username, giving packet start and end date by packet id
103108
"""
104109

105110
if info['ritdn'] != username:
106111
return 'Forbidden - not your packet', 403
107-
frosh = Freshman.by_username(username)
112+
frosh: Freshman = Freshman.by_username(username)
108113

109114
return {packet.id: {
110115
'start': packet.start,
@@ -115,17 +120,17 @@ def get_packets_by_user(username: str, info=None) -> dict:
115120
@app.route('/api/v1/packets/<username>/newest', methods=['GET'])
116121
@packet_auth
117122
@before_request
118-
def get_newest_packet_by_user(username: str, info=None) -> dict:
123+
def get_newest_packet_by_user(username: str, info: Dict[str, Any]) -> Union[Dict[int, Dict[str, Any]], Tuple[str, int]]:
119124
"""
120125
Return a user's newest packet
121126
"""
122127

123128
if not info['is_upper'] and info['ritdn'] != username:
124129
return 'Forbidden - not your packet', 403
125130

126-
frosh = Freshman.by_username(username)
131+
frosh: Freshman = Freshman.by_username(username)
127132

128-
packet = frosh.packets[-1]
133+
packet: Packet = frosh.packets[-1]
129134

130135
return {
131136
packet.id: {
@@ -137,15 +142,15 @@ def get_newest_packet_by_user(username: str, info=None) -> dict:
137142
}
138143

139144

140-
@app.route('/api/v1/packet/<packet_id>', methods=['GET'])
145+
@app.route('/api/v1/packet/<int:packet_id>', methods=['GET'])
141146
@packet_auth
142147
@before_request
143-
def get_packet_by_id(packet_id: int, info=None) -> dict:
148+
def get_packet_by_id(packet_id: int, info: Dict[str, Any]) -> Union[Dict[str, Dict[str, Any]], Tuple[str, int]]:
144149
"""
145150
Return the scores of the packet in question
146151
"""
147152

148-
packet = Packet.by_id(packet_id)
153+
packet: Packet = Packet.by_id(packet_id)
149154

150155
if not info['is_upper'] and info['ritdn'] != packet.freshman.rit_username:
151156
return 'Forbidden - not your packet', 403
@@ -156,14 +161,14 @@ def get_packet_by_id(packet_id: int, info=None) -> dict:
156161
}
157162

158163

159-
@app.route('/api/v1/sign/<packet_id>/', methods=['POST'])
164+
@app.route('/api/v1/sign/<int:packet_id>/', methods=['POST'])
160165
@packet_auth
161166
@before_request
162-
def sign(packet_id, info):
163-
packet = Packet.by_id(packet_id)
167+
def sign(packet_id: int, info: Dict[str, Any]) -> str:
168+
packet: Packet = Packet.by_id(packet_id)
164169

165170
if packet is not None and packet.is_open():
166-
was_100 = packet.is_100()
171+
was_100: bool = packet.is_100()
167172
if app.config['REALM'] == 'csh':
168173
# Check if the CSHer is an upperclassman and if so, sign that row
169174
for sig in filter(lambda sig: sig.member == info['uid'], packet.upper_signatures):
@@ -189,8 +194,9 @@ def sign(packet_id, info):
189194
@app.route('/api/v1/subscribe/', methods=['POST'])
190195
@packet_auth
191196
@before_request
192-
def subscribe(info):
197+
def subscribe(info: Dict[str, Any]) -> str:
193198
data = request.form
199+
subscription: NotificationSubscription
194200
if app.config['REALM'] == 'csh':
195201
subscription = NotificationSubscription(token=data['token'], member=info['uid'])
196202
else:
@@ -203,16 +209,16 @@ def subscribe(info):
203209
@app.route('/api/v1/report/', methods=['POST'])
204210
@packet_auth
205211
@before_request
206-
def report(info):
212+
def report(info: Dict[str, Any]) -> str:
207213
form_results = request.form
208214
send_report_mail(form_results, get_rit_name(info['uid']))
209215
return 'Success: ' + get_rit_name(info['uid']) + ' sent a report'
210216

211217

212-
@app.route('/api/v1/stats/packet/<packet_id>')
218+
@app.route('/api/v1/stats/packet/<int:packet_id>')
213219
@packet_auth
214220
@before_request
215-
def packet_stats(packet_id, info=None):
221+
def packet_stats(packet_id: int, info: Dict[str, Any]) -> Union[stats.PacketStats, Tuple[str, int]]:
216222
if not info['is_upper'] and info['ritdn'] != Packet.by_id(packet_id).freshman.rit_username:
217223
return 'Forbidden - not your packet', 403
218224
return stats.packet_stats(packet_id)
@@ -221,20 +227,20 @@ def packet_stats(packet_id, info=None):
221227
@app.route('/api/v1/stats/upperclassman/<uid>')
222228
@packet_auth
223229
@before_request
224-
def upperclassman_stats(uid, info=None):
230+
def upperclassman_stats(uid: str, info: Dict[str, Any]) -> Union[stats.UpperStats, Tuple[str, int]]:
225231
if not info['is_upper']:
226232
return 'Forbidden', 403
227233

228234
return stats.upperclassman_stats(uid)
229235

230236

231237
@app.route('/readiness')
232-
def readiness() -> tuple[str, int]:
238+
def readiness() -> Tuple[str, int]:
233239
"""A basic healthcheck. Returns 200 to indicate flask is running"""
234240
return 'ready', 200
235241

236242

237-
def commit_sig(packet, was_100, uid):
243+
def commit_sig(packet: Packet, was_100: bool, uid: str) -> str:
238244
packet_signed_notification(packet, uid)
239245
db.session.commit()
240246
if not was_100 and packet.is_100():

packet/routes/freshmen.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
Routes available to freshmen only
33
"""
44

5-
from flask import redirect, url_for
5+
from typing import Any
6+
from flask import Response, redirect, url_for
67

78
from packet import app
89
from packet.models import Packet
@@ -12,8 +13,11 @@
1213
@app.route('/')
1314
@packet_auth
1415
@before_request
15-
def index(info=None):
16-
most_recent_packet = Packet.query.filter_by(freshman_username=info['uid']).order_by(Packet.id.desc()).first()
16+
def index(info: dict[str, Any]) -> Response:
17+
most_recent_packet = (Packet.query
18+
.filter_by(freshman_username=info['uid'])
19+
.order_by(Packet.id.desc()) # type: ignore
20+
.first())
1721

1822
if most_recent_packet is not None:
1923
return redirect(url_for('freshman_packet', packet_id=most_recent_packet.id), 302)

0 commit comments

Comments
 (0)