Browse Source

Некоторые изменения

master
VinokurovVE 8 months ago
parent
commit
9935c81d78
  1. 5
      .env.template
  2. 47
      main.py
  3. 3
      requirements.txt

5
.env.template

@ -1,5 +1,6 @@
DB_URL=mssql+pyodbc://{user}:{password}@{host}/{database_name}?driver=ODBC+Driver+17+for+SQL+Server
HOST=0.0.0.0
PORT=4444
SERVER_ROOT=
PREFIX=/agree
SERVER_ROOT=/lk/agreement
PREFIX=
URL=https://api.jkhsakha.ru

47
main.py

@ -1,6 +1,8 @@
from fastapi import FastAPI, APIRouter, Request, HTTPException
from fastapi import FastAPI, APIRouter, Request, HTTPException,Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import ORJSONResponse, HTMLResponse
from aiohttp import ClientSession
from fastapi.security import OAuth2PasswordBearer
from sqlmodel import create_engine, Field, SQLModel, UUID, DateTime, func, Column, text, bindparam
from sqlalchemy.dialects.mssql import UNIQUEIDENTIFIER, DATETIME
from sqlalchemy import insert
@ -12,7 +14,8 @@ import os
load_dotenv()
DB_URL = os.getenv("DB_URL")
SERVER_ROOT = os.getenv("SERVER_ROOT")
PREFIX = os.getenv("PREFIX")
PREFIX = (SERVER_ROOT if SERVER_ROOT else "") +os.getenv("PREFIX")
URL = os.getenv("URL")
db_engine = create_engine(DB_URL)
class Agreement(SQLModel,table=True):
@ -46,32 +49,30 @@ app.add_middleware(
allow_headers=["*"],
)
async def get_current_user(data: str = Depends(OAuth2PasswordBearer(tokenUrl=f"{URL}/auth/login/"))):
import json
async with ClientSession() as session:
response = await session.get(f"{URL}/auth/get_current_user/{data}")
data = await response.read()
return json.loads(data)
router = APIRouter(
prefix=PREFIX
prefix=PREFIX,
dependencies=[Depends(get_current_user)]
)
@app.get("/", response_class= HTMLResponse)
async def hello(request: Request):
return """
<html>
<head>
<title>Привет</title>
</head>
<body>
<h1>Это API, а не сайт!</h1>
</body>
</html>
"""
@router.get('/')
async def get_ageement(id_account: Optional[UUID] = None) -> Sequence[Agreement]:
async def get_ageements(id_account: Optional[UUID] = None) -> Sequence[Agreement]:
with db_engine.begin() as con:
query = text("SELECT * FROM agreement WHERE id_account=:id_account").params({"id_account":id_account})
if id_account:
query = text("SELECT * FROM agreement WHERE id_account=:id_account").params({"id_account":id_account})
else:
query = text("SELECT * FROM agreement")
return con.execute(query).fetchall()
@router.delete("/")
async def delete_pk(acc_list: Sequence[UUID]):
async def delete_agreements(acc_list: Sequence[UUID]):
if acc_list:
with db_engine.begin() as con:
stmt = text("DELETE agreement WHERE id_account IN :acc_list")
@ -82,8 +83,8 @@ async def delete_pk(acc_list: Sequence[UUID]):
raise HTTPException(405,"list is empty")
@router.post("/")
async def add_agreement(agrees: Sequence[AgreementCreate]):
if acc_list:
async def add_agreements(agrees: Sequence[AgreementCreate]):
if agrees:
with db_engine.begin() as con:
dict_list=[]
acc_list = []
@ -93,7 +94,7 @@ async def add_agreement(agrees: Sequence[AgreementCreate]):
acc_id = agree_dict.get("id_account")
if acc_id not in acc_list:
acc_list.append(acc_id)
await delete_pk(acc_list)
await delete_agreements(acc_list)
stmt = insert(Agreement).values(dict_list)
con.execute(stmt)
con.commit()
@ -106,5 +107,5 @@ if __name__ == "__main__":
uvicorn.run(
app,
host=os.getenv("HOST"),
port=int(os.getenv("PORT"))
port=int(os.getenv("PORT")),
)

3
requirements.txt

@ -3,4 +3,5 @@ uvicorn
sqlmodel
pyodbc
python-dotenv
orjson
orjson
aiohttp
Loading…
Cancel
Save