Why Flask?
Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks.
Why __name__
is used?
from flask import Flask
# this __name__ is required!
app = Flask(__name__)
The first argument is the name of the application’s module or package. name is a convenient shortcut for this that is appropriate for most cases. This is needed so that Flask knows where to look for resources such as templates and static files.
Easy reload
if __name__ == "__main__":
# note that `debug=True`
app.run(debug=True)
The
debug=True
server provides an interactive debugger and will reload when code is changed. So, no need to stop the app, and restart it again. Just save a python file, and the server will automatically reload.
Sessions
## CODE FROM:
## https://flask.palletsprojects.com/en/2.0.x/quickstart/#sessions
from flask import session
# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
@app.route('/')
def index():
if 'username' in session:
return f'Logged in as {session["username"]}'
return 'You are not logged in'
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
return redirect(url_for('index'))
return '''
<form method="post">
<p><input type=text name=username>
<p><input type=submit value=Login>
</form>
'''
@app.route('/logout')
def logout():
# remove the username from the session if it's there
session.pop('username', None)
return redirect(url_for('index'))
session allows you to store information specific to a user from one request to the next. This is implemented on top of cookies for you and signs the cookies cryptographically. What this means is that the user could look at the contents of your cookie but not modify it, unless they know the secret key used for signing.
Custom 404 Pages
from flask import render_template
@app.errorhandler(404)
def not_found(error):
# assuming you have `error.html` at `templates` directory
return render_template('error.html')
Reference: Flask
Top comments (0)