Skip to content

Commit

Permalink
Merge pull request #13 from zy7y/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
zy7y authored Dec 30, 2023
2 parents 96bf0c8 + 9dab1e6 commit 2c99014
Show file tree
Hide file tree
Showing 11 changed files with 275 additions and 200 deletions.
23 changes: 23 additions & 0 deletions .github/workflows/python_pip.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: pip install check

on:
push:
branches:
- develop

jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ windows-latest, ubuntu-latest, macos-latest ]
python-version: [ "3.8", "3.9", "3.10", "3.11" ]
steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v3
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
pip install -r requirements.txt
57 changes: 57 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
name: release

on:
push:
tags:
- v*

jobs:

# 创建发布
release:
runs-on: ubuntu-latest
# 输出变量
outputs:
upload_url: ${{ steps.create_release.outputs.upload_url }}
steps:
- name: Create release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: Release ${{ github.ref }}
body: |
Release ${{ github.ref }}
draft: false
prerelease: false


# 打包上传
build-windows-app:
needs: release
runs-on: windows-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python 3.10
uses: actions/setup-python@v3
with:
python-version: "3.10"
- name: Install dependencies
run: |
pip install -r requirements.txt
- name: Build executable
run: |
pyinstaller --windowed --onefile main.py
- name: Upload executables
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.TOKEN }}
with:
# 获取变量
upload_url: ${{ needs.release.outputs.upload_url }}
asset_path: ./dist/main.exe
asset_name: dfs-generate.exe
asset_content_type: application/octet-stream
43 changes: 0 additions & 43 deletions db.py

This file was deleted.

104 changes: 104 additions & 0 deletions entity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import uuid
from typing import Generic, List, Optional, TypeVar

import black
import isort
from pydantic import BaseModel, ConfigDict, field_serializer
from pydantic.alias_generators import to_camel
from sqlmodel import Field, MetaData, Session, SQLModel, create_engine, select

db_uri = "sqlite:///main.sqlite"
engine = create_engine(db_uri)


def get_metadata_by_db_uri(uri: str):
db_engine = create_engine(uri)
db_metadata = MetaData()
db_metadata.reflect(bind=db_engine)
return db_metadata


class Conf(SQLModel, table=True):
__tablename__ = "dfs_conf"
id: int = Field(None, primary_key=True)
db_uri: str = Field(..., description="数据库连接")

@classmethod
def get_db_uri_last_new(cls):
"""获取最新的db_url"""
with Session(engine) as session:
query = select(cls).order_by(cls.id.desc())
latest_conf = session.exec(query).first()
if latest_conf:
return latest_conf.db_uri
else:
return None

@classmethod
def create(cls, uri) -> "Conf":
with Session(engine) as session:
obj = cls(db_uri=uri)
session.add(obj)
session.commit()
session.refresh(obj)
return obj

@classmethod
def get_last_uri_with_metadata(cls):
uri = cls.get_db_uri_last_new()
return uri, get_metadata_by_db_uri(uri)


T = TypeVar("T")


class R(BaseModel, Generic[T]):
code: int = 20000
msg: str = "ok"
data: Optional[T] = None

@classmethod
def success(cls, **kwargs):
return cls(**kwargs)

@classmethod
def error(cls, msg):
return cls(code=40000, msg=msg)


class RList(R[T]):
data: List[T] = Field(default_factory=list)


class BaseVo(SQLModel):
key: uuid.UUID = Field(default_factory=uuid.uuid4)
model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True)


class Table(BaseVo):
table_name: str
table_comment: Optional[str] = None


class DBConf(SQLModel):
user: str
password: str
port: int
host: str
db: str

def get_db_uri(self):
return f"mysql+pymysql://{self.user}:{self.password}@{self.host}:{self.port}/{self.db}"

def get_metadata(self):
return get_metadata_by_db_uri(self.get_db_uri())


class CodeGen(BaseVo):
name: str
code: str

@field_serializer("code")
def serialize_code(self, code: str, _info):
_code = black.format_str(code, mode=black.FileMode())
return isort.code(_code)
4 changes: 0 additions & 4 deletions generate/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +0,0 @@
from generate.db import render as db_code_render
from generate.main import render as main_render
from generate.model import GenerateEntity
from generate.router import render as router_render
12 changes: 0 additions & 12 deletions generate/db.py

This file was deleted.

78 changes: 75 additions & 3 deletions generate/main.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
template = """
from generate.model import GenerateEntity, Table, to_pascal

main_template = """
from fastapi import FastAPI
from fastapi.openapi.docs import get_swagger_ui_html
Expand All @@ -24,5 +26,75 @@ def docs():
"""


def render(table_name):
return template.format(table_name=table_name)
def render_main(table_name):
return main_template.format(table_name=table_name)


db_template = """
from sqlmodel import create_engine
db_uri = "{db_uri}"
engine = create_engine(db_uri)
"""


def render_db(db_uri):
"""数据库链接- sqlalchemy"""
return db_template.format(db_uri=db_uri)


router_template = """
from fastapi import APIRouter, Depends
from sqlmodel import Session
from model import {pascal_name}DTO, {pascal_name}, Result, PageResult, {pascal_name}Query
from db import engine
{table_name}_router = APIRouter(prefix="/{table_name}", tags=["{table_name}"])
@{table_name}_router.get("/{id}", summary="通过ID查询详情")
def query_{table_name}_by_id(id: int) -> Result[{pascal_name}]:
with Session(engine) as session:
return Result.ok({pascal_name}.query_by_id(session, id))
@{table_name}_router.get("", summary="分页条件查询")
def query_{table_name}_all_by_limit(query: {pascal_name}Query = Depends()) -> PageResult[{pascal_name}]:
with Session(engine) as session:
total = {pascal_name}.count(session, **query.count_kwargs(exclude_none=True))
data = {pascal_name}.query_all_by_limit(session, **query.model_dump(exclude_none=True))
return PageResult.ok(data=data, total=total)
@{table_name}_router.post("", summary="新增数据")
def create_{table_name}(instance: {pascal_name}DTO) -> Result[{pascal_name}]:
with Session(engine) as session:
return Result.ok({pascal_name}.create(session, instance))
@{table_name}_router.patch("/{id}", summary="更新数据")
def update_{table_name}_by_id(id: int, instance: {pascal_name}DTO) -> Result[{pascal_name}]:
with Session(engine) as session:
return Result.ok({pascal_name}.update(session, id, instance))
@{table_name}_router.delete("/{id}", summary="删除数据")
def delete_{table_name}_by_id(id: int) -> Result[{pascal_name}]:
with Session(engine) as session:
return Result.ok({pascal_name}.delete_by_id(session, id))
"""


def render_router(table_name):
router_code = router_template.format(
table_name=table_name, pascal_name=to_pascal(table_name), id="{id}"
)
return router_code


def generate_code(table: Table, uri: str):
return [
{"name": "model.py", "code": GenerateEntity(table).render()},
{"name": "router.py", "code": render_router(table.name)},
{"name": "main.py", "code": render_main(table.name)},
{"name": "db.py", "code": render_db(uri)},
]
47 changes: 0 additions & 47 deletions generate/router.py

This file was deleted.

Loading

0 comments on commit 2c99014

Please sign in to comment.