flask身份验证_使用Flask登录进行身份验证和授权

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're going to build some sign up and login pages that allows our app to allow users to login and access protected pages that non-logged in users can see. We'll grab information from the user model and display it on our protected pages when the user logs in to simulate what a profile would look like.

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
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python Flask提供了多种身份验证方式,常用的有以下几种: 1. 基本认证(Basic Authentication):通过用户名和密码进行验证,使用HTTP的Authorization头字段传递。 2. Token认证(Token Authentication):通过在每个请求中传递一个token来验证用户身份。token通常是一串加密的字符串,用于识别用户。 3. OAuth认证(OAuth Authentication):OAuth是一种授权协议,允许用户通过第三方服务进行身份验证授权。 下面是一个使用基本认证的示例代码: ```python from flask import Flask, request, Response from functools import wraps app = Flask(__name__) def check_auth(username, password): return username == 'admin' and password == 'secret' def authenticate(): return Response( 'Unauthorized', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'} ) def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): auth = request.authorization if not auth or not check_auth(auth.username, auth.password): return authenticate() return f(*args, **kwargs) return decorated @app.route('/') @requires_auth def index(): return "Hello, authenticated user!" if __name__ == '__main__': app.run() ``` 在上面的代码中,我们定义了一个check_auth函数,用于验证用户名和密码是否正确。authenticate函数用于返回401错误码和WWW-Authenticate头,提示用户需要登录。requires_auth是一个装饰器函数,用于验证请求是否经过身份验证。如果没有经过身份验证,则调用authenticate函数。 在路由函数中使用@requires_auth装饰器,表示该路由需要经过身份验证才能访问。如果用户提供了正确的用户名和密码,则返回"Hello, authenticated user!"。如果没有提供正确的用户名和密码,则返回401错误码和WWW-Authenticate头,提示用户登录

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值