Rename api_server2 module to apiserver

This commit is contained in:
Matthias 2020-12-31 11:01:50 +01:00
parent eb20f6e7d0
commit b2ab553a31
10 changed files with 25 additions and 27 deletions

View File

@ -6,9 +6,8 @@ from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer from fastapi.security import OAuth2PasswordBearer
from fastapi.security.http import HTTPBasic, HTTPBasicCredentials from fastapi.security.http import HTTPBasic, HTTPBasicCredentials
from freqtrade.rpc.api_server2.api_models import AccessAndRefreshToken, AccessToken from freqtrade.rpc.api_server.api_models import AccessAndRefreshToken, AccessToken
from freqtrade.rpc.api_server.deps import get_api_config
from .deps import get_api_config
ALGORITHM = "HS256" ALGORITHM = "HS256"
@ -45,7 +44,7 @@ def get_user_from_token(token, secret_key: str, token_type: str = "access"):
return username return username
def create_token(data: dict, secret_key: str, token_type: str = "access") -> str: def create_token(data: dict, secret_key: str, token_type: str = "access") -> bytes:
to_encode = data.copy() to_encode = data.copy()
if token_type == "access": if token_type == "access":
expire = datetime.utcnow() + timedelta(minutes=15) expire = datetime.utcnow() + timedelta(minutes=15)

View File

@ -167,7 +167,7 @@ class DeleteTrade(BaseModel):
class PlotConfig(BaseModel): class PlotConfig(BaseModel):
main_plot: Optional[Dict[str, Any]] main_plot: Dict[str, Any]
subplots: Optional[Dict[str, Any]] subplots: Optional[Dict[str, Any]]

View File

