指标CRUD

This commit is contained in:
王思川 2022-09-30 15:00:45 +08:00
parent ad14d06816
commit 413511a6c8
10 changed files with 371 additions and 92 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
.idea
*.pyc

0
Indicator/__init__.py Normal file
View File

128
Indicator/crud.py Normal file
View File

@ -0,0 +1,128 @@
from sqlalchemy.orm import Session
from . import models, schemas
def get_indicator(db: Session, _id: int):
"""
:param db:
:param _id:
:return:
"""
return db.query(models.Indicator).filter(models.Indicator.id == _id).first()
def get_indicator_by_ename(db: Session, ename: str):
"""
:param db:
:param ename:
:return:
"""
return db.query(models.Indicator).filter(models.Indicator.ename == ename).first()
def get_indicator_by_cname(db: Session, cname: str):
"""
:param cname:
:param db:
:param cname:
:return:
"""
return db.query(models.Indicator).filter(models.Indicator.cname == cname).first()
def get_indicators(db: Session, skip: int = 0, limit: int = 20):
"""
:param db:
:param skip:
:param limit:
:return:
"""
return db.query(models.Indicator).offset(skip).limit(limit).all()
def create_indicator(db: Session, indicator_create: schemas.IndicatorCreate):
"""
创建指标
:param db: 数据库会话
:param indicator_create:
:return:
"""
db_item = models.Indicator(**indicator_create.dict())
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
def delete_indicator(db: Session, _id: int):
"""
删除指标
:param db:
:param _id:
:return:
"""
db.query(models.Indicator).filter_by(id=_id).delete()
db.commit()
return True
def edit_indicator(db: Session, _id: int, body: schemas.IndicatorEdit):
"""
编辑指标
:param _id:
:param db: 数据库会话
:param body:
:return:
"""
db.query(models.Indicator).filter_by(id=_id).update(body.dict())
db.commit()
return db.query(models.Indicator).filter(models.Indicator.id == _id).first()
def get_parameters(db: Session, skip: int = 0, limit: int = 100):
"""
:param db: 数据库会话
:param skip: 开始位置
:param limit: 限制数量
:return:
"""
return db.query(models.Parameters).offset(skip).limit(limit).all()
def create_indicator_parameters(db: Session, item: schemas.ParameterCreate, _id: int):
"""
:param db: 数据库会话
:param item:
:param _id:
:return:
"""
db_item = models.Parameters(**item.dict(), indicator_id=_id)
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
def delete_indicator_parameters(db: Session, _id: int):
"""
删除指标参数
:param db:
:param _id:
:return:
"""
db.query(models.Parameters).filter_by(id=_id).delete()
db.commit()
return True
def edit_indicator_parameters(db: Session, _id: int, body: schemas.ParameterEdit):
"""
删除指标参数
:param body:
:param db:
:param _id:
:return:
"""
db.query(models.Parameters).filter_by(id=_id).update(body.dict())
db.commit()
return True

13
Indicator/database.py Normal file
View File

@ -0,0 +1,13 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = (
"mysql+pymysql://root:123456@localhost/wr_index_store?charset=utf8mb4"
)
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

78
Indicator/indicator.py Normal file
View File

@ -0,0 +1,78 @@
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from Indicator import crud, models, schemas
from Indicator.database import SessionLocal, engine
models.Base.metadata.create_all(bind=engine)
router = APIRouter()
def get_db():
try:
db = SessionLocal()
yield db
finally:
db.close()
# 新建指标
@router.post("/create/", response_model=schemas.Indicator, summary='新建指标', description='接口描述', tags=['指标'])
def create_indicator(req_body: schemas.IndicatorCreate, db: Session = Depends(get_db)):
db_indicator = crud.get_indicator_by_ename(db, ename=req_body.ename)
if db_indicator:
raise HTTPException(status_code=400, detail="Indicator already registered")
return crud.create_indicator(db=db, indicator_create=req_body)
# 删除指标
@router.post("/delete/", summary='删除指标', description='接口描述', tags=['指标'])
def delete_indicator(_id: int, db: Session = Depends(get_db)):
return crud.delete_indicator(db=db, _id=_id)
# 编辑指标
@router.post("/edit/{indicator_id}/", response_model=schemas.Indicator, summary='编辑指标', description='接口描述', tags=['指标'])
def edit_indicator(_id: int, req_body: schemas.IndicatorEdit, db: Session = Depends(get_db)):
db_indicator = crud.get_indicator(db, _id)
if not db_indicator:
raise HTTPException(status_code=400, detail="Indicator not found")
return crud.edit_indicator(db=db, body=req_body, _id=_id)
# 查看指标
@router.get("/{indicator_id}/", response_model=schemas.Indicator, summary='查看指标', description='接口描述', tags=['指标'])
def read_indicator(indicator_id: int, db: Session = Depends(get_db)):
db_user = crud.get_indicator(db, _id=indicator_id)
if db_user is None:
raise HTTPException(status_code=404, detail="Indicator not found")
return db_user
# 查询指标
@router.post("/indicators/", response_model=List[schemas.Indicator], summary='查询指标', description='接口描述', tags=['指标'])
def read_indicators(req_body: schemas.IndicatorSearch, db: Session = Depends(get_db)):
indicators = crud.get_indicators(db, skip=req_body.skip, limit=req_body.limit)
return indicators
# 新建参数
@router.post("/parameters/{indicator_id}/create", response_model=schemas.Parameter, summary='新建参数', description='接口描述', tags=['指标参数'])
def create_parameters_for_indicator(_id: int, item: schemas.ParameterCreate, db: Session = Depends(get_db)):
return crud.create_indicator_parameters(db=db, item=item, _id=_id)
# 删除参数
@router.post("/parameters/{indicator_id}/delete", summary='删除参数', description='接口描述', tags=['指标参数'])
def delete_parameters_for_indicator(_id: int, db: Session = Depends(get_db)):
return crud.delete_indicator_parameters(db=db, _id=_id)
# 编辑参数
@router.post("/parameters/{indicator_id}/edit", summary='编辑参数', description='接口描述', tags=['指标参数'])
def edit_parameters_for_indicator(_id: int, req_body: schemas.ParameterEdit, db: Session = Depends(get_db)):
return crud.edit_indicator_parameters(db, _id, req_body)

