Skip to content

Commit bdd6aed

Browse files
committed
Format the project with Ruff format.
1 parent 3f5c427 commit bdd6aed

File tree

39 files changed

+173
-176
lines changed

39 files changed

+173
-176
lines changed

code/ch3-hello-fastapi-world/main.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,7 @@
66

77
@app.get('/')
88
def index():
9-
return {
10-
'message': "Hello world"
11-
}
9+
return {'message': 'Hello world'}
1210

1311

1412
if __name__ == '__main__':

code/ch4-templates/views/home.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,10 @@ def index():
1212
'release_count': 2_234_847,
1313
'user_count': 73_874,
1414
'packages': [
15-
{'id': 'fastapi', 'summary': "A great web framework"},
16-
{'id': 'uvicorn', 'summary': "Your favorite ASGI server"},
17-
{'id': 'httpx', 'summary': "Requests for an async world"},
18-
]
15+
{'id': 'fastapi', 'summary': 'A great web framework'},
16+
{'id': 'uvicorn', 'summary': 'Your favorite ASGI server'},
17+
{'id': 'httpx', 'summary': 'Requests for an async world'},
18+
],
1919
}
2020

2121

code/ch5-viewmodels/data/package.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
class Package:
2-
3-
def __init__(self,
4-
package_name: str,
5-
summary: str,
6-
description: str,
7-
home_page: str,
8-
lic: str,
9-
author_name: str,
10-
maintainers: list = None,
11-
):
2+
def __init__(
3+
self,
4+
package_name: str,
5+
summary: str,
6+
description: str,
7+
home_page: str,
8+
lic: str,
9+
author_name: str,
10+
maintainers: list = None,
11+
):
1212
if maintainers is None:
1313
maintainers = []
1414
self.maintainers = maintainers

code/ch5-viewmodels/data/release.py

-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33

44
class Release:
5-
65
def __init__(self, version: str, created_date: datetime.datetime):
76
self.version = version
87
self.created_date = created_date

code/ch5-viewmodels/services/package_service.py

+11-7
Original file line numberDiff line numberDiff line change
@@ -15,19 +15,23 @@ def package_count() -> int:
1515

1616
def latest_packages(limit: int = 5) -> List:
1717
return [
18-
{'id': 'fastapi', 'summary': "A great web framework"},
19-
{'id': 'uvicorn', 'summary': "Your favorite ASGI server"},
20-
{'id': 'httpx', 'summary': "Requests for an async world"},
21-
][:limit]
18+
{'id': 'fastapi', 'summary': 'A great web framework'},
19+
{'id': 'uvicorn', 'summary': 'Your favorite ASGI server'},
20+
{'id': 'httpx', 'summary': 'Requests for an async world'},
21+
][:limit]
2222

2323

2424
def get_package_by_id(package_name: str) -> Optional[Package]:
2525
package = Package(
26-
package_name, "This is the summary", "Full details here!",
27-
"https://fastapi.tiangolo.com/", "MIT", "Sebastián Ramírez"
26+
package_name,
27+
'This is the summary',
28+
'Full details here!',
29+
'https://fastapi.tiangolo.com/',
30+
'MIT',
31+
'Sebastián Ramírez',
2832
)
2933
return package
3034

3135

3236
def get_latest_release_for_package(package_name: str) -> Optional[Release]:
33-
return Release("1.2.0", datetime.datetime.now())
37+
return Release('1.2.0', datetime.datetime.now())

code/ch5-viewmodels/viewmodels/packages/details_viewmodel.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ def __init__(self, package_name: str, request: Request):
1010
self.package_name = package_name
1111
self.package = package_service.get_package_by_id(package_name)
1212
self.latest_release = package_service.get_latest_release_for_package(package_name)
13-
self.latest_version = "0.0.0"
13+
self.latest_version = '0.0.0'
1414
self.is_latest = True
1515
self.maintainers = []
1616

code/ch5-viewmodels/viewmodels/shared/viewmodel.py

