本文由 简悦 SimpRead 转码, 原文地址 readmedium.com
Introduction
Building an Admin Panel for FastAPI Apps | Step-by-Step Tutorial | Sqladmin
Introduction
FastAPI, known for it’s lightning-fast performance and intuitive design, has emerged as a favorite among developers seeking to streamline their backend processes. Today in this article we will see how can we create an admin panel. This is a complete step-by-step tutorial will cover everything you need to build a feature-rich admin interface from scratch. Let’s harness the power of FastAPI and embark on a journey to build an admin panel that not only meets but exceeds your expectations. Let’s dive in!
Step -1 : Installation
Before we start let’s clear the dependencies. we will use sqlalchemy for database operation and sqladmin for admin service. These two are very important because if you are using any other database operation library or other admin then this article might not help you.
pip install sqlalchemy
pip install sqladmin
pip install sqladmin[full]
Step-2 : Create the Database
create a example_database.py file and create or link your database with sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine("sqlite:///example.db",isolation_level='AUTOCOMMIT')
session = sessionmaker(bind=engine)
Base = declarative_base()
Step-3 : Create Models
create a models.py file and create your models(Tables)
from sqlalchemy import Column, Integer, String, Boolean
from example_database import Base, engine, session
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
email = Column(String)
username = Column(String)
password = Column(String)
firstname = Column(String)
lastname = Column(String)
is_admin = Column(Boolean)
Base.metadata.create_all(engine)
Step-4: Create main.py
Now create a file named main.py. This will be the main file of your fastapi app.
from fastapi import FastAPI
from admin import create_admin #we will create this file in a while
app = FastAPI(title="AppName")
admin = create_admin(app) # we will write this function in a while
# list your APIs here
@app.get("/")
async def hello_world():
return {"message":"Hello World"}
Step-5: Create admin.py
Now create another file named admin.py. all the admin actions will be controlled from here. Also authentication will be handled from here.
from sqladmin import Admin, ModelView
from example_database import engine, session
from models.py import Users
from sqladmin.authentication import AuthenticationBackend
from starlette.requests import Request
#This page will implement the authentication for your admin pannel
class AdminAuth(AuthenticationBackend):
async def login(self, request: Request) -> bool:
form = await request.form()
user)
password= form.get("password")
session = session()
user = session.query(Users).filter(Users.username == username).first()
if user and password== user.password:
if user.is_admin:
request.session.update({"token": beta_user.username})
return True
else:
False
async def logout(self, request: Request) -> bool:
request.session.clear()
return True
async def authenticate(self, request: Request) -> bool:
token = request.session.get("token")
return token is not None
# create a view for your models
class UsersAdmin(ModelView, model=Users):
column_list = [
'id', 'email', 'first_name', 'last_name', 'is_admin'
]
# add the views to admin
def create_admin(app):
authentication_backend = AdminAuth(secret_key="supersecretkey")
admin = Admin(app=app, engine=engine, authentication_backend=authentication_backend)
admin.add_view(UsersAdmin)
return admin
That’t it . we are finished with the coding. now just a few steps are left.
Step-6 : Migrate your models to database
run this command to create a migration script.
alembic revision --autogenerate -m "Add table Users"
Then apply the migration to move your model to your database
alembic upgrade head
Step-7 : Run the app
Now run the app
uvicorn main:app --reload
if everything is okay then go to
http://localhost:8000/admin
You should see a page that will ask you for username and password