简体   繁体   English

FastAPI 数据库 SQL

[英]FastAPI database SQL

I has a FastAPI project where I have main.py, endpoints.py (with endpoint functions) and users_db.py where I have list of dictionaries.我有一个 FastAPI 项目,其中有 main.py、endpoints.py(带有端点函数)和 users_db.py,其中有字典列表。 Every dictionary save users data.每个字典都保存用户数据。 It just pet project to understand web application.它只是宠物项目来了解 Web 应用程序。 An now I want to create database.现在我想创建数据库。 I chose SQL.我选择了 SQL。 Can somebody explaine or give a link where is described how to do that?!有人可以解释或给出描述如何做到这一点的链接吗? Or is it very hard?!还是很难?!

it's very simple.这很简单。

first you need install sqlalchemy首先你需要安装 sqlalchemy

pip install SQLAlchemy

then create database.py file and paste the following code to that.然后创建 database.py 文件并将以下代码粘贴到该文件中。

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker


SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"

engine = create_engine(
    SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

then create models.py file and write some database models you need.然后创建models.py文件并编写一些您需要的数据库模型。

from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship

from .database import Base


class User(Base):
    __tablename__ = "users" # this is table name

    id = Column(Integer, primary_key=True, index=True)
    email = Column(String, unique=True, index=True)
    hashed_password = Column(String)
    is_active = Column(Boolean, default=True)


Read the documentation for more information.阅读文档以获取更多信息。 documentation文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM