Projekt

Obecné

Profil

« Předchozí | Další » 

Revize d446b62c

Přidáno uživatelem Matěj Zeman před více než 2 roky(ů)

re #9304 HelloWorld API for sending data defined in USBLog class. Returns simple sucess message

Zobrazit rozdíly:

.gitignore
1
# Created by https://www.toptal.com/developers/gitignore/api/python,pycharm
2
# Edit at https://www.toptal.com/developers/gitignore?templates=python,pycharm
3

  
4
### PyCharm ###
5
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
6
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
7

  
8
# User-specific stuff
9
.idea/**/workspace.xml
10
.idea/**/tasks.xml
11
.idea/**/usage.statistics.xml
12
.idea/**/dictionaries
13
.idea/**/shelf
14

  
15
# AWS User-specific
16
.idea/**/aws.xml
17

  
18
# Generated files
19
.idea/**/contentModel.xml
20

  
21
# Sensitive or high-churn files
22
.idea/**/dataSources/
23
.idea/**/dataSources.ids
24
.idea/**/dataSources.local.xml
25
.idea/**/sqlDataSources.xml
26
.idea/**/dynamic.xml
27
.idea/**/uiDesigner.xml
28
.idea/**/dbnavigator.xml
29

  
30
# Gradle
31
.idea/**/gradle.xml
32
.idea/**/libraries
33

  
34
# Gradle and Maven with auto-import
35
# When using Gradle or Maven with auto-import, you should exclude module files,
36
# since they will be recreated, and may cause churn.  Uncomment if using
37
# auto-import.
38
# .idea/artifacts
39
# .idea/compiler.xml
40
# .idea/jarRepositories.xml
41
# .idea/modules.xml
42
# .idea/*.iml
43
# .idea/modules
44
# *.iml
45
# *.ipr
46

  
47
# CMake
48
cmake-build-*/
49

  
50
# Mongo Explorer plugin
51
.idea/**/mongoSettings.xml
52

  
53
# File-based project format
54
*.iws
55

  
56
# IntelliJ
57
out/
58

  
59
# mpeltonen/sbt-idea plugin
60
.idea_modules/
61

  
62
# JIRA plugin
63
atlassian-ide-plugin.xml
64

  
65
# Cursive Clojure plugin
66
.idea/replstate.xml
67

  
68
# SonarLint plugin
69
.idea/sonarlint/
70

  
71
# Crashlytics plugin (for Android Studio and IntelliJ)
72
com_crashlytics_export_strings.xml
73
crashlytics.properties
74
crashlytics-build.properties
75
fabric.properties
76

  
77
# Editor-based Rest Client
78
.idea/httpRequests
79

  
80
# Android studio 3.1+ serialized cache file
81
.idea/caches/build_file_checksums.ser
82

  
83
### PyCharm Patch ###
84
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
85

  
86
# *.iml
87
# modules.xml
88
# .idea/misc.xml
89
# *.ipr
90

  
91
# Sonarlint plugin
92
# https://plugins.jetbrains.com/plugin/7973-sonarlint
93
.idea/**/sonarlint/
94

  
95
# SonarQube Plugin
96
# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin
97
.idea/**/sonarIssues.xml
98

  
99
# Markdown Navigator plugin
100
# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced
101
.idea/**/markdown-navigator.xml
102
.idea/**/markdown-navigator-enh.xml
103
.idea/**/markdown-navigator/
104

  
105
# Cache file creation bug
106
# See https://youtrack.jetbrains.com/issue/JBR-2257
107
.idea/$CACHE_FILE$
108

  
109
# CodeStream plugin
110
# https://plugins.jetbrains.com/plugin/12206-codestream
111
.idea/codestream.xml
112

  
113
### Python ###
114
# Byte-compiled / optimized / DLL files
115
__pycache__/
116
*.py[cod]
117
*$py.class
118

  
119
# C extensions
120
*.so
121

  
122
# Distribution / packaging
123
.Python
124
build/
125
develop-eggs/
126
dist/
127
downloads/
128
eggs/
129
.eggs/
130
lib/
131
lib64/
132
parts/
133
sdist/
134
var/
135
wheels/
136
share/python-wheels/
137
*.egg-info/
138
.installed.cfg
139
*.egg
140
MANIFEST
141

  
142
# PyInstaller
143
#  Usually these files are written by a python script from a template
144
#  before PyInstaller builds the exe, so as to inject date/other infos into it.
145
*.manifest
146
*.spec
147

  
148
# Installer logs
149
pip-log.txt
150
pip-delete-this-directory.txt
151

  
152
# Unit test / coverage reports
153
htmlcov/
154
.tox/
155
.nox/
156
.coverage
157
.coverage.*
158
.cache
159
nosetests.xml
160
coverage.xml
161
*.cover
162
*.py,cover
163
.hypothesis/
164
.pytest_cache/
165
cover/
166

  
167
# Translations
168
*.mo
169
*.pot
170

  
171
# Django stuff:
172
*.log
173
local_settings.py
174
db.sqlite3
175
db.sqlite3-journal
176

  
177
# Flask stuff:
178
instance/
179
.webassets-cache
180

  
181
# Scrapy stuff:
182
.scrapy
183

  
184
# Sphinx documentation
185
docs/_build/
186

  
187
# PyBuilder
188
.pybuilder/
189
target/
190

  
191
# Jupyter Notebook
192
.ipynb_checkpoints
193

  
194
# IPython
195
profile_default/
196
ipython_config.py
197

  
198
# pyenv
199
#   For a library or package, you might want to ignore these files since the code is
200
#   intended to run in multiple environments; otherwise, check them in:
201
# .python-version
202

  
203
# pipenv
204
#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
205
#   However, in case of collaboration, if having platform-specific dependencies or dependencies
206
#   having no cross-platform support, pipenv may install dependencies that don't work, or not
207
#   install all needed dependencies.
208
#Pipfile.lock
209

  
210
# poetry
211
#   Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
212
#   This is especially recommended for binary packages to ensure reproducibility, and is more
213
#   commonly ignored for libraries.
214
#   https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
215
#poetry.lock
216

  
217
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
218
__pypackages__/
219

  
220
# Celery stuff
221
celerybeat-schedule
222
celerybeat.pid
223

  
224
# SageMath parsed files
225
*.sage.py
226

  
227
# Environments
228
.env
229
.venv
230
env/
231
venv/
232
ENV/
233
env.bak/
234
venv.bak/
235

  
236
# Spyder project settings
237
.spyderproject
238
.spyproject
239

  
240
# Rope project settings
241
.ropeproject
242

  
243
# mkdocs documentation
244
/site
245

  
246
# mypy
247
.mypy_cache/
248
.dmypy.json
249
dmypy.json
250

  
251
# Pyre type checker
252
.pyre/
253

  
254
# pytype static type analyzer
255
.pytype/
256

  
257
# Cython debug symbols
258
cython_debug/
259

  
260
# PyCharm
261
#  JetBrains specific template is maintained in a separate JetBrains.gitignore that can
262
#  be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
263
#  and can be added to the global gitignore or merged into this file.  For a more nuclear
264
#  option (not recommended) you can uncomment the following to ignore the entire idea folder.
265
#.idea/
266

  
267
# End of https://www.toptal.com/developers/gitignore/api/python,pycharm
server/sql_app/crud.py
1
from sqlalchemy.orm import Session
2

  
3
from . import models, schemas
4

  
5

  
6
def get_device(db: Session, device_id: int):
7
    return db.query(models.Device).filter(models.Device.id == device_id).first()
