Skip to content

Commit a601ed4

Browse files
Merge pull request #43 from devind-team/develop
Develop
2 parents 45c1e55 + 9f0f672 commit a601ed4

13 files changed

Lines changed: 623 additions & 75 deletions

File tree

.editorconfig

Lines changed: 442 additions & 0 deletions
Large diffs are not rendered by default.

.flake8

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22
max-line-length = 120
33
per-file-ignores =
44
__init__.py:F401
5-
ignore = F401, SC200, ANN002, ANN003, ANN001, I100
5+
ignore = F401, SC200, ANN002, ANN003, ANN001, ANN101, I100, I201, I202
66
exclude = .git,.github,.venv,__pycache__,migrations,docs
77
# ignore = ANN001, ANN002, ANN003, ANN101,ANN102, ANN206, D107
88
import-order-style = pycharm
9-
dictionaries=en_US,python,technical,django
9+
dictionaries=en_US,python,technical,django

.github/workflows/build.yml

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
name: Build
22
on:
3-
push:
4-
branches:
5-
- main
3+
workflow_run:
4+
workflows:
5+
- Lint
6+
types:
7+
- completed
68

79
env:
810
REGISTRY: ghcr.io
@@ -65,4 +67,4 @@ jobs:
6567
context: .
6668
push: true
6769
tags: ${{ steps.meta.outputs.tags }}
68-
labels: ${{ steps.meta.outputs.labels }}
70+
labels: ${{ steps.meta.outputs.labels }}

.github/workflows/lint.yml

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
name: Lint
2+
on:
3+
pull_request:
4+
branches:
5+
- main
6+
7+
jobs:
8+
lint:
9+
name: Lint Code Base
10+
runs-on: ubuntu-latest
11+
steps:
12+
- name: Checkout Code
13+
uses: actions/checkout@v3
14+
with:
15+
fetch-depth: 0
16+
17+
- name: Lint Code Base
18+
uses: github/super-linter@v4
19+
env:
20+
VALIDATE_ALL_CODEBASE: false
21+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
22+
DEFAULT_BRANCH: main
23+
EDITORCONFIG_FILE_NAME: .editorconfig
24+
VALIDATE_EDITORCONFIG: true

.github/workflows/release.yml

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
name: Release
2+
on:
3+
push:
4+
branches:
5+
- main
6+
7+
env:
8+
REGISTRY: ghcr.io
9+
IMAGE_NAME: ${{ github.repository }}
10+
11+
jobs:
12+
release:
13+
name: release
14+
runs-on: ubuntu-latest
15+
steps:
16+
- uses: actions/checkout@v3
17+
- name: Bump version and push tag
18+
id: tag_version
19+
uses: mathieudutour/github-tag-action@v6.0
20+
with:
21+
github_token: ${{ secrets.GITHUB_TOKEN }}
22+
- name: Create a GitHub release
23+
uses: ncipollo/release-action@v1
24+
with:
25+
token: ${{ secrets.GITHUB_TOKEN }}
26+
draft: false
27+
allowUpdates: true
28+
tag: ${{ steps.tag_version.outputs.new_tag }}
29+
name: Release ${{ steps.tag_version.outputs.new_tag }}
30+
body: ${{ steps.tag_version.outputs.changelog }}
31+
bodyFile: CHANGELOG.md
32+
generateReleaseNotes: true
33+
outputs:
34+
tag: ${{ steps.tag_version.outputs.new_tag }}

database.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
"""Открытие соединения с базой данных."""
22
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
33
from sqlalchemy.orm import sessionmaker
4-
from sqlmodel import SQLModel # noqa
4+
from sqlmodel import SQLModel
5+
6+
from settings import get_settings
57

6-
from settings import get_settings # noqa
78

89
engine = create_async_engine(
910
get_settings().db_sync_connections, echo=True, future=True

main.py

Lines changed: 70 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,16 @@
1111
from sqlalchemy.ext.asyncio import AsyncSession
1212
from sqlalchemy.sql import select
1313

14-
from database import get_session # noqa
14+
from database import get_session # noqa
1515
from models import Email, Site, Traffic
1616
from services.network_load import interest_calculation
1717
from settings import SECRET_KEY
1818

19+
1920
app = FastAPI()
2021

2122
origins = ['*']
2223

23-
2424
app.add_middleware(
2525
CORSMiddleware,
2626
allow_origins=origins,
@@ -34,41 +34,47 @@
3434

3535
@app.get('/')
3636
async def redirect_page_docs() -> RedirectResponse:
37-
"""FastAPI - Swagger UI."""
37+
"""FastAPI - Swagger UI.""" # noqa: D403
3838
return RedirectResponse('/docs#/')
3939

4040

4141
@app.post('/traffic/', response_model=Traffic)
42-
async def calculate(identification: str, session: AsyncSession = Depends(get_session)): # noqa
42+
async def calculate(identification: str, session: AsyncSession = Depends(get_session)): # noqa
4343
"""Функция на обновление счетчика в базе данных."""
4444
site = (await session.execute(select(Site).where(Site.identification == identification))).first()[0]
4545
if site is None:
4646
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='Запрашиваемый ключ доступа не найден')
47-
traffic = (await session.execute(select(Traffic).
48-
where(Traffic.site_id == site.id).
49-
where(Traffic.create_at == date.today()))).first()
47+
traffic = (await session.execute(
48+
select(Traffic).
49+
where(Traffic.site_id == site.id).
50+
where(Traffic.create_at == date.today())
51+
)).first()
5052
if traffic:
51-
await session.execute(update(Traffic).
52-
where(Traffic.id == traffic[0].id).
53-
values(id=traffic[0].id,
54-
counter=Traffic.counter + 1,
55-
))
53+
await session.execute(
54+
update(Traffic).
55+
where(Traffic.id == traffic[0].id).
56+
values(
57+
id=traffic[0].id,
58+
counter=Traffic.counter + 1,
59+
)
60+
)
5661
await session.commit()
5762
return traffic[0]
5863
network_load = interest_calculation()
59-
traffic_id = (await session.execute(insert(Traffic).values(
60-
counter=1,
61-
create_at=date.today(),
62-
site_id=site.id,
63-
average_load=network_load['average_load'],
64-
maximum_load=network_load['maximum_load'],)
64+
traffic_id = (await session.execute(
65+
insert(Traffic).values(
66+
counter=1,
67+
create_at=date.today(),
68+
site_id=site.id,
69+
average_load=network_load['average_load'],
70+
maximum_load=network_load['maximum_load'], )
6571
)).inserted_primary_key[0]
6672
await session.commit()
6773
return (await session.execute(select(Traffic).where(Traffic.id == traffic_id))).first()[0]
6874

6975

70-
@app.get('/traffic/{token_access}', response_model=Site) # noqa
71-
async def verify_token_access(token_access: str): # noqa
76+
@app.get('/traffic/{token_access}', response_model=Site) # noqa
77+
async def verify_token_access(token_access: str): # noqa
7278
"""Функция проверки доступа."""
7379
if token_access == SECRET_KEY:
7480
return RedirectResponse('/identification_site/')
@@ -77,44 +83,69 @@ async def verify_token_access(token_access: str): # noqa
7783

7884

7985
@app.get('/identification_site/')
80-
async def form_send(request: Request): # noqa
86+
async def form_send(request: Request): # noqa
8187
"""Функция получения идентификатора сайта."""
8288
return templates.TemplateResponse('post_identification.html', {'request': request})
8389

8490

8591
@app.post('/identification/', response_model=Site)
8692
async def generate_secret_key(
87-
website_url: str = Form(...),
88-
secret_key: str = Form(...),
89-
list_email: str = Form(...),
90-
session: AsyncSession = Depends(get_session)): # noqa
93+
website_url: str = Form(...),
94+
secret_key: str = Form(...),
95+
list_email: str = Form(...),
96+
session: AsyncSession = Depends(get_session)
97+
): # noqa
9198
"""Функция добавления сайта для отслеживания."""
9299
verify_site = (await session.execute(select(Site).where(Site.site_name == website_url))).first()
93100
if verify_site is None:
94101
email_id = (await session.execute(insert(Email).values(name=list_email))).inserted_primary_key[0]
95102
await session.commit()
96-
site_id = (await session.execute(insert(Site).values(site_name=website_url,
97-
identification=secret_key,
98-
email_id=email_id))).inserted_primary_key[0]
103+
site_id = (await session.execute(
104+
insert(Site).values(
105+
site_name=website_url,
106+
identification=secret_key,
107+
email_id=email_id
108+
)
109+
)).inserted_primary_key[0]
99110
await session.commit()
100-
return JSONResponse(content=jsonable_encoder((await session.execute(select(Site).
101-
where(Site.id == site_id))).first()))
102-
return JSONResponse(content=jsonable_encoder((await session.execute(select(Site).
103-
where(Site.site_name == website_url))).first()))
111+
return JSONResponse(
112+
content=jsonable_encoder(
113+
(await session.execute(
114+
select(Site).
115+
where(Site.id == site_id)
116+
)).first()
117+
)
118+
)
119+
return JSONResponse(
120+
content=jsonable_encoder(
121+
(await session.execute(
122+
select(Site).
123+
where(Site.site_name == website_url)
124+
)).first()
125+
)
126+
)
104127

105128

106-
@app.get('/info/{identification_site}', response_model=Traffic, response_class=HTMLResponse) # noqa
107-
async def infi_traffic(identification_site: str, request: Request, session: AsyncSession = Depends(get_session)): # noqa
129+
@app.get('/info/{identification_site}', response_model=Traffic, response_class=HTMLResponse) # noqa
130+
async def infi_traffic(
131+
identification_site: str,
132+
request: Request,
133+
session: AsyncSession = Depends(get_session)
134+
): # noqa
108135
"""Функция получения параметров сайта."""
109136
site = (await session.execute(select(Site).where(Site.identification == identification_site))).first()[0]
110137
if site is None:
111138
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='Запрашиваемый ключ доступа не найден')
112-
traffic_site = (await session.execute(select(Traffic).
113-
where(Traffic.site_id == site.id).
114-
where(Traffic.create_at == date.today()))).first()
139+
traffic_site = (await session.execute(
140+
select(Traffic).
141+
where(Traffic.site_id == site.id).
142+
where(Traffic.create_at == date.today())
143+
)).first()
115144
if traffic_site is None:
116-
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Мониторинг сайта {site.site_name} '
117-
f'за эту дату не производился')
145+
raise HTTPException(
146+
status_code=status.HTTP_404_NOT_FOUND, detail=f'Мониторинг сайта {site.site_name} '
147+
f'за эту дату не производился'
148+
)
118149
return templates.TemplateResponse(
119150
'statistics.html',
120151
{

models.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,23 +19,24 @@ class TrafficBase(SQLModel):
1919
class Traffic(TrafficBase, table=True):
2020
"""Модель Traffic."""
2121

22-
id: int = Field(default=None, primary_key=True) # noqa
22+
id: int = Field(default=None, primary_key=True) # noqa
2323

2424

2525
class SiteBase(SQLModel):
2626
"""Базовая модель Site."""
2727

2828
identification: str = Field(
2929
sa_column=Column('identification', String, unique=True, nullable=False),
30-
title='Индентификатор сайта')
30+
title='Индентификатор сайта'
31+
)
3132
site_name: str = Field(sa_column=Column('site_name', String, unique=True, nullable=False), title='URL сайта')
3233
email_id: int = Field(default=None, foreign_key='email.id', nullable=False)
3334

3435

3536
class Site(SiteBase, table=True):
3637
"""Модель Site."""
3738

38-
id: int = Field(default=None, primary_key=True) # noqa
39+
id: int = Field(default=None, primary_key=True) # noqa
3940

4041

4142
class EmailBase(SQLModel):
@@ -47,4 +48,4 @@ class EmailBase(SQLModel):
4748
class Email(EmailBase, table=True):
4849
"""Модель Email."""
4950

50-
id: int = Field(default=None, primary_key=True) # noqa
51+
id: int = Field(default=None, primary_key=True) # noqa

services/generate_word.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
from docxtpl import DocxTemplate
66

7-
from settings import get_settings # noqa
7+
from settings import get_settings # noqa
88

99

1010
def create_report(counter: int, avg_load: float, max_load: float, site_name: str) -> str:
@@ -20,7 +20,9 @@ def create_report(counter: int, avg_load: float, max_load: float, site_name: str
2020
}
2121
)
2222
current_date = (date.today() - timedelta(days=1)).strftime('%d-%m-%Y')
23-
path_report = join(get_settings().static_dir, f'{current_date}-'
24-
f"{site_name.replace('/', '').replace('https:', '')}.docx")
23+
path_report = join(
24+
get_settings().static_dir, f'{current_date}-'
25+
f"{site_name.replace('/', '').replace('https:', '')}.docx"
26+
)
2527
template_word.save(path_report)
2628
return path_report

services/send_email.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,15 @@
77

88

99
async def generate_message(
10-
login: str,
11-
password: str,
12-
sender: str,
13-
receivers: str,
14-
attachment_path: str,
15-
smtp_server: str,
16-
port: int,
17-
site_name: str) -> None:
10+
login: str,
11+
password: str,
12+
sender: str,
13+
receivers: str,
14+
attachment_path: str,
15+
smtp_server: str,
16+
port: int,
17+
site_name: str
18+
) -> None:
1819
"""Функция оформления письма и прикрепление файла для отправки на почту."""
1920
current_date = (date.today() - timedelta(days=1)).strftime('%d-%m-%Y')
2021
message = MIMEMultipart()

0 commit comments

Comments
 (0)