-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44

55

66
class ViewModelBase:
7-
87
def __init__(self, request: Request):
98
self.request: Request = request
109
self.error: Optional[str] = None

code/ch6-users-and-forms/data/package.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
class Package:
2-
3-
def __init__(self,
4-
package_name: str,
5-
summary: str,
6-
description: str,
7-
home_page: str,
8-
lic: str,
9-
author_name: str,
10-
maintainers: list = None,
11-
):
2+
def __init__(
3+
self,
4+
package_name: str,
5+
summary: str,
6+
description: str,
7+
home_page: str,
8+
lic: str,
9+
author_name: str,
10+
maintainers: list = None,
11+
):
1212
if maintainers is None:
1313
maintainers = []
1414
self.maintainers = maintainers

code/ch6-users-and-forms/data/release.py

-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33

44
class Release:
5-
65
def __init__(self, version: str, created_date: datetime.datetime):
76
self.version = version
87
self.created_date = created_date

code/ch6-users-and-forms/data/user.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,11 @@
22

33

44
class User:
5-
65
def __init__(self, name, email, hashed_password):
76
self.id = 1
87
self.name = name
98
self.email = email
109
self.hash_password = hashed_password
1110
self.created_date = None
12-
self.profile_image_url = ""
11+
self.profile_image_url = ''
1312
self.last_login: datetime.datetime = None

code/ch6-users-and-forms/infrastructure/cookie_auth.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
def set_auth(response: Response, user_id: int):
1212
hash_val = __hash_text(str(user_id))
13-
val = "{}:{}".format(user_id, hash_val)
13+
val = '{}:{}'.format(user_id, hash_val)
1414
response.set_cookie(auth_cookie_name, val, secure=False, httponly=True, samesite='Lax')
1515

1616

@@ -32,7 +32,7 @@ def get_user_id_via_auth_cookie(request: Request) -> Optional[int]:
3232
hash_val = parts[1]
3333
hash_val_check = __hash_text(user_id)
3434
if hash_val != hash_val_check:
35-
print("Warning: Hash mismatch, invalid cookie value")
35+
print('Warning: Hash mismatch, invalid cookie value')
3636
return None
3737

3838
return try_int(user_id)

code/ch6-users-and-forms/services/package_service.py

+11-7
Original file line numberDiff line numberDiff line change
@@ -15,19 +15,23 @@ def package_count() -> int:
1515

1616
def latest_packages(limit: int = 5) -> List:
1717
return [
18-
{'id': 'fastapi', 'summary': "A great web framework"},
19-
{'id': 'uvicorn', 'summary': "Your favorite ASGI server"},
20-
{'id': 'httpx', 'summary': "Requests for an async world"},
21-
][:limit]
18+
{'id': 'fastapi', 'summary': 'A great web framework'},
19+
{'id': 'uvicorn', 'summary': 'Your favorite ASGI server'},
20+
{'id': 'httpx', 'summary': 'Requests for an async world'},
21+
][:limit]
2222

2323

2424
def get_package_by_id(package_name: str) -> Optional[Package]:
2525
package = Package(
26-
package_name, "This is the summary", "Full details here!",
27-
"https://fastapi.tiangolo.com/", "MIT", "Sebastián Ramírez"
26+
package_name,
27+
'This is the summary',
28+
'Full details here!',
29+
'https://fastapi.tiangolo.com/',
30+
'MIT',
31+
'Sebastián Ramírez',
2832
)
2933
return package
3034

3135

3236
def get_latest_release_for_package(package_name: str) -> Optional[Release]:
33-
return Release("1.2.0", datetime.datetime.now())
37+
return Release('1.2.0', datetime.datetime.now())

code/ch6-users-and-forms/services/user_service.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,6 @@ def create_account(name: str, email: str, password: str) -> User:
1313

1414
def login_user(email: str, password: str) -> Optional[User]:
1515
if password == 'abc':
16-
return User("test user", email, 'abc')
16+
return User('test user', email, 'abc')
1717

