Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the FastAPI framework?

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

The main content of this article is to explain "what is the FastAPI framework". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what is the FastAPI framework"?

FastAPI is a modern, fast (high-performance) web framework for building API, using Python 3.6 + and standards-based Python type hints.

Key features:

Fast: extremely high performance comparable to NodeJS and Go (thanks to Starlette and Pydantic). One of the fastest Python web frameworks.

Efficient coding: increase the speed of function development by about 200% to 300%.

Less bug: reduce human (developer) errors by about 40%.

Smart: excellent editor support. It can be completed automatically everywhere to reduce the debugging time.

Simple: the design is easy to use and learn, and it takes less time to read the document.

Brevity: minimize code repetition. Rich functionality is achieved through different parameter declarations. There is less bug.

Robust: produces available levels of code. There are also automatically generated interactive documents.

Standardization: based on (and fully compatible with) the relevant open standards of API: OpenAPI (formerly known as Swagger) and JSON Schema.

The above is the introduction of FastAPI official documentation, through my own use, I found that although the efficiency is not as high as officially said, but it will be much faster, and I think the code writing of this framework is a little bit more pythonic, if you are used to it, you will be more standardized when writing other Python code.

People who are familiar with Flask may be faster to use FastAPI, a py script can build a website, but when we develop a project, we certainly will not put all the logic into a script, so we need to provide a complete project framework like Django, business development as long as according to fixed rules to add. Although the official provided a project framework template, but because of the high degree of freedom of FastAPI, so we can according to their own habits to achieve a project framework, I used to use Django to achieve a framework that I think is more appropriate. The following is a general introduction.

Brief introduction

Use FastAPI + MySql + Tortoise-orm as the main database operation, and the project structure refers to two projects on GitHub:

CoderCharm / fastapi-mysql-generator

FastAPI-demo

Function

JWT token certification.

Use Tortoise-orm models (MySql).

Authority Verification based on casbin

Loguru logging module uses

Authority control

Interfaces with openapi in login, registration and routing do not log in and authenticate permissions

Async def jwt_authentication (request: Request, x_token: str = Header (None, title=' login Token', description=' login, registration and open API do not need this parameter'): "" except for open API, login, registration Other authentication is required: param request:: return: "if 'openapi' in request.url.path.lower () or\' login' in request.url.path.lower () or\ 'register' in request.url.path.lower (): return None....

Global login authentication (with the exception of the above interfaces, all other interfaces perform login authentication)

App = FastAPI (debug=settings.DEBUG, title=settings.TITLE, description=settings.DESCRIPTION, docs_url=settings.DOCS_URL, redoc_url=settings.REDOC_URL, dependencies= [Depends (jwt_authentication)])

Global Depends (jwt_authentication) dependency injection

Interface permission authentication

Firstly, the permissions are configured through auth/add and auth/del interfaces.

@ router.get ("/ info", summary= "get current user information", name= "get current user information", response_model=schema.UserOut, response_model_exclude_unset=True, dependencies= [Depends (Authority ('user,check'))])

Add Depends (Authority ('user,check')) dependency injection to the interface to determine permissions

Operation authority authentication

To authenticate special permissions in the interface, you only need to use the check_authority function to judge. If there is no limit, an exception will be thrown.

Await check_authority (f'{request.state.user.username}, auth,add') configuration

Configuration file:

Core/config/development_config.py and production_config.py

Modify the default address of an API document

In order to pass the permission authentication, change the address of the API document to the URL containing openapi

# document address defaults to docs DOCS_URL: str = "/ openapi/docs" # document association request data interface OPENAPI_URL: str = "/ openapi/openapi.json" # redoc document REDOC_URL: Optional [str] = "/ openapi/redoc"

Super Admin

Set the user whose role is super to Super Admin

SUPER_USER: str = 'super' configuration database # Database configuration DATABASE_CONFIG: dict = {' connections': {# Dict format for connection 'default':' mysql://root:123456@127.0.0.1:3306/testdb'} 'apps': {' models': {# set the database connection to the key value "default" 'default_connection':' default', 'models': [' apps.user.model', 'auth.casbin_tortoise_adapter']}

The database uses Tortoise-orm library, because I have been using Django,Django to have its own set of ORM model operations, which is convenient and familiar. Many people use sqlalchemy, which I think is inconvenient, while Tortoise-orm is an asynchronous database operation library implemented by Django ORM, which is friendly to people who use Django.

Run # to enter the project directory pipenv install # enter the virtual environment pipenv shell # run server python run.py here, I believe you have a deeper understanding of "what is the FastAPI framework", you might as well to actually do it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report