简体   繁体   中英

How to check allowed file extensions in flask

I am working on a code where in I need to define a fuction which checks for the allowed file extensions. The fuction takes filename and extension as arguments as shown below:

def allowed_file(filename, extensions=None):

Steps to write the function:

  • extensions' is either None or a list of file extensions.
  • If a list is passed as 'extensions' argument, check if 'filename' contains one of the extension provided in the list and return True or False respectively.
  • If no list is passed to 'extensions' argument, then check if 'filename' contains one of the extension provided in list
    'ALLOWED_EXTENSIONS', defined in 'config.py',and return True or False respectively.

Kindly guide how to proceed on this.

Since we don't do homework in stackoverflow I'm not going to give you the full code.

But I can give you the pseudo code:

First of all filenames in python are provided in their full form: file1.txt , image.png and so on.

For checking if a list contains an object we use in operator: "txt" in extensions => True

def allowed_extensions(filename,extensions=None):
    # TODO : Extract the file extension from filename
    # TODO : Check if the extension exists in extensions list or not
    # TODO : Return True if it exists and False if not

btw, these links can help you:

in and not operator in python

split function in python

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM