From 0df1d506125cb874a325c1e2092ea830f3436e5b Mon Sep 17 00:00:00 2001 From: dm1sh Date: Fri, 8 Sep 2023 19:40:29 +0300 Subject: [PATCH] Added config loading from .env file --- back/add_poems_and_filters.py | 5 ----- back/api.py | 13 ++++--------- back/auth_utils.py | 11 ++--------- back/config.py | 13 +++++++++++++ back/db.py | 4 ++-- requirements.txt | 1 + 6 files changed, 22 insertions(+), 25 deletions(-) create mode 100644 back/config.py diff --git a/back/add_poems_and_filters.py b/back/add_poems_and_filters.py index 67847f3..9380918 100644 --- a/back/add_poems_and_filters.py +++ b/back/add_poems_and_filters.py @@ -7,11 +7,6 @@ from sqlalchemy import select, or_, and_ from . import auth_utils, orm_models, pydantic_schemas import datetime -# Переменные для получения данных о мусорках с внешнего API -# url API -BASE_URL='https://geointelect2.gate.petersburg.ru'#адрес сайта и мой токин -# токен для получения данных -my_token='eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJhU1RaZm42bHpTdURYcUttRkg1SzN5UDFhT0FxUkhTNm9OendMUExaTXhFIn0.eyJleHAiOjE3ODM3ODk4NjgsImlhdCI6MTY4OTA5NTQ2OCwianRpIjoiNDUzNjQzZTgtYTkyMi00NTI4LWIzYmMtYWJiYTNmYjkyNTkxIiwiaXNzIjoiaHR0cHM6Ly9rYy5wZXRlcnNidXJnLnJ1L3JlYWxtcy9lZ3MtYXBpIiwiYXVkIjoiYWNjb3VudCIsInN1YiI6ImJjYjQ2NzljLTU3ZGItNDU5ZC1iNWUxLWRlOGI4Yzg5MTMwMyIsInR5cCI6IkJlYXJlciIsImF6cCI6ImFkbWluLXJlc3QtY2xpZW50Iiwic2Vzc2lvbl9zdGF0ZSI6ImM2ZDJiOTZhLWMxNjMtNDAxZS05ZjMzLTI0MmE0NDcxMDY5OCIsImFjciI6IjEiLCJhbGxvd2VkLW9yaWdpbnMiOlsiLyoiXSwicmVhbG1fYWNjZXNzIjp7InJvbGVzIjpbImRlZmF1bHQtcm9sZXMtZWdzLWFwaSIsIm9mZmxpbmVfYWNjZXNzIiwidW1hX2F1dGhvcml6YXRpb24iXX0sInJlc291cmNlX2FjY2VzcyI6eyJhY2NvdW50Ijp7InJvbGVzIjpbIm1hbmFnZS1hY2NvdW50IiwibWFuYWdlLWFjY291bnQtbGlua3MiLCJ2aWV3LXByb2ZpbGUiXX19LCJzY29wZSI6ImVtYWlsIHByb2ZpbGUiLCJzaWQiOiJjNmQyYjk2YS1jMTYzLTQwMWUtOWYzMy0yNDJhNDQ3MTA2OTgiLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsIm5hbWUiOiLQktC70LDQtNC40LzQuNGAINCv0LrQvtCy0LvQtdCyIiwicHJlZmVycmVkX3VzZXJuYW1lIjoiZTBmYzc2OGRhOTA4MjNiODgwZGQzOGVhMDJjMmQ5NTciLCJnaXZlbl9uYW1lIjoi0JLQu9Cw0LTQuNC80LjRgCIsImZhbWlseV9uYW1lIjoi0K_QutC-0LLQu9C10LIifQ.E2bW0B-c6W5Lj63eP_G8eI453NlDMnW05l11TZT0GSsAtGayXGaolHtWrmI90D5Yxz7v9FGkkCmcUZYy1ywAdO9dDt_XrtFEJWFpG-3csavuMjXmqfQQ9SmPwDw-3toO64NuZVv6qVqoUlPPj57sLx4bLtVbB4pdqgyJYcrDHg7sgwz4d1Z3tAeUfSpum9s5ZfELequfpLoZMXn6CaYZhePaoK-CxeU3KPBPTPOVPKZZ19s7QY10VdkxLULknqf9opdvLs4j8NMimtwoIiHNBFlgQz10Cr7bhDKWugfvSRsICouniIiBJo76wrj5T92s-ztf1FShJuqnQcKE_QLd2A' # Загружаем стихи async def add_poems_to_db(async_db: AsyncSession): diff --git a/back/api.py b/back/api.py index c29b676..2a038c0 100644 --- a/back/api.py +++ b/back/api.py @@ -11,7 +11,6 @@ from typing import Any, Annotated, List, Union from starlette.staticfiles import StaticFiles from sqlalchemy.orm import Session from sqlalchemy import select -from dotenv import load_dotenv, dotenv_values import requests from uuid import uuid4 @@ -26,6 +25,8 @@ import os from . import add_poems_and_filters, auth_utils, orm_models, pydantic_schemas +from .config import TRASHBOXES_BASE_URL, TRASHBOXES_TOKEN + # создаем приложение Fastapi app = FastAPI() @@ -42,10 +43,6 @@ if not os.path.exists("./uploads"): # создаем эндпоинт для хранения файлов пользователя app.mount("/uploads", StaticFiles(directory = "./uploads")) -# load_dotenv("unimportant.env") -# ACCESS_TOKEN_EXPIRE_MINUTES = os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES") -ACCESS_TOKEN_EXPIRE_MINUTES = 1440 - # эндпоинт для возвращения согласия в pdf @app.get("/privacy_policy.pdf") async def privacy_policy(): @@ -247,9 +244,7 @@ async def poems_to_front(db: Annotated[Session, Depends(auth_utils.get_session)] @app.get("/api/trashbox", response_model=List[pydantic_schemas.TrashboxResponse]) async def get_trashboxes(data: pydantic_schemas.TrashboxRequest = Depends()):#крутая функция для работы с api # json, передаваемый стороннему API - BASE_URL= "https://geointelect2.gate.petersburg.ru" - my_token="eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJhU1RaZm42bHpTdURYcUttRkg1SzN5UDFhT0FxUkhTNm9OendMUExaTXhFIn0.eyJleHAiOjE3ODgzODM1NzQsImlhdCI6MTY5MzY4OTE3NCwianRpIjoiNTIxNTE4ODYtZjJiMy00MWQ2LWE2OTYtN2JjNjg1YzRmZDBjIiwiaXNzIjoiaHR0cHM6Ly9rYy5wZXRlcnNidXJnLnJ1L3JlYWxtcy9lZ3MtYXBpIiwiYXVkIjoiYWNjb3VudCIsInN1YiI6ImJjYjQ2NzljLTU3ZGItNDU5ZC1iNWUxLWRlOGI4Yzg5MTMwMyIsInR5cCI6IkJlYXJlciIsImF6cCI6ImFkbWluLXJlc3QtY2xpZW50Iiwic2Vzc2lvbl9zdGF0ZSI6IjMyNmZlYjNjLWJhMDktNDU4NC05M2JiLTgzZjMyMTRjOTdkNSIsImFjciI6IjEiLCJhbGxvd2VkLW9yaWdpbnMiOlsiLyoiXSwicmVhbG1fYWNjZXNzIjp7InJvbGVzIjpbImRlZmF1bHQtcm9sZXMtZWdzLWFwaSIsIm9mZmxpbmVfYWNjZXNzIiwidW1hX2F1dGhvcml6YXRpb24iXX0sInJlc291cmNlX2FjY2VzcyI6eyJhY2NvdW50Ijp7InJvbGVzIjpbIm1hbmFnZS1hY2NvdW50IiwibWFuYWdlLWFjY291bnQtbGlua3MiLCJ2aWV3LXByb2ZpbGUiXX19LCJzY29wZSI6ImVtYWlsIHByb2ZpbGUiLCJzaWQiOiIzMjZmZWIzYy1iYTA5LTQ1ODQtOTNiYi04M2YzMjE0Yzk3ZDUiLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsIm5hbWUiOiLQktC70LDQtNC40LzQuNGAINCv0LrQvtCy0LvQtdCyIiwicHJlZmVycmVkX3VzZXJuYW1lIjoiZTBmYzc2OGRhOTA4MjNiODgwZGQzOGVhMDJjMmQ5NTciLCJnaXZlbl9uYW1lIjoi0JLQu9Cw0LTQuNC80LjRgCIsImZhbWlseV9uYW1lIjoi0K_QutC-0LLQu9C10LIifQ.SpFC8EufKYV4tHWSvaeypZ-j-Lqhpva3tvilMba_Yh79EzT1EUOomeT5pC7PNJPlfsuXvOyutPBXG9Fpo7tazY2K5ymxQubYrsYt1m6KrPAJYAvDVGiZl5762-7zH1NoENgxLOjNc8eqN_cZBlcqImPyGiGAIqXaZ_Bwns-Jx5qHrYipFOQ3yXtehvy8-l84ZFhO0VhUHoZZnlfXz5x3OuOTVLU1-NjUclZEYc7t3ZlOl5m-r8jAfAdTnY-V-JDfLMbwqjouAAzauUNm4-1uiZjntrShuBsYoJcVaXcW8cSWnVk5NgWQNxwHoel4AhGIGBWPQ6gmJw2jkXBBjzXbqA" - head = {'Authorization': 'Bearer {}'.format(my_token)} + head = {'Authorization': 'Bearer ' + TRASHBOXES_TOKEN} # Данные пользователя (местоположение, количество мусорок, которое пользователь хочет видеть) my_data={ 'x' : f"{data.Lng}", @@ -276,7 +271,7 @@ async def get_trashboxes(data: pydantic_schemas.TrashboxRequest = Depends()):#к list_of_category = ["Металл", "Бумага", "Стекло", "Иное", "Тетра Пак", "Батарейки", "Крышечки", "Шины", "Опасные отходы", "Лампочки", "Пластик"] # Получение ответа от стороннего апи - response = requests.post(f"{BASE_URL}/nearest_recycling/get", headers=head, data=my_data, timeout=10) + response = requests.post(TRASHBOXES_BASE_URL + "/nearest_recycling/get", headers=head, data=my_data, timeout=10) infos = response.json() # Чтение ответа trashboxes = [] diff --git a/back/auth_utils.py b/back/auth_utils.py index 9a34646..942bc4a 100644 --- a/back/auth_utils.py +++ b/back/auth_utils.py @@ -1,6 +1,5 @@ from datetime import datetime, timedelta from typing import Annotated, Union -import os from fastapi import Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer @@ -9,18 +8,12 @@ from passlib.context import CryptContext from sqlalchemy import select from sqlalchemy.orm import Session from sqlalchemy.ext.asyncio import AsyncSession -from dotenv import load_dotenv from .db import SessionLocal from . import orm_models, pydantic_schemas +from .config import SECRET_KEY, ALGORITHM, ACCESS_TOKEN_EXPIRE_MINUTES + -# load_dotenv("unimportant.env") -# SECRET_KEY = os.getenv("SECRET_KEY") -# ALGORITHM = os.getenv("ALGORITHM") -# ACCESS_TOKEN_EXPIRE_MINUTES = os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES") -ACCESS_TOKEN_EXPIRE_MINUTES = 1440 -SECRET_KEY = "651a52941cf5de14d48ef5d7af115709" -ALGORITHM = "HS256" pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/token") diff --git a/back/config.py b/back/config.py new file mode 100644 index 0000000..3c90b68 --- /dev/null +++ b/back/config.py @@ -0,0 +1,13 @@ +import os +from dotenv import load_dotenv + +load_dotenv('.env') + +TRASHBOXES_TOKEN = os.environ.get("TRASHBOXES_TOKEN") +TRASHBOXES_BASE_URL = os.environ.get("TRASHBOXES_BASE_URL") + +SECRET_KEY = os.environ.get("SECRET_KEY") +ALGORITHM = os.environ.get("ALGORITHM") +ACCESS_TOKEN_EXPIRE_MINUTES = int(os.environ.get("ACCESS_TOKEN_EXPIRE_MINUTES")) + +SQLALCHEMY_DATABASE_URL = os.environ.get("SQLALCHEMY_DATABASE_URL") \ No newline at end of file diff --git a/back/db.py b/back/db.py index 132e973..6e13214 100644 --- a/back/db.py +++ b/back/db.py @@ -3,8 +3,8 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_scoped_session, create_as from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base -SQLALCHEMY_DATABASE_URL = "sqlite+aiosqlite:///./sql_app.db" -# SQLALCHEMY_DATABASE_URL = "postgresql+asyncpg://postgres:D560c34V112Ak@localhost/porridger" +from .config import SQLALCHEMY_DATABASE_URL + engine = create_async_engine(SQLALCHEMY_DATABASE_URL) SessionLocal = sessionmaker(bind=engine, class_=AsyncSession, expire_on_commit=False) diff --git a/requirements.txt b/requirements.txt index 9c3358a..2ac0161 100644 --- a/requirements.txt +++ b/requirements.txt @@ -17,6 +17,7 @@ pyasn1==0.5.0 pydantic==1.10.10 pydantic_core==2.4.0 python-dateutil==2.8.2 +python-dotenv==1.0.0 python-jose==3.3.0 python-multipart==0.0.6 redbird==0.7.1