8

  
9
def get_devices(db: Session, skip: int = 0, limit: int = 100):
10
    return db.query(models.Device).offset(skip).limit(limit).all()
11

  
12

  
13
def create_device(db: Session, device: schemas.DeviceCreate):
14
    db_device = models.Device(vendor_id=device.vendor_id, product_id=device.product_id)
15
    db.add(db_device)
16
    db.commit()
17
    db.refresh(db_device)
18
    return db_device
19

  
20

  
21
def get_logs(db: Session, skip: int = 0, limit: int = 100):
22
    return db.query(models.USBLog).offset(skip).limit(limit).all()
23

  
24
def get_log(db: Session, device_id: int, skip: int=0, limit: int=100):
25
    return db.query(models.USBLog).filter(models.USBLog.device_id == device_id).offset(skip).limit(limit).all()
26

  
27
def create_device_logs(db: Session, item: schemas.USBLogCreate, dev_id: int):
28
    db_log = models.USBLog(**item.dict(), device_id=dev_id)
29
    db.add(db_log)
30
    db.commit()
31
    db.refresh(db_log)
32
    return db_log
33

  
server/sql_app/database.py
1
from sqlalchemy import create_engine
2
from sqlalchemy.ext.declarative import declarative_base
3
from sqlalchemy.orm import sessionmaker
4

  
5
SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
6

  
7
engine = create_engine(
8
    SQLALCHEMY_DATABASE_URL
9
)
10
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
11

  
12
Base = declarative_base()
13

  
server/sql_app/main.py
1
from typing import List
2

  
3
from fastapi import Depends, FastAPI, HTTPException
4
from sqlalchemy.orm import Session
5

  
6
from . import crud, models, schemas
7
from .database import SessionLocal, engine
8

  
9
models.Base.metadata.create_all(bind=engine)
10

  
1
from fastapi import FastAPI
2
import fastapi
3
from pydantic import BaseModel
4
from typing import Optional, List
11 5

  
12 6
app = FastAPI()
13
    
