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.http import HTTPBasic, HTTPBasicCredentials
from freqtrade.rpc.api_server2.api_models import AccessAndRefreshToken, AccessToken
from .deps import get_api_config
from freqtrade.rpc.api_server.api_models import AccessAndRefreshToken, AccessToken
from freqtrade.rpc.api_server.deps import get_api_config
ALGORITHM = "HS256"
@ -45,7 +44,7 @@ def get_user_from_token(token, secret_key: str, token_type: str = "access"):
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()
if token_type == "access":
expire = datetime.utcnow() + timedelta(minutes=15)

View File

@ -167,7 +167,7 @@ class DeleteTrade(BaseModel):
class PlotConfig(BaseModel):
main_plot: Optional[Dict[str, Any]]
main_plot: 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
@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)
@ -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)
@router.get('/plot_config', response_model=Union[Dict, PlotConfig], tags=['candle data'])
def plot_config(rpc=Depends(get_rpc)):
@router.get('/plot_config', response_model=Union[PlotConfig, Dict], tags=['candle data'])
def plot_config(rpc: RPC = Depends(get_rpc)):
return rpc._rpc_plot_config()

View File

@ -17,7 +17,7 @@ logger = logging.getLogger(__name__)
class ApiServer(RPCHandler):
_rpc: RPC = None
_rpc: RPC
_config: Dict[str, Any] = {}
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
if config.get('api_server', {}).get('enabled', False):
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))

View File

@ -3,17 +3,13 @@ Unit test file for rpc/api_server.py
"""
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 unittest.mock import ANY, MagicMock, PropertyMock
import pytest
import uvicorn
from fastapi import FastAPI
from fastapi.exceptions import HTTPException
from fastapi.testclient import TestClient
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.persistence import PairLocks, Trade
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 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"
@ -46,7 +45,7 @@ def botclient(default_conf, mocker):
ftbot = get_patched_freqtradebot(mocker, default_conf)
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)
yield ftbot, TestClient(apiserver.app)
# Cleanup ... ?
@ -209,13 +208,13 @@ def test_api__init__(default_conf, mocker):
"password": "testPass",
}})
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)
assert apiserver._config == default_conf
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'))
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())
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)
@ -281,10 +280,10 @@ def test_api_run(default_conf, mocker, caplog):
"Please make sure that this is intentional!", caplog)
assert log_has_re("SECURITY WARNING - `jwt_secret_key` seems to be default.*", caplog)
# Test crashing flask
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()
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.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)

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:
caplog.set_level(logging.DEBUG)
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
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:
caplog.set_level(logging.DEBUG)
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["api_server"] = {"enabled": True,