Skip to content

Commit cabe864

Browse files
committed
Convert print to logging
1 parent 1d66e67 commit cabe864

File tree

8 files changed

+30
-39
lines changed

8 files changed

+30
-39
lines changed

src/common/Authentication.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,10 @@ def generate_token(user_id):
3333
}
3434
return jwt.encode(payload, current_app.config["JWT_SECRET_KEY"], "HS512")
3535
except Exception as e:
36-
print("generate_token() exception!")
37-
print(type(e)) # the exception instance
38-
print(e.args) # arguments stored in .args
39-
print(e) # __str__ allows args to be printed directly,
36+
logging.exception(f"generate_token() exception! {e}")
37+
#print(type(e)) # the exception instance
38+
#print(e.args) # arguments stored in .args
39+
#print(e) # __str__ allows args to be printed directly,
4040
# but may be overridden in exception subclasses
4141
return Response(mimetype="application/json", response=json.dumps({"error": "Token generation error!"}), status=400)
4242
else:
@@ -57,7 +57,7 @@ def decode_token(token):
5757
return result
5858
except jwt.InvalidAudienceError as audError:
5959
result["error"] = {"message": "Invalid Audience! Please login again!"}
60-
print("InvalidAudienceError!")
60+
logging.exception(f"InvalidAudienceError! {audError}")
6161
except jwt.InvalidTokenError as invalid:
6262
result["error"] = {"message": "Invalid Token! Please login again!"}
6363
return result

src/controllers/AuthenticationController.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,7 @@ async def login():
5454
except ValidationError as err:
5555
errors = err.messages
5656
valid_data = err.valid_data
57-
logging.error(f"[Auth] login() error! {errors}")
58-
print(f"login() error! {errors}")
57+
logging.exception(f"[Auth] login() exception! {errors}")
5958
return await render_template("login.html", title="Welcome to Python Flask RESTful API", error=errors)
6059
return await render_template("login.html", title="Welcome to Python Flask RESTful API")
6160

@@ -105,7 +104,6 @@ async def logout():
105104
"""
106105
User Logout
107106
"""
108-
print(f"logout()")
109107
logging.info(f"[Auth] User logged out")
110108
session["url"] = None
111109
session["user"] = None

src/controllers/AuthorController.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ async def create():
5454
"email": form["email"],
5555
"phone": form["phone"],
5656
}
57-
print(f"author.create() request data: {req_data}")
57+
logging.debug(f"author.create() request data: {req_data}")
5858
data = author_schema.load(req_data)
5959
if not data:
6060
await flash(f"Invalid input!", "danger")
@@ -71,7 +71,7 @@ async def create():
7171
except ValidationError as err:
7272
errors = err.messages
7373
valid_data = err.valid_data
74-
logging.error(f"User {user.email} failed to creat author! Exception: {errors}")
74+
logging.exception(f"User {user.email} failed to creat author! Exception: {errors}")
7575
await flash(f"Failed to create author! {err.messages}", "danger")
7676
return redirect(url_for("author.create"))
7777
return await render_template("author_create.html", title="Welcome to Python Flask RESTful API")
@@ -93,7 +93,7 @@ async def get_by_firstname(firstname):
9393
"""
9494
Get Author by firstname
9595
"""
96-
print(f"get_author_by_author_firstname: {firstname}")
96+
logging.debug(f"get_author_by_author_firstname: {firstname}")
9797
return custom_response(author_schema.dump(AuthorModel.get_author_by_firstname(firstname)), 200)
9898

9999
@author_api.route("/lastname/<string:lastname>")
@@ -143,7 +143,7 @@ async def update(id):
143143
except ValidationError as err:
144144
errors = err.messages
145145
valid_data = err.valid_data
146-
logging.error(f"User {user.email} failed to update author {id}! Exception: {errors}")
146+
logging.exception(f"User {user.email} failed to update author {id}! Exception: {errors}")
147147
await flash(f"Failed to update author {id}! Exception: {errors}", "danger")
148148
return redirect(url_for("author.index"))
149149

@@ -165,7 +165,6 @@ async def delete(id):
165165
except ValidationError as err:
166166
errors = err.messages
167167
valid_data = err.valid_data
168-
print(f"Failed to delete author {id} error! {errors}")
169-
logging.error(f"User {user.email} failed to delete author {id}! Exception: {errors}")
168+
logging.exception(f"User {user.email} failed to delete author {id}! Exception: {errors}")
170169
await flash(f"Failed to delete author {id}! Exception: {errors}", "danger")
171170
return redirect(url_for("user.index"))

