{"id":457,"date":"2024-11-14T14:38:04","date_gmt":"2024-11-14T06:38:04","guid":{"rendered":"https:\/\/my.di.cloudns.asia\/?p=457"},"modified":"2024-11-14T14:39:44","modified_gmt":"2024-11-14T06:39:44","slug":"building-an-admin-panel-for-fastapi-apps-step-by-step-tutorial-sqladmin","status":"publish","type":"post","link":"https:\/\/my.di.cloudns.asia\/index.php\/2024\/11\/14\/457.html","title":{"rendered":"Building an Admin Panel for FastAPI Apps | Step-by-Step Tutorial | Sqladmin"},"content":{"rendered":"<blockquote>\n<p>\u672c\u6587\u7531 <a href=\"http:\/\/ksria.com\/simpread\/\">\u7b80\u60a6 SimpRead<\/a> \u8f6c\u7801\uff0c \u539f\u6587\u5730\u5740 <a href=\"https:\/\/readmedium.com\/building-an-admin-panel-for-fastapi-apps-step-by-step-tutorial-sqladmin-23eb6f1d6a37\">readmedium.com<\/a><\/p>\n<h1>Introduction<br \/>\n<div class='fancybox-wrapper lazyload-container-unload' data-fancybox='post-images' href='https:\/\/my.di.cloudns.asia\/wp-content\/uploads\/2024\/11\/image-1731566348069.png'><img class=\"lazyload lazyload-style-1\" src=\"data:image\/svg+xml;base64,PCEtLUFyZ29uTG9hZGluZy0tPgo8c3ZnIHdpZHRoPSIxIiBoZWlnaHQ9IjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgc3Ryb2tlPSIjZmZmZmZmMDAiPjxnPjwvZz4KPC9zdmc+\"  decoding=\"async\" data-original=\"https:\/\/my.di.cloudns.asia\/wp-content\/uploads\/2024\/11\/image-1731566348069.png\" src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB\/AAffA0nNPuCLAAAAAElFTkSuQmCC\" alt=\"file\" \/><\/div><br \/>\nBuilding an Admin Panel for FastAPI Apps | Step-by-Step Tutorial | Sqladmin<\/h1>\n<\/blockquote>\n<h1>Introduction<\/h1>\n<p>FastAPI, known for it\u2019s 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\u2019s harness the power of FastAPI and embark on a journey to build an admin panel that not only meets but exceeds your expectations. Let\u2019s dive in!<\/p>\n<h1>Step -1 : Installation<\/h1>\n<p>Before we start let\u2019s clear the dependencies. we will use <strong><em>sqlalchemy<\/em><\/strong> for database operation and <strong><em>sqladmin<\/em><\/strong> 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.<\/p>\n<pre><code>pip install sqlalchemy\npip install sqladmin\npip install sqladmin[full]\n<\/code><\/pre>\n<h1>Step-2 : Create the Database<\/h1>\n<p>create a example_database.py file and create or link your database with sqlalchemy<\/p>\n<pre><code>from sqlalchemy import create_engine\nfrom sqlalchemy.orm import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\nengine = create_engine(&quot;sqlite:\/\/\/example.db&quot;,isolation_level=&#039;AUTOCOMMIT&#039;)\n\nsession = sessionmaker(bind=engine)\nBase = declarative_base()\n<\/code><\/pre>\n<h1>Step-3 : Create Models<\/h1>\n<p>create a models.py file and create your models(Tables)<\/p>\n<pre><code>from sqlalchemy import Column, Integer, String, Boolean\nfrom example_database import Base, engine, session\n\nclass User(Base):\n    __tablename__ = &quot;users&quot;\n\n    id = Column(Integer, primary_key=True)\n    email = Column(String)\n    username = Column(String)\n    password = Column(String)\n    firstname = Column(String)\n    lastname = Column(String)\n    is_admin = Column(Boolean)\n\nBase.metadata.create_all(engine)\n<\/code><\/pre>\n<h1>Step-4: Create main.py<\/h1>\n<p>Now create a file named main.py. This will be the main file of your fastapi app.<\/p>\n<pre><code>from fastapi import FastAPI\nfrom admin import create_admin #we will create this file in a while\n\napp = FastAPI(title=&quot;AppName&quot;)\nadmin = create_admin(app)  # we will write this function in a while\n\n# list your APIs here\n@app.get(&quot;\/&quot;)\nasync def hello_world():\n    return {&quot;message&quot;:&quot;Hello World&quot;}\n<\/code><\/pre>\n<h1>Step-5: Create admin.py<\/h1>\n<p>Now create another file named admin.py. all the admin actions will be controlled from here. Also authentication will be handled from here.<\/p>\n<pre><code>from sqladmin import Admin, ModelView\nfrom example_database import engine, session\nfrom models.py import Users\nfrom sqladmin.authentication import AuthenticationBackend\nfrom starlette.requests import Request\n\n#This page will implement the authentication for your admin pannel\nclass AdminAuth(AuthenticationBackend):\n\n    async def login(self, request: Request) -&gt; bool:\n        form = await request.form()\n        user)\n        password= form.get(&quot;password&quot;)\n        session = session()\n        user = session.query(Users).filter(Users.username == username).first()\n        if user and password== user.password:\n            if user.is_admin:\n                request.session.update({&quot;token&quot;: beta_user.username})\n                return True\n        else:\n            False\n\n    async def logout(self, request: Request) -&gt; bool:\n        request.session.clear()\n        return True\n\n    async def authenticate(self, request: Request) -&gt; bool:\n        token = request.session.get(&quot;token&quot;)\n        return token is not None\n\n# create a view for your models\nclass UsersAdmin(ModelView, model=Users):\n    column_list = [\n        &#039;id&#039;, &#039;email&#039;, &#039;first_name&#039;, &#039;last_name&#039;, &#039;is_admin&#039;\n    ]\n\n# add the views to admin\ndef create_admin(app):\n    authentication_backend = AdminAuth(secret_key=&quot;supersecretkey&quot;)\n    admin = Admin(app=app, engine=engine, authentication_backend=authentication_backend)\n    admin.add_view(UsersAdmin)\n\n    return admin\n<\/code><\/pre>\n<p>That\u2019t it . we are finished with the coding. now just a few steps are left.<\/p>\n<h1>Step-6 : Migrate your models to database<\/h1>\n<p>run this command to create a migration script.<\/p>\n<pre><code>alembic revision --autogenerate -m &quot;Add table Users&quot;\n<\/code><\/pre>\n<p>Then apply the migration to move your model to your database<\/p>\n<pre><code>alembic upgrade head\n<\/code><\/pre>\n<h1>Step-7 : Run the app<\/h1>\n<p>Now run the app<\/p>\n<pre><code>uvicorn main:app --reload\n<\/code><\/pre>\n<p>if everything is okay then go to<\/p>\n<pre><code>http:\/\/localhost:8000\/admin\n<\/code><\/pre>\n<p>You should see a page that will ask you for username and password<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u672c\u6587\u7531 \u7b80\u60a6 SimpRead \u8f6c\u7801\uff0c \u539f\u6587\u5730\u5740 readmedium.com Introduction Bu [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":459,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-457","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/my.di.cloudns.asia\/index.php\/wp-json\/wp\/v2\/posts\/457","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/my.di.cloudns.asia\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/my.di.cloudns.asia\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/my.di.cloudns.asia\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/my.di.cloudns.asia\/index.php\/wp-json\/wp\/v2\/comments?post=457"}],"version-history":[{"count":2,"href":"https:\/\/my.di.cloudns.asia\/index.php\/wp-json\/wp\/v2\/posts\/457\/revisions"}],"predecessor-version":[{"id":460,"href":"https:\/\/my.di.cloudns.asia\/index.php\/wp-json\/wp\/v2\/posts\/457\/revisions\/460"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/my.di.cloudns.asia\/index.php\/wp-json\/wp\/v2\/media\/459"}],"wp:attachment":[{"href":"https:\/\/my.di.cloudns.asia\/index.php\/wp-json\/wp\/v2\/media?parent=457"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/my.di.cloudns.asia\/index.php\/wp-json\/wp\/v2\/categories?post=457"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/my.di.cloudns.asia\/index.php\/wp-json\/wp\/v2\/tags?post=457"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}