Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
Empty file added .dockerignore
Empty file.
47 changes: 47 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
name: CI

on:
push:
branches:
- main
- phase-3-workflow
pull_request:
branches:
- main

jobs:
lint-and-build:
runs-on: ubuntu-latest
env:
PYTHONPATH: .

steps:
- name: Checkout code
uses: actions/checkout@v3

- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.11'

- name: Install Python dependencies
run: |
python -m pip install --upgrade pip
pip install pylint flask requests fastapi pytest

#- name: Lint Python code
# run: pylint **/*.py

#- name: Install hadolint
# run: |
# wget -O hadolint https://github.com/hadolint/hadolint/releases/latest/download/hadolint-Linux-x86_64
# chmod +x /bin/hadolint

#- name: Lint Dockerfile
# run: hadolint Dockerfile

- name: Build Docker image
run: docker build -t hivebox-app .

- name: Run tests (placeholder)
run: echo "No tests yet, add your tests here"
32 changes: 32 additions & 0 deletions .github/workflows/openssf-scorecard.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
name: OpenSSF Scorecard

on:
branch_protection_rule:
schedule:
- cron: '0 0 * * 0'
push:
branches: [main]

permissions:
actions: read
contents: read
id-token: write
security-events: write

jobs:
analysis:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Run Scorecard analysis
uses: ossf/scorecard-action@v2
with:
results_file: results.sarif
results_format: sarif

- name: Upload SARIF file
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: results.sarif
21 changes: 21 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
FROM python:3.11-slim

# Set working directory
WORKDIR /app

# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy source code
COPY ./app ./app

# Use non-root user
RUN adduser --disabled-password --gecos '' appuser && chown -R appuser /app
USER appuser

# Expose port
EXPOSE 8000

# Start FastAPI with uvicorn
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
Binary file added __pycache__/main.cpython-311.pyc
Binary file not shown.
3 changes: 3 additions & 0 deletions app/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
"""
Moduł odpowiedzialny za endpoint /version.
"""
Binary file added app/__pycache__/__init__.cpython-39.pyc
Binary file not shown.
Binary file added app/__pycache__/version.cpython-39.pyc
Binary file not shown.
8 changes: 8 additions & 0 deletions app/version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
__version__ = "0.0.1"

def print_version():
print(f"HiveBox version: {__version__}")

"""
Moduł odpowiedzialny za endpoint /version.
"""
101 changes: 101 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import os
from flask import Flask, jsonify, Response
import httpx
from datetime import datetime, timezone, timedelta
from prometheus_client import generate_latest, CONTENT_TYPE_LATEST, Counter

app = Flask(__name__)
VERSION = "0.0.3"

# Lista ID senseBoxów, które Cię interesują
SENSEBOX_IDS = [
"5eba5fbad46fb8001b799786",
"5c21ff8f919bf8001adf2488",
"5ade1acf223bd80019a1011c"
]

@app.route("/version")
def get_version():
return jsonify({"version": VERSION})

@app.route("/metrics")
def metrics():
return Response(generate_latest(), mimetype=CONTENT_TYPE_LATEST)


@app.route("/temperatur")
def get_temperatur():
print("Starting /temperatur endpoint")
temperatures = []
now = datetime.now(timezone.utc)
one_hour_ago = now - timedelta(hours=1)

max_retries = 3

for sensebox_id in SENSEBOX_IDS:
print(f"Processing senseBox ID: {sensebox_id}")
url = f"https://api.opensensemap.org/boxes/{sensebox_id.strip()}"
for attempt in range(max_retries):
print(f"Attempt {attempt + 1} for {sensebox_id}")
try:
resp = httpx.get(url, timeout=10.0)
resp.raise_for_status()
data = resp.json()
print(f"Received data for {sensebox_id}: {data}")

sensors = data.get("sensors", [])
for sensor in sensors:
title = sensor.get("title", "").lower()
print(f"Sensor title: {title}")
if title == "temperatur":
measurement = sensor.get("lastMeasurement")
print(f"Last measurement: {measurement}")
if not measurement:
continue

value = measurement.get("value")
created_at = measurement.get("createdAt")
if not value or not created_at:
continue

created_time = datetime.fromisoformat(created_at.replace("Z", "+00:00"))
if created_time > one_hour_ago:
try:
val = float(value)
temperatures.append(val)
print(f"Added temperature: {val}")
except ValueError:
print(f"ValueError for value: {value}")
continue
break
except httpx.ReadTimeout:
print(f"Timeout on {sensebox_id}, attempt {attempt + 1}")
if attempt == max_retries - 1:
return jsonify({"error": f"Timeout contacting {sensebox_id}"}), 504
except Exception as e:
print(f"Exception on {sensebox_id}: {e}")
return jsonify({"error": str(e)}), 500

print(f"Collected temperatures: {temperatures}")
if not temperatures:
return jsonify({"message": "No recent temperature data found."}), 404

avg_temp = sum(temperatures) / len(temperatures)
print(f"Average temperature: {avg_temp}")

