flask身份验证
Allowing users to login to your app is one of the most common features you'll add to a web app you build. This article will cover how to add simple authentication to your Flask app. The main package we will use to accomplish this is Flask Login.
允许用户登录到您的应用程序是您将添加到所构建的Web应用程序中的最常见功能之一。 本文将介绍如何向Flask应用添加简单身份验证。 我们将使用的主要软件包是Flask Login 。
我们将要建设的 ( What We'll Be Building )
We will cover the following in this article:
我们将在本文中介绍以下内容:
- Use the Flask-Login library for session management 使用Flask-Login库进行会话管理
- Use the built-in Flask utility for hashing passwords 使用内置的Flask实用程序对密码进行哈希处理
- Add protected pages to our app for logged in users only 将受保护的页面添加到我们的应用中,仅适用于登录用户
- Use Flask-SQLAlchemy to create a user model 使用Flask-SQLAlchemy创建用户模型
- Create sign up and login forms for our users to create accounts and login 为我们的用户创建注册和登录表单,以创建帐户和登录
- Flash error messages back to users when something goes wrong 发生错误时将Flash错误消息返回给用户
- Use information from the user's account to display on the profile page 使用来自用户帐户的信息显示在配置文件页面上
设置应用 ( Setting Up The Application )
Our app will use the Flask app factory pattern with blueprints. We'll have one blueprint that handles everything auth related, and we'll have another blueprint for our regular routes, which include the index and the protected profile page. In a real app, of course, you can break down the functionality in any way you like, but what I've proposed will work well for this tutorial.
我们的应用程序将使用带有蓝图的Flask应用程序工厂模式。 我们将拥有一个处理所有与auth相关的蓝图,并且还将为我们的常规路由(包括索引和受保护的配置文件页面)提供另一蓝图。 当然,在真实的应用程序中,您可以按自己喜欢的任何方式分解功能,但是我建议的内容在本教程中会很好地起作用。
To start, we need to create the directories and files for our project.
首先,我们需要为项目创建目录和文件。
- project
---- templates
-------- base.html<!-- contains common layout and links -->
-------- index.html <!-- show the home page -->
-------- login.html <!-- show the login form -->
-------- profile.html <!-- show the profile page -->
-------- signup.html <!-- show the signup form -->
---- __init__.py <!-- setup our app -->
---- auth.py <!-- the auth routes for our app -->
---- main.py <!-- the non-auth routes for our app -->
---- models.py <!-- our user model -->
You can create those files and we'll add them as we progress along.
您可以创建这些文件,并在进行过程中添加它们。
安装套件 ( Install Packages )
There are three main packages we need for our project:
我们的项目需要三个主要软件包:
- Flask 烧瓶
- Flask-Login - to handle the user sessions after authentication Flask-Login-处理身份验证后的用户会话
- Flask-SQLAlchemy - to represent the user model and interface with our database Flask-SQLAlchemy-表示用户模型和与我们的数据库的接口
We'll only be using SQLite for the database to avoid having to install any extra dependencies for the database. Here's what you need to run after creating your virtual environment to install the packages.
我们将仅对数据库使用SQLite,以避免必须为数据库安装任何其他依赖项。 这是在创建虚拟环境以安装软件包之后需要运行的内容。
pipinstall flask flask-sqlalchemy flask-login
主应用程序文件 ( Main App File )
Let's start by creating the __init__.py file for our project. This will have the function to create our app which will initialize the database and register our blueprints. At the moment this won't do much, but it will be needed for the rest of our app. All we need to do is initialize SQLAlchemy, set some configuration values, and register our blueprints here.
让我们从为项目创建__init__.py文件开始。 这将具有创建我们的应用程序的功能,该应用程序将初始化数据库并注册我们的蓝图。 目前,这不会做太多,但其余的应用程序将需要它。 我们需要做的就是初始化SQLAlchemy,设置一些配置值,然后在此处注册我们的蓝图。
__init__.py (__init__.py)
# __init__.py
from flask import Flask__
from flask_sqlalchemy import SQLAlchemy
# init SQLAlchemy so we can use it later in our models
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = '9OLWxND4o83j4K4iuopO'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
db.init_app(app)
# blueprint for auth routes in our app
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)
# blueprint for non-auth parts of app
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
return app
路线脚手架 ( Route Scaffolding )
Now that we have the main app file, we can start adding in our routes.
现在我们有了主应用程序文件,我们可以开始添加路线了。
For our routes, we'll use two blueprints. For our main blueprint, we'll have a home page (/) and profile page (/profile) for after we log in. If the user tries to access the profile page without being logged in, they'll be sent to our login route.
对于我们的路线,我们将使用两个蓝图。 对于我们的主要蓝图,我们将在登录后有一个主页(/)和个人资料页面(/ profile)。如果用户试图在未登录的情况下访问个人资料页面,则会将其发送到我们的登录名路线。
For our auth blueprint, we'll have routes to retrieve both the login page (/login) and signup page (/signup). We'll also have routes for handling the POST request from both of those two routes. Finally, we'll have a logout route (/logout) to logout an active user.
对于我们的身份验证蓝图,我们将具有检索登录页面(/ login)和注册页面(/ signup)的路由。 我们还将提供用于处理来自这两个路由的POST请求的路由。 最后,我们将有一个注销路由(/ logout)来注销活动用户。
Let's go ahead and add them even though they won't do much. Later we will update them so we can use them.
让我们继续添加它们,即使它们不会做太多。 稍后我们将对其进行更新,以便我们可以使用它们。
main.py (main.py)
# main.py
from flask import Blueprint
from . import db
main = Blueprint('main', __name__)
@main.route('/')
def index():
return 'Index'
@main.route('/profile')
def profile():
return 'Profile'
身份验证 (auth.py)
# auth.py
from flask import Blueprint
from . import db
auth = Blueprint('auth', __name__)
@auth.route('/login')
def login():
return 'Login'
@auth.route('/signup')
def signup():
return 'Signup'
@auth.route('/logout')
def logout():
return 'Logout'
You can now set the FLASK_APP and FLASK_DEBUG values and run the project. You should be able to view navigate to the five possible URLs and see the text returned.
现在,您可以设置FLASK_APP和FLASK_DEBUG值并运行项目。 您应该能够查看导航到五个可能的URL并看到返回的文本。
export FLASK_APP=project
export FLASK_DEBUG=1
flask run
范本 ( Templates )
Let's go ahead and create the templates that are used in our app. This is the first step before we can implement the actual login functionality. Our app will use four templates:
让我们继续创建在我们的应用程序中使用的模板。 这是实现实际登录功能之前的第一步。 我们的应用将使用四个模板:
- index.html index.html
- profile.html profile.html
- login.html login.html
- signup.html signup.html
We'll also have a base template that will have code common to each of the pages. In this case, the base template will have navigation links and the general layout of the page. Let's create them now.
我们还将有一个基本模板,该模板将具有每个页面共有的代码。 在这种情况下,基本模板将具有导航链接和页面的总体布局。 现在创建它们。
templates / base.html (templates/base.html)
<!-- templates/base.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Flask Auth Example</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css" />
</head>
<body>
<section class="hero is-primary is-fullheight">
<div class="hero-head">
<nav class="navbar