Skip to content

Commit 951f11e

Browse files
committed
PR feedback, more error-checking
1 parent a4f2dfa commit 951f11e

File tree

3 files changed

+54
-33
lines changed

3 files changed

+54
-33
lines changed

src/cs50/flask.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
try:
2020
import flask.logging
2121
flask.logging.default_handler.formatter.formatException = lambda exc_info: formatException(*exc_info)
22-
except:
22+
except Exception:
2323
pass
2424

2525
# Enable logging when Flask is in use,
@@ -28,21 +28,19 @@
2828
try:
2929
import flask
3030
from .sql import SQL
31+
except ImportError:
32+
pass
33+
else:
3134
_before = SQL.execute
3235
def _after(*args, **kwargs):
3336
disabled = logging.getLogger("cs50").disabled
3437
if flask.current_app:
3538
logging.getLogger("cs50").disabled = False
3639
try:
37-
ret = _before(*args, **kwargs)
38-
logging.getLogger("cs50").disabled = disabled
39-
return ret
40-
except:
40+
return _before(*args, **kwargs)
41+
finally:
4142
logging.getLogger("cs50").disabled = disabled
42-
raise
4343
SQL.execute = _after
44-
except:
45-
pass
4644

4745
# Add support for Cloud9 proxy so that flask.redirect doesn't redirect from HTTPS to HTTP
4846
# http://stackoverflow.com/a/23504684/5156190
@@ -58,6 +56,5 @@ def _after(*args, **kwargs):
5856
except:
5957
pass
6058

61-
except Exception as e:
62-
print(e)
59+
except Exception:
6360
pass

src/cs50/sql.py

Lines changed: 45 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -100,33 +100,54 @@ def execute(self, sql, *args, **kwargs):
100100
# Determine paramstyle, name
101101
_paramstyle, name = _parse_placeholder(token)
102102

103-
# Ensure paramstyle is consistent
104-
if paramstyle is not None and _paramstyle != paramstyle:
105-
raise RuntimeError("inconsistent paramstyle")
106-
107103
# Remember paramstyle
108-
if paramstyle is None:
104+
if not paramstyle:
109105
paramstyle = _paramstyle
110106

107+
# Ensure paramstyle is consistent
108+
elif _paramstyle != paramstyle:
109+
raise RuntimeError("inconsistent paramstyle")
110+
111111
# Remember placeholder's index, name
112112
placeholders[index] = name
113113

114-
# In case user passes args in list or tuple
115-
if len(args) == 1 and (isinstance(args[0], list) or isinstance(args[0], tuple)) and len(placeholders) != 1:
116-
args = args[0]
114+
# If more placeholders than arguments
115+
if len(args) == 1 and len(placeholders) > 1:
116+
117+
# If user passed args as list or tuple, explode values into args
118+
if isinstance(args[0], (list, tuple)):
119+
args = args[0]
120+
121+
# If user passed kwargs as dict, migrate values from args to kwargs
122+
elif len(kwargs) == 0 and isinstance(args[0], dict):
123+
kwargs = args[0]
124+
args = []
125+
126+
# If no placeholders
127+
if not paramstyle:
128+
129+
# Error-check like qmark if args
130+
if args:
131+
paramstyle = "qmark"
132+
133+
# Error-check like named if kwargs
134+
elif kwargs:
135+
paramstyle = "named"
117136

118-
# In case user passes kwargs in dict
119-
if len(args) == 1 and len(kwargs) == 0 and isinstance(args[0], dict) and len(placeholders) != 1:
120-
kwargs = args[0]
137+
# In case of errors
138+
_placeholders = ", ".join([str(tokens[index]) for index in placeholders])
139+
_args = ", ".join([str(self._escape(arg)) for arg in args])
140+
#_kwargs = ", ".join([str(self._escape(arg)) for arg in args])
121141

122142
# qmark
123143
if paramstyle == "qmark":
124144

125145
# Validate number of placeholders
126-
if len(placeholders) < len(args):
127-
raise RuntimeError("too few placeholders")
128-
elif len(placeholders) > len(args):
129-
raise RuntimeError("too many placeholders")
146+
if len(placeholders) != len(args):
147+
if len(placeholders) < len(args):
148+
raise RuntimeError("fewer placeholders ({}) than values ({})".format(_placeholders, _args))
149+
else:
150+
raise RuntimeError("more placeholders ({}) than values ({})".format(_placeholders, _args))
130151

131152
# Escape values
132153
for i, index in enumerate(placeholders.keys()):
@@ -138,8 +159,8 @@ def execute(self, sql, *args, **kwargs):
138159
# Escape values
139160
for index, name in placeholders.items():
140161
i = int(name) - 1
141-
if i < 0 or i >= len(args):
142-
raise RuntimeError("placeholder out of range")
162+
if i >= len(args):
163+
raise RuntimeError("placeholder (:{}) greater than number of values ({})".format(name, _args))
143164
tokens[index] = self._escape(args[i])
144165

145166
# named
@@ -148,17 +169,18 @@ def execute(self, sql, *args, **kwargs):
148169
# Escape values
149170
for index, name in placeholders.items():
150171
if name not in kwargs:
151-
raise RuntimeError("missing value for placeholder")
172+
raise RuntimeError("missing value for placeholder (:{})".format(name))
152173
tokens[index] = self._escape(kwargs[name])
153174

154175
# format
155176
elif paramstyle == "format":
156177

157178
# Validate number of placeholders
158-
if len(placeholders) < len(args):
159-
raise RuntimeError("too few placeholders")
160-
elif len(placeholders) > len(args):
161-
raise RuntimeError("too many placeholders")
179+
if len(placeholders) != len(args):
180+
if len(placeholders) < len(args):
181+
raise RuntimeError("fewer placeholders ({}) than values ({})".format(_placeholders, _args))
182+
else:
183+
raise RuntimeError("more placeholders ({}) than values ({})".format(_placeholders, _args))
162184

163185
# Escape values
164186
for i, index in enumerate(placeholders.keys()):
@@ -170,7 +192,7 @@ def execute(self, sql, *args, **kwargs):
170192
# Escape values
171193
for index, name in placeholders.items():
172194
if name not in kwargs:
173-
raise RuntimeError("missing value for placeholder")
195+
raise RuntimeError("missing value for placeholder (:{})".format(name))
174196
tokens[index] = self._escape(kwargs[name])
175197

176198
# Join tokens into statement

tests/sqlite.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
db.execute("SELECT * FROM Employee WHERE FirstName IN (?)", ("Andrew",))
1818
db.execute("SELECT * FROM Employee WHERE FirstName IN (?)", ["Andrew", "Nancy"])
1919
db.execute("SELECT * FROM Employee WHERE FirstName IN (?)", ("Andrew", "Nancy"))
20+
db.execute("SELECT * FROM Employee WHERE FirstName IN (?)", [])
21+
db.execute("SELECT * FROM Employee WHERE FirstName IN (?)", ())
2022

2123
db.execute("SELECT * FROM Employee WHERE FirstName = ? AND LastName = ?", "Andrew", "Adams")
2224
db.execute("SELECT * FROM Employee WHERE FirstName = ? AND LastName = ?", ["Andrew", "Adams"])

0 commit comments

Comments
 (0)