@ -83,7 +83,7 @@ def status(rpc: RPC = Depends(get_rpc)):
# TODO: Missing response model # TODO: Missing response model
@router.get('/trades', tags=['info', 'trading']) @router.get('/trades', tags=['info', 'trading'])
def trades(limit: Optional[int] = 0, rpc: RPC = Depends(get_rpc)): def trades(limit: int = 0, rpc: RPC = Depends(get_rpc)):
return rpc._rpc_trade_history(limit) return rpc._rpc_trade_history(limit)
@ -180,8 +180,8 @@ def pair_history(pair: str, timeframe: str, timerange: str, strategy: str,
return RPC._rpc_analysed_history_full(config, pair, timeframe, timerange) return RPC._rpc_analysed_history_full(config, pair, timeframe, timerange)
@router.get('/plot_config', response_model=Union[Dict, PlotConfig], tags=['candle data']) @router.get('/plot_config', response_model=Union[PlotConfig, Dict], tags=['candle data'])
def plot_config(rpc=Depends(get_rpc)): def plot_config(rpc: RPC = Depends(get_rpc)):
return rpc._rpc_plot_config() return rpc._rpc_plot_config()

View File

@ -17,7 +17,7 @@ logger = logging.getLogger(__name__)
class ApiServer(RPCHandler): class ApiServer(RPCHandler):
_rpc: RPC = None _rpc: RPC
_config: Dict[str, Any] = {} _config: Dict[str, Any] = {}
def __init__(self, rpc: RPC, config: Dict[str, Any]) -> None: def __init__(self, rpc: RPC, config: Dict[str, Any]) -> None:

View File

@ -34,7 +34,7 @@ class RPCManager:
# Enable local rest api server for cmd line control # Enable local rest api server for cmd line control
if config.get('api_server', {}).get('enabled', False): if config.get('api_server', {}).get('enabled', False):
logger.info('Enabling rpc.api_server') logger.info('Enabling rpc.api_server')
from freqtrade.rpc.api_server2 import ApiServer from freqtrade.rpc.api_server import ApiServer
self.registered_modules.append(ApiServer(self._rpc, config)) self.registered_modules.append(ApiServer(self._rpc, config))

View File

@ -3,17 +3,13 @@ Unit test file for rpc/api_server.py
""" """
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
import uvicorn
from freqtrade.rpc.api_server2.uvicorn_threaded import UvicornServer
from fastapi.exceptions import HTTPException
from freqtrade.rpc.api_server2.api_auth import create_token, get_user_from_token
from pathlib import Path from pathlib import Path
from unittest.mock import ANY, MagicMock, PropertyMock from unittest.mock import ANY, MagicMock, PropertyMock
import pytest import pytest
import uvicorn
from fastapi import FastAPI from fastapi import FastAPI
from fastapi.exceptions import HTTPException
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from requests.auth import _basic_auth_str from requests.auth import _basic_auth_str
@ -21,9 +17,12 @@ from freqtrade.__init__ import __version__
from freqtrade.loggers import setup_logging, setup_logging_pre from freqtrade.loggers import setup_logging, setup_logging_pre
from freqtrade.persistence import PairLocks, Trade from freqtrade.persistence import PairLocks, Trade
from freqtrade.rpc import RPC from freqtrade.rpc import RPC
from freqtrade.rpc.api_server2 import ApiServer from freqtrade.rpc.api_server import ApiServer
from freqtrade.rpc.api_server.api_auth import create_token, get_user_from_token
from freqtrade.rpc.api_server.uvicorn_threaded import UvicornServer
from freqtrade.state import RunMode, State from freqtrade.state import RunMode, State
from tests.conftest import create_mock_trades, get_patched_freqtradebot, log_has, log_has_re, patch_get_signal from tests.conftest import (create_mock_trades, get_patched_freqtradebot, log_has, log_has_re,
patch_get_signal)
BASE_URI = "/api/v1" BASE_URI = "/api/v1"
@ -46,7 +45,7 @@ def botclient(default_conf, mocker):
ftbot = get_patched_freqtradebot(mocker, default_conf) ftbot = get_patched_freqtradebot(mocker, default_conf)
rpc = RPC(ftbot) rpc = RPC(ftbot)
mocker.patch('freqtrade.rpc.api_server2.ApiServer.start_api', MagicMock()) mocker.patch('freqtrade.rpc.api_server.ApiServer.start_api', MagicMock())
apiserver = ApiServer(rpc, default_conf) apiserver = ApiServer(rpc, default_conf)
yield ftbot, TestClient(apiserver.app) yield ftbot, TestClient(apiserver.app)
# Cleanup ... ? # Cleanup ... ?
@ -209,13 +208,13 @@ def test_api__init__(default_conf, mocker):
"password": "testPass", "password": "testPass",
}}) }})
mocker.patch('freqtrade.rpc.telegram.Updater', MagicMock()) mocker.patch('freqtrade.rpc.telegram.Updater', MagicMock())
mocker.patch('freqtrade.rpc.api_server2.webserver.ApiServer.start_api', MagicMock()) mocker.patch('freqtrade.rpc.api_server.webserver.ApiServer.start_api', MagicMock())
apiserver = ApiServer(RPC(get_patched_freqtradebot(mocker, default_conf)), default_conf) apiserver = ApiServer(RPC(get_patched_freqtradebot(mocker, default_conf)), default_conf)
assert apiserver._config == default_conf assert apiserver._config == default_conf
def test_api_UvicornServer(default_conf, mocker): def test_api_UvicornServer(default_conf, mocker):
thread_mock = mocker.patch('freqtrade.rpc.api_server2.uvicorn_threaded.threading.Thread') thread_mock = mocker.patch('freqtrade.rpc.api_server.uvicorn_threaded.threading.Thread')
s = UvicornServer(uvicorn.Config(MagicMock(), port=8080, host='127.0.0.1')) s = UvicornServer(uvicorn.Config(MagicMock(), port=8080, host='127.0.0.1'))
assert thread_mock.call_count == 0 assert thread_mock.call_count == 0
@ -242,7 +241,7 @@ def test_api_run(default_conf, mocker, caplog):
mocker.patch('freqtrade.rpc.telegram.Updater', MagicMock()) mocker.patch('freqtrade.rpc.telegram.Updater', MagicMock())
server_mock = MagicMock() server_mock = MagicMock()
mocker.patch('freqtrade.rpc.api_server2.webserver.UvicornServer', server_mock) mocker.patch('freqtrade.rpc.api_server.webserver.UvicornServer', server_mock)
apiserver = ApiServer(RPC(get_patched_freqtradebot(mocker, default_conf)), default_conf) apiserver = ApiServer(RPC(get_patched_freqtradebot(mocker, default_conf)), default_conf)
@ -281,10 +280,10 @@ def test_api_run(default_conf, mocker, caplog):
"Please make sure that this is intentional!", caplog) "Please make sure that this is intentional!", caplog)
assert log_has_re("SECURITY WARNING - `jwt_secret_key` seems to be default.*", caplog) assert log_has_re("SECURITY WARNING - `jwt_secret_key` seems to be default.*", caplog)
# Test crashing flask # Test crashing flask
caplog.clear() caplog.clear()
mocker.patch('freqtrade.rpc.api_server2.webserver.UvicornServer', MagicMock(side_effect=Exception)) mocker.patch('freqtrade.rpc.api_server.webserver.UvicornServer',
MagicMock(side_effect=Exception))
apiserver.start_api() apiserver.start_api()
assert log_has("Api server failed to start.", caplog) assert log_has("Api server failed to start.", caplog)
@ -300,7 +299,7 @@ def test_api_cleanup(default_conf, mocker, caplog):
server_mock = MagicMock() server_mock = MagicMock()
server_mock.cleanup = MagicMock() server_mock.cleanup = MagicMock()
mocker.patch('freqtrade.rpc.api_server2.webserver.UvicornServer', server_mock) mocker.patch('freqtrade.rpc.api_server.webserver.UvicornServer', server_mock)
apiserver = ApiServer(RPC(get_patched_freqtradebot(mocker, default_conf)), default_conf) apiserver = ApiServer(RPC(get_patched_freqtradebot(mocker, default_conf)), default_conf)

