Add User and Display Current Username in Flask

Add User and Display Current Username in Flask

In Flask, adding a user typically involves handling user data through forms, storing it in a database, and then using session management to track the current user. To display the current username, you would retrieve the user's information from the session.

Below is a simplified example to demonstrate this process. This example does not include user authentication mechanisms like passwords for simplicity.

Step 1: Set Up Flask App

First, install Flask if you haven't already:

pip install Flask 

Then, create your Flask app. Here's a basic structure:

from flask import Flask, request, render_template, redirect, url_for, session app = Flask(__name__) app.secret_key = 'your_secret_key' # Replace with a real secret key @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 render_template('login.html') @app.route('/logout') def logout(): session.pop('username', None) return redirect(url_for('index')) if __name__ == '__main__': app.run(debug=True) 

Step 2: Create Login Template

Create a template named login.html in the templates directory:

<!doctype html> <html> <head> <title>Login</title> </head> <body> <form action="" method="post"> <p><input type=text name=username> <p><input type=submit value=Login> </form> </body> </html> 

Step 3: Running the Flask App

Run your app, and it will allow users to "log in" by entering a username. The username is then stored in the session, and the user can see a message indicating they are logged in with their username. There's also a logout route to remove the username from the session.

Important Notes:

  • Security: This example does not include any form of real authentication (like password checks) or protection against CSRF attacks. For real-world applications, you should implement proper authentication and security measures.
  • Data Storage: This example does not connect to a database. In a real application, you would typically store user information in a database.
  • Secret Key: Make sure to use a secure, random secret key in your Flask app. This key is used to protect sessions and other sensitive data.
  • Session Management: Flask uses client-side sessions, which store a cookie on the user's browser. Be cautious about what you store in sessions. For more security, consider using server-side session management.

This example is a basic demonstration. Depending on your application's requirements, you might need more sophisticated user handling, authentication, and session management.


More Tags

getattr yup viewaction morse-code haml android-networking sslengine static-classes iis-7.5

More Programming Guides

Other Guides

More Programming Examples