1818
return None

code/ch6-users-and-forms/viewmodels/account/register_viewmodel.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@ async def load(self):
1919
self.email = form.get('email')
2020

2121
if not self.name or not self.name.strip():
22-
self.error = "Your name is required."
22+
self.error = 'Your name is required.'
2323
elif not self.email or not self.email.strip():
24-
self.error = "Your email is required."
24+
self.error = 'Your email is required.'
2525
elif not self.password or len(self.password) < 5:
26-
self.error = "Your password is required and must be at 5 characters."
26+
self.error = 'Your password is required and must be at 5 characters.'

code/ch6-users-and-forms/viewmodels/packages/details_viewmodel.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ def __init__(self, package_name: str, request: Request):
1010
self.package_name = package_name
1111
self.package = package_service.get_package_by_id(package_name)
1212
self.latest_release = package_service.get_latest_release_for_package(package_name)
13-
self.latest_version = "0.0.0"
13+
self.latest_version = '0.0.0'
1414
self.is_latest = True
1515
self.maintainers = []
1616

code/ch6-users-and-forms/viewmodels/shared/viewmodel.py

-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55

66

77
class ViewModelBase:
8-
98
def __init__(self, request: Request):
109
self.request: Request = request
1110
self.error: Optional[str] = None

code/ch6-users-and-forms/views/account.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ async def register(request: Request):
4646

4747
# ################### LOGIN #################################
4848

49+
4950
@router.get('/account/login')
5051
@template(template_file='account/login.pt')
5152
def login_get(request: Request):
@@ -64,7 +65,7 @@ async def login_post(request: Request):
6465

6566
user = user_service.login_user(vm.email, vm.password)
6667
if not user:
67-
vm.error = "The account does not exist or the password is wrong."
68+
vm.error = 'The account does not exist or the password is wrong.'
6869
return vm.to_dict()
6970

7071
resp = fastapi.responses.RedirectResponse('/account', status_code=status.HTTP_302_FOUND)

code/ch7-databases/bin/load_data.py

+21-29
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@
88
import progressbar
99
from dateutil.parser import parse
1010

11-
sys.path.insert(0, os.path.abspath(os.path.join(
12-
os.path.dirname(__file__), "..")))
11+
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
1312

1413
import data.db_session as db_session
1514
from data.package import Package
@@ -35,14 +34,14 @@ def main():
3534
def do_summary():
3635
session = db_session.create_session()
3736

38-
print("Final numbers:")
39-
print("Users: {:,}".format(session.query(User).count()))
40-
print("Packages: {:,}".format(session.query(Package).count()))
41-
print("Releases: {:,}".format(session.query(Release).count()))
37+
print('Final numbers:')
38+
print('Users: {:,}'.format(session.query(User).count()))
39+
print('Packages: {:,}'.format(session.query(Package).count()))
40+
print('Releases: {:,}'.format(session.query(Release).count()))
4241

4342

4443
def do_user_import(user_lookup: Dict[str, str]) -> Dict[str, User]:
45-
print("Importing users ... ", flush=True)
44+
print('Importing users ... ', flush=True)
4645
with progressbar.ProgressBar(max_value=len(user_lookup)) as bar:
4746
for idx, (email, name) in enumerate(user_lookup.items()):
4847
session = db_session.create_session()
@@ -66,29 +65,29 @@ def do_user_import(user_lookup: Dict[str, str]) -> Dict[str, User]:
6665