src/controllers/BookController.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ async def create():
7575
if not author:
7676
await flash(f"Invalid author!", "danger")
7777
return redirect(url_for("book.create"))
78-
print(f"book.create(): {json.dumps(data)}")
78+
logging.debug(f"book.create(): {json.dumps(data)}")
7979
book = BookModel(data)
8080
book.save()
8181
await flash(f"Book {book.title} created successfully!", "success")
@@ -84,9 +84,8 @@ async def create():
8484
except ValidationError as err:
8585
errors = err.messages
8686
valid_data = err.valid_data
87-
print(f"create() error! {errors}")
8887
await flash(f"Failed to create book! {err.messages}", "danger")
89-
logging.error(f"User {user.email} failed to create book! Exception: {errors}")
88+
logging.exception(f"User {user.email} failed to create book! Exception: {errors}")
9089
return redirect(url_for("book.create"))
9190
authors = author_schema.dump(AuthorModel.get_authors(), many=True)
9291
return await render_template("book_create.html", title="Welcome to Python Flask RESTful API", authors = authors)
@@ -191,7 +190,7 @@ async def update(id):
191190
except ValidationError as err:
192191
errors = err.messages
193192
valid_data = err.valid_data
194-
logging.error(f"User {user.email} failed to update book {id}! Exception: {errors}")
193+
logging.exception(f"User {user.email} failed to update book {id}! Exception: {errors}")
195194
await flash(f"Failed to update book {id}! Exception: {errors}", "danger")
196195
return redirect(url_for("book.index"))
197196

@@ -213,6 +212,6 @@ async def delete(id):
213212
except ValidationError as err:
214213
errors = err.messages
215214
valid_data = err.valid_data
216-
logging.error(f"User {user.email} failed to delete book {id}! Exception: {errors}")
215+
logging.exception(f"User {user.email} failed to delete book {id}! Exception: {errors}")
217216
await flash(f"Failed to delete book {id}! Exception: {errors}", "danger")
218217
return redirect(url_for("book.index"))

src/controllers/FibonacciController.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import jsonpickle
1+
import jsonpickle, logging
22
from quart import request, session, Blueprint, flash, render_template, session
33
from quart.utils import run_sync
44
from datetime import datetime, timezone
@@ -24,19 +24,17 @@ async def fibonacci():
2424
if data["error"]:
2525
return await render_template("login.html", title="Welcome to Python Flask RESTful API", error=data["error"])
2626
user_id = data["data"]["user_id"]
27-
print(f"User: {user_id}")
27+
logging.debug(f"User: {user_id}")
2828
user = UserModel.get_user(user_id)
2929
if not user:
3030
return await render_template("login.html", title="Welcome to Python Flask RESTful API", error="Invalid user!")
31-
print("fibonacci()")
3231
if request.method == "POST":
33-
print("fibonacci() POST")
3432
data = await request.get_data()
3533
params = parse_qs(data.decode('utf-8'))
36-
print(f"data: {data}, params: {params}")
34+
logging.debug(f"data: {data}, params: {params}")
3735
if params['n'] and params["n"][0].strip() and params["n"][0].strip().isdigit():
3836
n = int(params["n"][0].strip())
39-
print(f"fibonacci(): {n}")
37+
logging.debug(f"fibonacci(): {n}")
4038
try:
4139
fibonacci = f"Hello {('there' if not user else user.firstname)}, fibonacci({n}): {await run_sync(fib)(n)}"
4240
except (Exception) as error:
@@ -47,7 +45,7 @@ async def fibonacci():
4745
#error = custom_response({"error": "Please provide an 'N' for the fibonacci number!"}, 400)
4846
await flash("Please provide a numeric value 'N' for the fibonacci number!", "danger")
4947
else:
50-
print(f"Invalid request method: {request.method}!")
48+
logging.error(f"Invalid request method: {request.method}!")
5149
return await render_template("fibonacci.html", title="Welcome to Python Flask Fibonacci calculator", fibonacci=fibonacci)
5250

5351
def fib(n):

