@@ -193,6 +193,7 @@ and the risk of command injection is significantly reduced.
193
193
.. code :: python
194
194
195
195
import subprocess
196
+
196
197
user_input = " malicious_command; rm -rf /" # User input that could be malicious
197
198
subprocess.run(f " echo { user_input} " , shell = True ) # Vulnerable to command injection
198
199
@@ -201,6 +202,7 @@ and the risk of command injection is significantly reduced.
201
202
.. code :: python
202
203
203
204
import subprocess
205
+
204
206
user_input = " malicious_command; rm -rf /" # User input that could be malicious
205
207
# Removing shell=True and using a list
206
208
subprocess.run([" echo" , user_input]) # User input is not executed as a shell command
@@ -219,21 +221,21 @@ exceptions explicitly and log or raise them as needed.
219
221
.. code :: python
220
222
221
223
try :
222
- risky_operation() # Some code that might raise an exception
224
+ risky_operation() # Some code that might raise an exception
223
225
except :
224
- continue # This will silently ignore all the exceptions and continue execution
226
+ continue # This will silently ignore all the exceptions and continue execution
225
227
226
228
.. tab-item :: `try except continue` with explicit exception handling
227
229
228
230
.. code :: python
229
231
230
232
try :
231
- risky_operation()
233
+ risky_operation()
232
234
except SpecificException as e:
233
- continue # Handle specific exceptions and continue
235
+ continue # Handle specific exceptions and continue
234
236
except AnotherSpecificException as e:
235
- log_error(e) # Log the error for debugging
236
- raise # Raise the exception to notify the caller
237
+ log_error(e) # Log the error for debugging
238
+ raise # Raise the exception to notify the caller
237
239
238
240
239
241
**requests.get() without timeout **
@@ -249,13 +251,15 @@ prevent this issue.
249
251
.. code :: python
250
252
251
253
import requests
254
+
252
255
response = requests.get(" https://example.com" ) # No timeout specified
253
256
254
257
.. tab-item :: `requests.get()` with timeout
255
258
256
259
.. code :: python
257
260
258
261
import requests
262
+
259
263
response = requests.get(" https://example.com" , timeout = 5 ) # Timeout set to 5 seconds
260
264
261
265
@@ -272,6 +276,7 @@ provides a secure way to generate random numbers.
272
276
.. code :: python
273
277
274
278
import random
279
+
275
280
random_number = random.randint(1 , 100 ) # Predictable random number generation
276
281
random_letter = random.choice([" a" , " b" , " c" ]) # Predictable choice from a list
277
282
@@ -280,5 +285,6 @@ provides a secure way to generate random numbers.
280
285
.. code :: python
281
286
282
287
import secrets
288
+
283
289
secure_random_number = secrets.randbelow(100 ) # Secure random number generation
284
290
secure_random_letter = secrets.choice([" a" , " b" , " c" ]) # Secure choice from a list
0 commit comments