6766
def do_import_packages(file_data: List[dict], user_lookup: Dict[str, User]):
6867
errored_packages = []
69-
print("Importing packages and releases ... ", flush=True)
68+
print('Importing packages and releases ... ', flush=True)
7069
with progressbar.ProgressBar(max_value=len(file_data)) as bar:
7170
for idx, p in enumerate(file_data):
7271
try:
7372
load_package(p, user_lookup)
7473
bar.update(idx)
7574
except Exception as x:
76-
errored_packages.append((p, " *** Errored out for package {}, {}".format(p.get('package_name'), x)))
75+
errored_packages.append((p, ' *** Errored out for package {}, {}'.format(p.get('package_name'), x)))
7776
raise
7877
sys.stderr.flush()
7978
sys.stdout.flush()
8079
print()
81-
print("Completed packages with {} errors.".format(len(errored_packages)))
82-
for (p, txt) in errored_packages:
80+
print('Completed packages with {} errors.'.format(len(errored_packages)))
81+
for p, txt in errored_packages:
8382
print(txt)
8483

8584

8685
def do_load_files() -> List[dict]:
8786
data_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../data/pypi-top-100'))
88-
print("Loading files from {}".format(data_path))
87+
print('Loading files from {}'.format(data_path))
8988
files = get_file_names(data_path)
90-
print("Found {:,} files, loading ...".format(len(files)), flush=True)
91-
time.sleep(.1)
89+
print('Found {:,} files, loading ...'.format(len(files)), flush=True)
90+
time.sleep(0.1)
9291

9392
file_data = []
9493
with progressbar.ProgressBar(max_value=len(files)) as bar:
@@ -103,7 +102,7 @@ def do_load_files() -> List[dict]:
103102

104103

105104
def find_users(data: List[dict]) -> dict:
106-
print("Discovering users...", flush=True)
105+
print('Discovering users...', flush=True)
107106
found_users = {}
108107

109108
with progressbar.ProgressBar(max_value=len(data)) as bar:
@@ -116,7 +115,7 @@ def find_users(data: List[dict]) -> dict:
116115
sys.stderr.flush()
117116
sys.stdout.flush()
118117
print()
119-
print("Discovered {:,} users".format(len(found_users)))
118+
print('Discovered {:,} users'.format(len(found_users)))
120119
print()
121120

122121
return found_users
@@ -147,7 +146,7 @@ def load_file_data(filename: str) -> dict:
147146
with open(filename, 'r', encoding='utf-8') as fin:
148147
data = json.load(fin)
149148
except Exception as x:
150-
print("ERROR in file: {}, details: {}".format(filename, x), flush=True)
149+
print('ERROR in file: {}, details: {}'.format(filename, x), flush=True)
151150
raise
152151

153152
return data
@@ -165,7 +164,7 @@ def load_package(data: dict, user_lookup: Dict[str, User]):
165164
p.author = info.get('author')
166165
p.author_email = info.get('author_email')
167166

168-
releases = build_releases(p.id, data.get("releases", {}))
167+
releases = build_releases(p.id, data.get('releases', {}))
169168

170169
if releases:
171170
p.created_date = releases[0].created_date
@@ -206,18 +205,13 @@ def detect_license(license_text: str) -> Optional[str]:
206205
license_text = license_text.strip()
207206

208207
if len(license_text) > 100 or '\n' in license_text:
209-
return "CUSTOM"
208+
return 'CUSTOM'
210209

211-
license_text = license_text \
212-
.replace('Software License', '') \
213-
.replace('License', '')
210+
license_text = license_text.replace('Software License', '').replace('License', '')
214211

215212
if '::' in license_text:
216213
# E.g. 'License :: OSI Approved :: Apache Software License'
217-
return license_text \
218-
.split(':')[-1] \
219-
.replace(' ', ' ') \
220-
.strip()
214+
return license_text.split(':')[-1].replace(' ', ' ').strip()
221215

222216
return license_text.strip()
223217

@@ -280,9 +274,7 @@ def get_file_names(data_path: str) -> List[str]:
280274
files = []
281275
for f in os.listdir(data_path):
282276
if f.endswith('.json'):
283-
files.append(
284-
os.path.abspath(os.path.join(data_path, f))
285-
)
277+
files.append(os.path.abspath(os.path.join(data_path, f)))
286278

287279
files.sort()
288280
return files

0 commit comments

Comments
 (0)