Random Static File Server Route

  • Share this:

Code introduction


This function defines a route that serves a random static file from a specified directory and returns it to the client. If the directory does not contain any files, it returns a 404 error.


Technology Stack : Bottle

Code Type : Web service

Code Difficulty : Intermediate


                
                    
from bottle import request, response, route, run, static_file

def random_resource():
    """
    This function serves a random static file from a specified directory.
    """
    route('/random', callback=random_resource)
    def callback():
        files = static_file.listdir('/path/to/static/files')
        if files:
            random_file = files[random.randint(0, len(files) - 1)]
            return static_file(random_file, root='/path/to/static/files')
        else:
            response.status = 404
            return "No files found in the directory."                
              
Tags: