0Pricing
Flask Academy · Урок

Загрузчик пользователей и UserMixin

Настройте LoginManager и модель пользователя.

«Загрузчик пользователей и UserMixin» — бесплатный урок Flask Academy на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Flask Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Flask Academy содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Meet Flask-Login

The Flask-Login extension manages who is logged in for you. It tracks the current user across requests so you do not wire sessions by hand.

pip install flask-login

Create a LoginManager

Everything starts with a LoginManager. You create one instance and connect it to your app so Flask-Login can hook into requests.

from flask_login import LoginManager
login_manager = LoginManager()
login_manager.init_app(app)

It Needs Two Things

To work, the manager needs a user model that follows its rules and a function that loads a user by id. Today you set up both.

The UserMixin Shortcut

Your model must expose a few properties like is_authenticated. The UserMixin class supplies them all, so you just inherit from it.

from flask_login import UserMixin
class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)

What UserMixin Gives You

UserMixin adds is_authenticated, is_active, is_anonymous, and get_id for free. That last one returns your user id as a string.

The user_loader Callback

Flask-Login stores only the user id in the session. It calls your user_loader on each request to turn that id back into a real user.

Register the Loader

Decorate a function with login_manager.user_loader. It receives the id from the session and must return a user object or None.

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

Ids Arrive as Strings

The id passed to your loader is always a string, since it came from a cookie. Cast it to int before querying an integer primary key.

return User.query.get(int(user_id))

Return None for Unknowns

If the id matches no row, your loader should return None. Flask-Login then treats the request as coming from an anonymous visitor.

Override get_id If Needed

If your primary key is not named id, override get_id so it returns the right value. Most apps with a plain id column never touch it.

def get_id(self):
    return str(self.uuid)

Pieces Now Connected

With the manager, the UserMixin model, and a user_loader in place, Flask-Login can identify the current user on every incoming request.

Quick Check

Think about what the session actually stores between requests.

Recap

You wired a LoginManager, mixed UserMixin into your model, and wrote a user_loader. Flask-Login can now rebuild the current user from a session. 👤

Часто задаваемые вопросы

Урок «Загрузчик пользователей и UserMixin» бесплатный?

Да — полный текст урока «Загрузчик пользователей и UserMixin» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Flask Academy, подпишись на CoddyKit PRO. Курс Flask Academy содержит 4 уроков всего.

Чему я научусь в уроке «Загрузчик пользователей и UserMixin»?

Настройте LoginManager и модель пользователя. Ты практикуешь Flask Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Flask Academy?

Предыдущий опыт не требуется. Flask Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Загрузчик пользователей и UserMixin»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Flask Academy?

Да. Каждый урок Flask Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Хеширование паролей: никогда не храните открытый текст
  2. Загрузчик пользователей и UserMixin
  3. login_user, logout_user и сеансы
  4. Защита представлений с помощью login_required
← Назад к Flask Academy