if avg_temp < 10:
status = "Too Cold"
elif 10 <= avg_temp <= 36:
status = "Good"
else:
status = "Too Hot"

result = {
"average_temperatur": round(avg_temp, 2),
"status": status
}
print(f"Response: {result}")
return jsonify(result)

if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)
4 changes: 4 additions & 0 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
pylint
pytest
httpx
flask
5 changes: 5 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
uvicorn
httpx
flask
Flask==3.1.1
requests
Empty file added tests/test_main.py
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pip
28 changes: 28 additions & 0 deletions venv/Lib/site-packages/MarkupSafe-3.0.2.dist-info/LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
Copyright 2010 Pallets

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
92 changes: 92 additions & 0 deletions venv/Lib/site-packages/MarkupSafe-3.0.2.dist-info/METADATA
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
Metadata-Version: 2.1
Name: MarkupSafe
Version: 3.0.2
Summary: Safely add untrusted strings to HTML/XML markup.
Maintainer-email: Pallets <[email protected]>
License: Copyright 2010 Pallets

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Project-URL: Donate, https://palletsprojects.com/donate
Project-URL: Documentation, https://markupsafe.palletsprojects.com/
Project-URL: Changes, https://markupsafe.palletsprojects.com/changes/
Project-URL: Source, https://github.com/pallets/markupsafe/
Project-URL: Chat, https://discord.gg/pallets
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Web Environment
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: BSD License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
Classifier: Topic :: Text Processing :: Markup :: HTML
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE.txt

# MarkupSafe

MarkupSafe implements a text object that escapes characters so it is
safe to use in HTML and XML. Characters that have special meanings are
replaced so that they display as the actual characters. This mitigates
injection attacks, meaning untrusted user input can safely be displayed
on a page.


## Examples

```pycon
>>> from markupsafe import Markup, escape

>>> # escape replaces special characters and wraps in Markup
>>> escape("<script>alert(document.cookie);</script>")
Markup('&lt;script&gt;alert(document.cookie);&lt;/script&gt;')

>>> # wrap in Markup to mark text "safe" and prevent escaping
>>> Markup("<strong>Hello</strong>")
Markup('<strong>hello</strong>')

>>> escape(Markup("<strong>Hello</strong>"))
Markup('<strong>hello</strong>')

>>> # Markup is a str subclass
>>> # methods and operators escape their arguments
>>> template = Markup("Hello <em>{name}</em>")
>>> template.format(name='"World"')
Markup('Hello <em>&#34;World&#34;</em>')
```

## Donate

The Pallets organization develops and supports MarkupSafe and other
popular packages. In order to grow the community of contributors and
users, and allow the maintainers to devote more time to the projects,
[please donate today][].

[please donate today]: https://palletsprojects.com/donate
14 changes: 14 additions & 0 deletions venv/Lib/site-packages/MarkupSafe-3.0.2.dist-info/RECORD
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
MarkupSafe-3.0.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
MarkupSafe-3.0.2.dist-info/LICENSE.txt,sha256=RjHsDbX9kKVH4zaBcmTGeYIUM4FG-KyUtKV_lu6MnsQ,1503
MarkupSafe-3.0.2.dist-info/METADATA,sha256=nhoabjupBG41j_JxPCJ3ylgrZ6Fx8oMCFbiLF9Kafqc,4067
MarkupSafe-3.0.2.dist-info/RECORD,,
MarkupSafe-3.0.2.dist-info/WHEEL,sha256=UAgGEIlEKluxCX20ppULf3M0rfG_1DUMdncOI_parX8,99
MarkupSafe-3.0.2.dist-info/top_level.txt,sha256=qy0Plje5IJuvsCBjejJyhDCjEAdcDLK_2agVcex8Z6U,11
markupsafe/__init__.py,sha256=pREerPwvinB62tNCMOwqxBS2YHV6R52Wcq1d-rB4Z5o,13609
markupsafe/__pycache__/__init__.cpython-39.pyc,,
markupsafe/__pycache__/_native.cpython-39.pyc,,
markupsafe/_native.py,sha256=2ptkJ40yCcp9kq3L1NqpgjfpZB-obniYKFFKUOkHh4Q,218
markupsafe/_speedups.c,sha256=SglUjn40ti9YgQAO--OgkSyv9tXq9vvaHyVhQows4Ok,4353
markupsafe/_speedups.cp39-win_amd64.pyd,sha256=Js1kySYtXhpjeY5zTOELmQOkMGIfUg9KECXjFaqbtZQ,13312
markupsafe/_speedups.pyi,sha256=LSDmXYOefH4HVpAXuL8sl7AttLw0oXh1njVoVZp2wqQ,42
markupsafe/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5 changes: 5 additions & 0 deletions venv/Lib/site-packages/MarkupSafe-3.0.2.dist-info/WHEEL
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Wheel-Version: 1.0
Generator: setuptools (75.2.0)
Root-Is-Purelib: false
Tag: cp39-cp39-win_amd64

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
markupsafe
Binary file not shown.
Loading