View File

@ -160,7 +160,7 @@ def test_startupmessages_telegram_enabled(mocker, default_conf, caplog) -> None:
def test_init_apiserver_disabled(mocker, default_conf, caplog) -> None: def test_init_apiserver_disabled(mocker, default_conf, caplog) -> None:
caplog.set_level(logging.DEBUG) caplog.set_level(logging.DEBUG)
run_mock = MagicMock() run_mock = MagicMock()
mocker.patch('freqtrade.rpc.api_server2.ApiServer.start_api', run_mock) mocker.patch('freqtrade.rpc.api_server.ApiServer.start_api', run_mock)
default_conf['telegram']['enabled'] = False default_conf['telegram']['enabled'] = False
rpc_manager = RPCManager(get_patched_freqtradebot(mocker, default_conf)) rpc_manager = RPCManager(get_patched_freqtradebot(mocker, default_conf))
@ -172,7 +172,7 @@ def test_init_apiserver_disabled(mocker, default_conf, caplog) -> None:
def test_init_apiserver_enabled(mocker, default_conf, caplog) -> None: def test_init_apiserver_enabled(mocker, default_conf, caplog) -> None:
caplog.set_level(logging.DEBUG) caplog.set_level(logging.DEBUG)
run_mock = MagicMock() run_mock = MagicMock()
mocker.patch('freqtrade.rpc.api_server2.ApiServer.start_api', run_mock) mocker.patch('freqtrade.rpc.api_server.ApiServer.start_api', run_mock)
default_conf["telegram"]["enabled"] = False default_conf["telegram"]["enabled"] = False
default_conf["api_server"] = {"enabled": True, default_conf["api_server"] = {"enabled": True,