29
Indicator/models.py Normal file
View File

@ -0,0 +1,29 @@
from sqlalchemy import Column, Integer, String, Enum, ForeignKey, Boolean
from sqlalchemy.orm import relationship
from sqlalchemy.dialects.mysql import LONGTEXT
from .database import Base
class Indicator(Base):
__tablename__ = "indicator"
id = Column(Integer, autoincrement=True, primary_key=True, index=True)
ename = Column(String(255), index=True)
cname = Column(String(255), index=True)
description = Column(LONGTEXT)
nature = Column(Enum('定性', '定量'))
category = Column(Enum('盈利能力', '收益质量', '现金流量', '资本结构', '偿债能力', '运营能力', '成长能力', '经营指标', '资质指标', '行业指标', '绿色指标', '司法指标', '合规指标', '舆情指标', '其他'))
is_active = Column(Boolean, default=True)
parameters = relationship("Parameters", back_populates="indicator")
class Parameters(Base):
__tablename__ = "parameters"
id = Column(Integer, autoincrement=True, primary_key=True, index=True)
ename = Column(String(255))
cname = Column(String(255))
description = Column(LONGTEXT)
indicator_id = Column(Integer, ForeignKey("indicator.id"))
indicator = relationship("Indicator", back_populates="parameters")

91
Indicator/schemas.py Normal file
View File

@ -0,0 +1,91 @@
import pydantic
from typing import List
from enum import Enum
from pydantic import BaseModel
ENameRegex = pydantic.constr(regex="^([A-Z][a-z0-9]+)+")
CNameRegex = pydantic.constr(regex="[\u4e00-\u9fa5]")
class ParameterBase(BaseModel):
ename: ENameRegex = "ExampleParameter"
cname: CNameRegex = "示例参数"
description: str = "参数介绍文字"
class ParameterCreate(ParameterBase):
pass
class ParameterEdit(ParameterBase):
pass
class Parameter(ParameterBase):
id: int
indicator_id: int
class Config:
orm_mode = True
class NatureEnum(Enum):
quantity = "定量"
qualitative = "定性"
class CategoryEnum(str, Enum):
profitability = "盈利能力"
quality_of_revenue = "收益质量"
cash_flows = "现金流量"
capital_structure = "资本结构"
solvency = "偿债能力"
operational_capability = "运营能力"
ability_to_grow = "成长能力"
operating_indicators = "经营指标"
qualification_indicators = "资质指标"
industry_indicators = "行业指标"
green_indicators = "绿色指标"
judicial_indicators = "司法指标"
compliance_indicators = "合规指标"
public_sentiment_indicators = "舆情指标"
others = "其他"
class IndicatorBase(BaseModel):
ename: ENameRegex = "ExampleIndicator"
cname: CNameRegex = "示例指标"
description: str = "指标介绍文字"
nature: NatureEnum
category: CategoryEnum
class IndicatorCreate(IndicatorBase):
pass
class IndicatorEdit(BaseModel):
cname: CNameRegex = "示例指标"
description: str = "指标介绍文字"
nature: NatureEnum
category: CategoryEnum
is_active: bool
class Config:
use_enum_values = True
class IndicatorSearch(BaseModel):
skip: int = 0
limit: int = 20
class Indicator(IndicatorBase):
id: int
is_active: bool
parameters: List[Parameter] = []
class Config:
orm_mode = True

View File

@ -1,92 +0,0 @@
# WR Index Store
WideRating指标仓库
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin http://gitlab.fecribd.com/root/wr-index-store.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](http://gitlab.fecribd.com/root/wr-index-store/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.

26
main.py Normal file
View File

@ -0,0 +1,26 @@
from fastapi import FastAPI, Header, Depends
from Indicator import indicator
app = FastAPI()
# async def get_token_header(authorization: str = Header(...)):
# """
# 获取Token并验证
# :param authorization:
# :return: openid
# """
# token = authorization.split(' ')[-1] # 获取token
# openid = auth_token(token) # 验证token
# if not openid:
# raise HTTPException(status_code=400, detail="无效Token")
# 游戏相关路由
app.include_router(
indicator.router,
prefix="/indicator_storehouse",
# dependencies=[Depends(get_token_header)],
responses={404: {"description": "Not found"}},
)

4
requirements.txt Normal file
View File

@ -0,0 +1,4 @@
fastapi~=0.85.0
pydantic~=1.10.2
SQLAlchemy~=1.4.41
PyMySQL~=1.0.2