In this Flask web development tutorial, we're going to cover how to protect files in a protected directory that you want some people to be able to access, but not everyone.
To start, we need some sort of super secret file. I will just use a Python logo.
Use whatever you like. Next, we need to add an instance path to our application. By default, the only place that Flask will look for files within your app will be the static directory. We could put the file in there, but the static directory is completely public, so that won't work. We'll start by editing our __init__.py
app = Flask(__name__, instance_path='/var/www/PythonProgramming/PythonProgramming/protected')
Here, we're adding instance_path to our initial app definition. Next, go ahead and create the protected directory in your project. This directory goes in the main app location, so you should be placing it with the static and templates directories.
Next, let's create a path that leads to this file within our __init__.py
from flask import send_from_directory # .... previous code .... @app.route('/protected/<path:filename>') @special_requirement def protected(filename): try: return send_from_directory( os.path.join(app.instance_path, ''), filename ) except: return redirect(url_for('main'))
Right away, you may notice our converter! Fancy stuff. So here, we're allowing any path after /protected/. From there, we use some fancy logic that will basically return the file that the path leads to. Not only this, but we can see this function is actually wrapped by special_requirement
. That function doesn't exist, let's make that. Again, that will be in __init__.py
def special_requirement(f): @wraps(f) def wrap(*args, **kwargs): try: if 'Harrison' == session['username']: return f(*args, **kwargs) else: return redirect(url_for('dashboard')) except: return redirect(url_for('dashboard')) return wrap
In this case, the username for the user needs to be 'Harrison.' Feel free to change it to whatever you like, or make up your own requirements. If the user is not logged in at all, an exception is hit and a redirect occurs. If they are logged in under another name, a redirection to the dashboard occurs.
This is really enough, we can now visit something like /protected/python.jpg
. If we're meeting the requirements of the wrapper, we can view the contents. If we attempt to just visit protected, that won't work. If we log out, then try again, we will not be granted access. You may need to hard refresh (shift+f5 in Chrome) to see this, as your cache may still show you the picture. Because of the way we have set our protected options up, you can organize your protected directory however you like and the files will be returned if the right path is used.
Next up, we're going to be talking about Flask with jQuery, which can help to make your website far more interactive and frictionless.