0
0
Flaskframework~10 mins

Why file operations matter in web apps in Flask - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to open a file for reading in a Flask app.

Flask
with open('data.txt', '[1]') as file:
    content = file.read()
Drag options to blanks, or click blank then click option'
Aa
Bw
Cr
Dx
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' which opens the file for writing and erases content.
Using 'a' which opens the file for appending.
2fill in blank
medium

Complete the code to save uploaded file content in a Flask route.

Flask
file = request.files['file']
file.save('[1]')
Drag options to blanks, or click blank then click option'
Afile.filename
B'uploads/' + file.filename
C'/tmp/'
D'static/'
Attempts:
3 left
💡 Hint
Common Mistakes
Saving directly as file.filename without a folder may cause permission issues.
Saving to 'static/' is not recommended for uploads.
3fill in blank
hard

Fix the error in the code to read a file safely in Flask.

Flask
try:
    with open('[1]', 'r') as f:
        data = f.read()
except FileNotFoundError:
    data = ''
Drag options to blanks, or click blank then click option'
Auploads/data.txt
Bdata.txt
C/uploads/data.txt
Dstatic/data.txt
Attempts:
3 left
💡 Hint
Common Mistakes
Using just 'data.txt' without folder causes FileNotFoundError.
Using absolute paths like '/uploads/data.txt' may not work on all systems.
4fill in blank
hard

Fill both blanks to check if a file exists before reading it in Flask.

Flask
import os

if os.path.[1]('uploads/data.txt'):
    with open('uploads/data.txt', '[2]') as f:
        content = f.read()
Drag options to blanks, or click blank then click option'
Aexists
Bisfile
Cr
Dw
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' mode will overwrite the file instead of reading.
Using os.path.isfile also works but here 'exists' is expected.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps filenames to their sizes in Flask.

Flask
import os

file_sizes = [1]: os.path.getsize(f'uploads/[2]') for [3] in os.listdir('uploads') if os.path.isfile(f'uploads/[2]')
Drag options to blanks, or click blank then click option'
A{f
Bf
Dfile
Attempts:
3 left
💡 Hint
Common Mistakes
Not using curly braces to start the dictionary.
Using inconsistent variable names inside the comprehension.