src/controllers/HomeController.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1+
import re, jsonpickle, logging
12
from quart import Blueprint, render_template, session
23
from datetime import datetime, timezone
34
from ..common.Authentication import Authentication
45
from ..models.UserModel import UserModel
5-
import re, jsonpickle
66
home_api = Blueprint("home", __name__)
77
@home_api.context_processor
88
def inject_now():
@@ -11,7 +11,6 @@ def inject_now():
1111
@home_api.route("/")
1212
@home_api.route("/index")
1313
async def index():
14-
#print("homeController hello")
1514
greeting = None
1615
now = datetime.now()
1716
# https://www.programiz.com/python-programming/datetime/strftime
@@ -31,13 +30,12 @@ async def index():
3130
if data["error"]:
3231
return await render_template("login.html", title="Welcome to Python RESTful API", error=data["error"])
3332
user_id = data["data"]["user_id"]
34-
print(f"User: {user_id}")
33+
logging.debug(f"User: {user_id}")
3534
user = UserModel.get_user(user_id)
3635
if not user:
3736
return await render_template("login.html", title="Welcome to Python RESTful API", error="Invalid user!")
3837
try:
39-
print("Get user name...")
40-
print(f"Firstname: {user.firstname}, Lastname: {user.lastname}")
38+
logging.debug(f"Firstname: {user.firstname}, Lastname: {user.lastname}")
4139
name = user.firstname + ", " + user.lastname
4240
# Filter the name argument to letters only using regular expressions. URL arguments
4341
# can contain arbitrary text, so we restrict to safe characters only.

src/controllers/UserController.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ async def create():
5151
"email": form["email"],
5252
"password": form["password"]
5353
}
54-
print(f"create() request data: {req_data}")
54+
logging.debug(f"create() request data: {req_data}")
5555
data = user_schema.load(req_data)
5656
# Check if user already exists in the database
5757
if not data:
@@ -67,14 +67,14 @@ async def create():
6767
#print(f"create() user id: {ser_data.get('id')}")
6868
token = Authentication.generate_token(ser_data.get("id"))
6969
session['user'] = jsonpickle.encode(user)
70-
print(f"session['user']: {session['user']}")
70+
logging.debug(f"session['user']: {session['user']}")
7171
#print(f"create() token: {token}")
7272
await flash(f"User created user id: {user.id}, email: {user.email} successfully!", "success")
7373
return redirect(url_for("user.index"))
7474
except ValidationError as err:
7575
errors = err.messages
7676
valid_data = err.valid_data
77-
print(f"create() error! {errors}")
77+
logging.exception(f"create() exception! {errors}")
7878
await flash(f"Failed to create user! {err.messages}", "danger")
7979
return redirect(url_for("user.create"))
8080
return await render_template("user_create.html", title="Welcome to Python Flask RESTful API")
@@ -92,7 +92,7 @@ async def get_user(id):
9292
"""
9393
user = UserModel.get_user(id)
9494
if not user:
95-
print(f"User id: {id} not found!")
95+
logging.warning(f"User id: {id} not found!")
9696
return custom_response({"error": f"User {id} not found!"}, 400)
9797
return custom_response(user_schema.dump(user), 200)
9898

@@ -119,7 +119,7 @@ async def update(id):
119119
except ValidationError as err:
120120
errors = err.messages
121121
valid_data = err.valid_data
122-
logging.error(f"Failed to update user {id}! Exception: {errors}")
122+
logging.exception(f"Failed to update user {id}! Exception: {errors}")
123123
await flash(f"Failed to update user {id}! Exception: {errors}!", "danger")
124124
return redirect(url_for("user.index"))
125125

@@ -141,7 +141,6 @@ async def delete(id):
141141
except ValidationError as err:
142142
errors = err.messages
143143
valid_data = err.valid_data
144-
print(f"create() error! {errors}")
145-
logging.error(f"User {user.email} failed to delete user {id}! Exception: {errors}")
144+
logging.exception(f"User {user.email} failed to delete user {id}! Exception: {errors}")
146145
await flash(f"Failed to delete user {id}! Exception: {errors}", "danger")
147146
return redirect(url_for("user.index"))

src/main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,5 +80,5 @@ def readiness():
8080

8181
app = create_app()
8282

83-
print(f"Running app...")
83+
logging.info(f"Running app...")
8484
#asyncio.run(serve(app, config), debug=True)

0 commit comments

Comments
 (0)