Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FLask login coroutine error #877

Open
kernel-paniccc opened this issue Aug 16, 2024 · 0 comments
Open

FLask login coroutine error #877

kernel-paniccc opened this issue Aug 16, 2024 · 0 comments

Comments

@kernel-paniccc
Copy link

kernel-paniccc commented Aug 16, 2024

when I try to use login in flask with async sqlalhimy ORM I get an error

init.py

from flask import Flask
from dotenv import load_dotenv
from flask_login import LoginManager
from app.database.models import User, async_session
from sqlalchemy import select

import os, base64

load_dotenv()

app = Flask(__name__)

app.secret_key = base64.b64encode(str(os.getenv('APP_SEC_KEY')).encode())

app.config["SQLALCHEMY_DATABASE_URI"] = str(os.getenv('URL'))


login_manager = LoginManager()
login_manager.init_app(app)

@login_manager.user_loader
async def load_user(user_id):
    async with async_session() as session:
        user = await session.scalar(select(User).where(User.id == user_id))
        print(user.password)
        return user

models.py

from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
from sqlalchemy.ext.asyncio import AsyncAttrs, async_sessionmaker, create_async_engine
from sqlalchemy import BigInteger, ForeignKey
from flask_login import UserMixin

from dotenv import load_dotenv
import os

load_dotenv()

engine = create_async_engine(os.getenv('URL'))
async_session = async_sessionmaker(engine)


class Base(AsyncAttrs, DeclarativeBase):
    pass

class User(Base, UserMixin):
    __tablename__ = 'users'

    id: Mapped[int] = mapped_column(primary_key=True)
    tg_id = mapped_column(BigInteger, nullable=False)
    password: Mapped[str] = mapped_column(nullable=False)

    books = relationship("Book", back_populates="user")

class Book(Base, UserMixin):
    __tablename__ = 'books'

    id: Mapped[int] = mapped_column(primary_key=True)
    autor: Mapped[str] = mapped_column(nullable=False)
    name: Mapped[str] = mapped_column(nullable=False)
    genre: Mapped[str] = mapped_column(nullable=False)
    user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)

    user = relationship("User", back_populates="books")


async def async_main():
    async with engine.begin() as connect:
        await connect.run_sync(Base.metadata.create_all)

routers.py

from flask import flash, render_template, request, redirect

from flask_login import login_user, login_required, logout_user, current_user

from app.database.models import User, Book
from Flask_app.init import app
from app.database.models import async_session
from sqlalchemy import select



@app.route('/', methods=['GET', 'POST'])
async def login():
    try:
        tg_id = request.form.get('id')
        password = request.form.get('password')
        async with async_session() as session:
            result = await session.execute(select(User).where(User.tg_id == tg_id))
            user = result.scalars().first()
            if user is not None and str(user.password) == str(password):
                login_user(user)
                return redirect("/add_book")
            else:
                flash('error', category='error')
    except Exception as e:
        print(e)
        flash(str(e), category='error')

    return render_template('login_page.html')

@login_required
@app.route('/add_book', methods=['GET', 'POST'])
async def add_book():
    if request.method == 'POST':
        autor = request.form.get('autor')
        name = request.form.get('name')
        genre = request.form.get('genre')

        async with async_session() as session:
            new_book = Book(autor=autor, name=name, genre=genre, user_id=current_user.id)
            session.add(new_book)
            await session.commit()
            return redirect('/books')

    return render_template('add_book.html')

@login_required
@app.route('/books', methods=['GET'])
async def view_books():
    async with async_session() as session:
        result = await session.execute(select(Book).where(Book.user_id == current_user.id))
        books = result.scalars().all()

    return render_template('view_books.html', books=books)

@app.after_request
def redirect_to_signin(response):
    if response.status_code == 401:
        return redirect('/')
    return response

my error

** new_book = Book(autor=autor, name=name, genre=genre, user_id=current_user.id)
^^^^^^^^^^^^^^^
AttributeError: 'coroutine' object has no attribute 'id'**

how can i fix this ? can i convert coroutine to object . please help

@kernel-paniccc kernel-paniccc changed the title FLask login corutine error FLask login coroutine error Aug 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant