[파이썬] Flask 로그인 및 인증

Flask is a popular web framework in Python that allows you to build web applications quickly and easily. In this blog post, we will explore how to implement login and authentication functionality in a Flask application.

Setting up Flask

To get started, we need to install Flask. You can do this by running the following command in your terminal:

$ pip install Flask

Creating the Flask Application

Let’s create a basic Flask application that will serve as the foundation for our login and authentication functionality. Create a new Python file called app.py and copy the following code into it:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Welcome to the Flask Login and Authentication example!"

if __name__ == '__main__':
    app.run()

Implementing Login

To implement the login functionality, we need to create a login view and handle the login request. Modify app.py with the following code:

from flask import Flask, render_template, request, redirect, session

app = Flask(__name__)
app.secret_key = 'your_secret_key'

@app.route('/')
def home():
    return "Welcome to the Flask Login and Authentication example!"

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        # Perform login validation here
        
        # If login is successful, store user info in session
        session['username'] = username
        return redirect('/')
    
    return render_template('login.html')

if __name__ == '__main__':
    app.run()

In the code above, we added a /login route that handles both GET and POST requests. When a POST request is received, we extract the username and password values from the request form data. You can perform your own login validation logic at this point.

If the login is successful, we store the username in the session object and redirect the user to the home page.

Adding Logout

It’s essential to provide a way for users to log out of our application. We can achieve this by adding a logout route to our app.py file:

from flask import Flask, render_template, request, redirect, session

app = Flask(__name__)
app.secret_key = 'your_secret_key'

# ...

@app.route('/logout')
def logout():
    # Clear the session
    session.clear()
    return redirect('/')

if __name__ == '__main__':
    app.run()

The /logout route clears the session, effectively logging the user out, and redirects them back to the home page.

Protecting Routes

Now that we have implemented the login and logout functionality, we can protect specific routes that require authentication. Modify your app.py file as shown below:

from flask import Flask, render_template, request, redirect, session, abort

# ...

@app.route('/protected')
def protected():
    # Check if the user is logged in
    if 'username' not in session:
        abort(401)  # Unauthorized
    
    # User is logged in, display protected content
    return "Welcome to the protected page!"

# ...

if __name__ == '__main__':
    app.run()

In the code above, we added a /protected route that requires the user to be logged in. If the user is not logged in (i.e., the username key is not present in the session), we abort the request and return an unauthorized status code (401).

Conclusion

In this blog post, we explored how to implement login and authentication functionality in a Flask application. We learned how to create a basic Flask application, handle login requests, add logout functionality, and protect routes that require authentication. Flask provides a simple yet powerful way to handle user authentication in your web applications.

Make sure to refer to the official Flask documentation for more detailed explanations and advanced usage. Happy coding!