Skip to content

Commit

Permalink
Merge branch 'master' of github.com:yoobool/flask-state
Browse files Browse the repository at this point in the history
  • Loading branch information
PindleskinY committed Nov 11, 2020
2 parents cc975ab + e3836eb commit cbcca0e
Show file tree
Hide file tree
Showing 14 changed files with 50 additions and 25 deletions.
17 changes: 17 additions & 0 deletions .github/workflows/lint_python.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
name: lint_python
on: [pull_request, push]
jobs:
lint_python:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
- run: pip install black codespell flake8 isort pytest pyupgrade
- run: black --check . || true
- run: codespell --quiet-level=2 # --ignore-words-list="" --skip=""
- run: flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
- run: isort --profile black . || true
- run: pip install -r requirements.txt || true
- run: pip install Flask Flask-SQLAlchemy psutil redis
- run: pytest .
- run: shopt -s globstar && pyupgrade --py36-plus **/*.py || true
1 change: 1 addition & 0 deletions examples/app.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from flask import render_template

from examples.config import setting_app

app = setting_app()
Expand Down
2 changes: 1 addition & 1 deletion examples/config.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from flask import Flask

from src.flask_state import init_app, DEFAULT_BIND_SQLITE
from src.flask_state import DEFAULT_BIND_SQLITE, init_app


def setting_app():
Expand Down
12 changes: 6 additions & 6 deletions src/flask_state/controller/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,20 @@
import threading
import time

from flask import request, current_app
from flask import current_app, request

from .response_methods import make_response_content
from ..conf.config import HttpMethod, Constant
from ..conf.config import Constant, HttpMethod
from ..exceptions import ErrorResponse
from ..exceptions.error_code import MsgCode
from ..exceptions.log_msg import ErrorMsg, InfoMsg
from ..models import model_init_app
from ..services import redis_conn
from ..services.host_status import query_flask_state_host, record_flask_state_host
from ..utils.auth import auth_user, auth_method
from ..utils.auth import auth_method, auth_user
from ..utils.file_lock import Lock
from ..utils.format_conf import format_address, format_sec
from ..utils.logger import logger, DefaultLogger
from ..utils.logger import DefaultLogger, logger
from .response_methods import make_response_content

ONE_MINUTE_SECONDS = 60

Expand Down Expand Up @@ -97,7 +97,7 @@ def query_flask_state():
b2d = request.json
if not isinstance(b2d, dict):
logger.warning(ErrorMsg.DATA_TYPE_ERROR).get_msg(
'.The target type is %s, not %s' % (dict.__name__, type(b2d).__name__))
'.The target type is {}, not {}'.format(dict.__name__, type(b2d).__name__))
return make_response_content(ErrorResponse(MsgCode.JSON_FORMAT_ERROR))
time_quantum = b2d.get('timeQuantum')
return make_response_content(resp=query_flask_state_host(time_quantum))
Expand Down
2 changes: 1 addition & 1 deletion src/flask_state/controller/response_methods.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from flask import make_response, jsonify
from flask import jsonify, make_response


def make_response_content(resp, msg=None, http_status=200):
Expand Down
4 changes: 2 additions & 2 deletions src/flask_state/exceptions/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from abc import abstractmethod, ABC
from enum import unique, Enum
from abc import ABC, abstractmethod
from enum import Enum, unique


class FlaskStateResponse(ABC):
Expand Down
4 changes: 2 additions & 2 deletions src/flask_state/models/flask_state_host.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from sqlalchemy import func
from sqlalchemy.sql import text

from . import db
from ..conf.config import Constant
from . import db


# model
Expand Down Expand Up @@ -40,5 +40,5 @@ class FlaskStateHost(db.Model):
delta_hits_ratio = db.Column(db.Float, server_default=text("0"))

def __repr__(self):
return "<FlaskStateHost cpu: %s, memory:%s, load_avg:%s, disk_usage:%s, boot_seconds:%s, ts:%s>" % (
return "<FlaskStateHost cpu: {}, memory:{}, load_avg:{}, disk_usage:{}, boot_seconds:{}, ts:{}>".format(
self.cpu, self.memory, self.load_avg, self.disk_usage, self.boot_seconds, self.ts)
15 changes: 10 additions & 5 deletions src/flask_state/services/host_status.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,19 @@

import psutil

from . import redis_conn
from ..conf.config import Constant, DAYS_SCOPE
from ..dao.host_status import create_host_status, retrieve_host_status, retrieve_host_status_yesterday, \
delete_thirty_days_status, retrieve_latest_host_status
from ..exceptions import FlaskStateResponse, SuccessResponse, ErrorResponse
from ..conf.config import DAYS_SCOPE, Constant
from ..dao.host_status import (
create_host_status,
delete_thirty_days_status,
retrieve_host_status,
retrieve_host_status_yesterday,
retrieve_latest_host_status,
)
from ..exceptions import ErrorResponse, FlaskStateResponse, SuccessResponse
from ..exceptions.error_code import MsgCode
from ..utils.date import get_current_ms, get_current_s
from ..utils.logger import logger
from . import redis_conn

SECONDS_TO_MILLISECOND_MULTIPLE = 1000 # Second to millisecond multiple
DEFAULT_HITS_RATIO = 100 # Default hits ratio value
Expand Down
2 changes: 1 addition & 1 deletion src/flask_state/utils/auth.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from flask import current_app, _request_ctx_stack, request
from flask import _request_ctx_stack, current_app, request
from werkzeug.local import LocalProxy

from ..controller.response_methods import make_response_content
Expand Down
2 changes: 1 addition & 1 deletion src/flask_state/utils/file_lock.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def __init__(self):
else:
lock_dir = '/tmp'

self.file = '%s%s%s' % (lock_dir, os.sep, lock_file)
self.file = f'{lock_dir}{os.sep}{lock_file}'
self._fn = None
self.release()

Expand Down
4 changes: 2 additions & 2 deletions src/flask_state/utils/format_conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def format_sec(secs) -> int:
"""
if not isinstance(secs, int):
raise TypeError(
ErrorMsg.DATA_TYPE_ERROR.get_msg('. The target type is %s, not %s' % (int.__name__, type(secs).__name__)))
ErrorMsg.DATA_TYPE_ERROR.get_msg('. The target type is {}, not {}'.format(int.__name__, type(secs).__name__)))
if secs < Constant.MIN_SECONDS:
logger.warning(WarningMsg.TIME_SMALL.get_msg())
return Constant.DEFAULT_SECONDS
Expand All @@ -31,7 +31,7 @@ def format_address(address) -> str:
"""
if not isinstance(address, str):
raise TypeError(
ErrorMsg.DATA_TYPE_ERROR.get_msg('.The target type is %s, not %s' % (str.__name__, type(address).__name__)))
ErrorMsg.DATA_TYPE_ERROR.get_msg('.The target type is {}, not {}'.format(str.__name__, type(address).__name__)))
if len(address) < Constant.MIN_ADDRESS_LENGTH or address[:Constant.MIN_ADDRESS_LENGTH - 1] != DB_URL_HEADER:
raise ValueError(ErrorMsg.ERROR_ADDRESS.get_msg('.Error sqlite url: %s' % address))
if platform.system() == Constant.WINDOWS_SYSTEM:
Expand Down
1 change: 1 addition & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

2 changes: 1 addition & 1 deletion tests/test_services.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from src.flask_state.exceptions import ErrorResponse, SuccessResponse
from src.flask_state.models import model_init_app
from src.flask_state.services import redis_conn, host_status
from src.flask_state.services import host_status, redis_conn


def test_redis(app):
Expand Down
7 changes: 4 additions & 3 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from src.flask_state.conf.config import Constant
from src.flask_state.exceptions.log_msg import ErrorMsg
from src.flask_state.utils import format_conf, date, file_lock, auth
from src.flask_state.utils import auth, date, file_lock, format_conf


# auth
Expand Down Expand Up @@ -72,7 +72,8 @@ def test_file_lock():
try:
lock_copy.acquire()
except BlockingIOError as e:
assert e.__str__() == "[Errno 35] Resource temporarily unavailable"
errno = 11 if os.getenv("GITHUB_ACTIONS") else 35
assert str(e) == f"[Errno {errno}] Resource temporarily unavailable"

lock.release()
assert not lock_copy.acquire()
Expand Down Expand Up @@ -120,7 +121,7 @@ def test_format_address():
if not isinstance(test_type_list.get(key), str):
raise TypeError(
ErrorMsg.DATA_TYPE_ERROR.get_msg(
'. The target type is %s, not %s' % (str.__name__, type(test_type_list.get(key)).__name__)))
'. The target type is {}, not {}'.format(str.__name__, type(test_type_list.get(key)).__name__)))
except TypeError as t:
target_type_error_count += 1
assert t.__str__() == 'Data type format error. The target type is str, not %s' % key
Expand Down

0 comments on commit cbcca0e

Please sign in to comment.