14
# Dependency
15
def get_db():
16
    db = SessionLocal()
17
    try:
18
        yield db
19
    finally:
20
        db.close()
21

  
22

  
23
@app.post("/device/", response_model=schemas.Device)
24
def create_device(device: schemas.DeviceCreate, db: Session = Depends(get_db)):
25
    return crud.create_device(db=db, device=device)
26

  
27
@app.get("/devices/", response_model=List[schemas.Device])
28
def read_devices(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
29
    devices = crud.get_devices(db, skip=skip, limit=limit)
30
    return devices
31

  
32

  
33
@app.get("/device/{device_id}", response_model=schemas.Device)
34
def read_device(device_id: int, db: Session = Depends(get_db)):
35
    db_device = crud.get_device(db, device_id=device_id)
36
    if db_device is None:
37
        raise HTTPException(status_code=404, detail="Device not found")
38
    return db_device
39

  
40

  
41
@app.post("/api/v1/logs/{device_id}/", response_model=schemas.USBLog)
42
def create_device_logs(device_id: int, log: schemas.USBLogCreate, db: Session = Depends(get_db)):
43
    return crud.create_device_logs(db=db, item=log, dev_id=device_id)
44

  
45

  
46
@app.get("/logs/", response_model=List[schemas.USBLog])
47
def read_logs(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
48
    items = crud.get_logs(db, skip=skip, limit=limit)
49
    return items
50

  
51
@app.get("/logs/{device_id}", response_model=List[schemas.USBLog])
52
def read_log(device_id: int, db: Session = Depends(get_db)):
53
    db_log = crud.get_log(db, device_id=device_id)
54
    if db_log is None:
55
        raise HTTPException(status_code=404, detail="Logs not found")
56
    return db_log
57 7

  
8
class Device(BaseModel):
9
	vendor_id: int
10
	product_id: int
11
	serial_number: int
12

  
13
class USBLog(BaseModel):
14
	username: str
15
	hostname: str
16
	timestamp: str
17
	device: Device
18
	status:str
19

  
20
@app.post("/api/v1/usb-logs/")
21
async def root_post(usb_log: USBLog):
22
	print(usb_log)
23
	return {"message": "Sucess"}
24
	
25
@app.get("/")
26
async def root_read():
27
	print("Hello")
28
	return {"message":"Hello World"}
server/sql_app/models.py
1
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
2
from sqlalchemy.orm import relationship
3

  
4
from .database import Base
5

  
6

  
7
class Device(Base):
8
    __tablename__ = "usb_devices"
9

  
10
    id = Column(Integer, primary_key=True, index=True)
11
    vendor_id = Column(Integer, index=True, nullable=False)
12
    product_id = Column(Integer, index=True, nullable=False)
13

  
14
    logs = relationship("USBLog", back_populates="device")
15

  
16

  
17
class USBLog(Base):
18
    __tablename__ = "usb_logs"
19

  
20
    id = Column(Integer, primary_key=True, index=True)
21
    username = Column(String, index=True, nullable=False)
22
    hostname = Column(String, index=True, nullable=False)
23
    timestamp = Column(String, index=True, nullable=False)
24
    status = Column(String, index=True, nullable=False)
25
    device_id = Column(Integer, ForeignKey("usb_devices.id"))
26

  
27
    device = relationship("Device", back_populates="logs")
28

  
server/sql_app/schemas.py
1
from typing import List, Optional
2

  
3
from pydantic import BaseModel
4

  
5

  
6
class USBLogBase(BaseModel):
7
    username: str
8
    hostname: str
9
    timestamp: str
10
    status: str
11

  
12

  
13
class USBLogCreate(USBLogBase):
14
    pass
15

  
16

  
17
class USBLog(USBLogBase):
18
    id: int
19
    device_id: int
20

  
21
    class Config:
22
        orm_mode = True
23
        
24
class DeviceBase(BaseModel):
25
    vendor_id: int
26
    product_id: int
27

  
28

  
29
class DeviceCreate(DeviceBase):
30
    pass
31

  
32

  
33
class Device(DeviceBase):
34
    id: int
35
    logs: List[USBLog] = []
36
    class Config:
37
        orm_mode = True
38

  

Také k dispozici: Unified diff