reyserver 1.1.66__py3-none-any.whl → 1.1.68__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of reyserver might be problematic. Click here for more details.

reyserver/rbase.py CHANGED
@@ -11,8 +11,8 @@
11
11
 
12
12
  from typing import Literal, Type, NoReturn, overload
13
13
  from http import HTTPStatus
14
- from fastapi import APIRouter
15
- from fastapi import HTTPException, Request, UploadFile as File
14
+ from fastapi import FastAPI, APIRouter, Request, UploadFile, HTTPException
15
+ from fastapi.responses import HTMLResponse, FileResponse
16
16
  from fastapi.params import (
17
17
  Depends,
18
18
  Path,
@@ -26,6 +26,7 @@ from fastapi.params import (
26
26
  from reydb.rconn import DatabaseConnectionAsync
27
27
  from reydb.rorm import DatabaseORMSessionAsync
28
28
  from reykit.rbase import Base, Exit, StaticMeta, Singleton, throw
29
+ from reykit.ros import File, Folder
29
30
 
30
31
  from . import rserver
31
32
 
@@ -40,7 +41,9 @@ __all__ = (
40
41
  'ServerBindInstanceDatabaseSession',
41
42
  'ServerBindInstance',
42
43
  'ServerBind',
43
- 'Bind'
44
+ 'Bind',
45
+ 'router_test',
46
+ 'router_public'
44
47
  )
45
48
 
46
49
 
@@ -311,6 +314,26 @@ class ServerBindInstance(ServerBase, Singleton):
311
314
  return forms
312
315
 
313
316
 
317
+ async def depend_server(request: Request) -> 'rserver.Server':
318
+ """
319
+ Dependencie function of now Server instance.
320
+
321
+ Parameters
322
+ ----------
323
+ request : Request.
324
+
325
+ Returns
326
+ -------
327
+ Server.
328
+ """
329
+
330
+ # Get.
331
+ app: FastAPI = request.app
332
+ server: rserver.Server = app.extra['server']
333
+
334
+ return server
335
+
336
+
314
337
  class ServerBind(ServerBase, metaclass=StaticMeta):
315
338
  """
316
339
  Server API bind parameter type.
@@ -332,15 +355,15 @@ class ServerBind(ServerBase, metaclass=StaticMeta):
332
355
  'Request body form parameter dependency type.'
333
356
  Forms = Forms
334
357
  'Request body multiple forms parameter dependency type.'
335
- File = File
336
- 'Verify file type.'
358
+ File = UploadFile
359
+ 'Type hints file type.'
337
360
  Depend = Depends
338
361
  'Dependency type.'
339
362
  Conn = DatabaseConnectionAsync
340
363
  Sess = DatabaseORMSessionAsync
341
364
  Server = Type['rserver.Server']
342
365
  'Server type.'
343
- server: Depend
366
+ server: Depend = Depend(depend_server)
344
367
  'Server instance dependency type.'
345
368
  i = ServerBindInstance()
346
369
  'Server API bind parameter build instance.'
@@ -353,11 +376,11 @@ class ServerBind(ServerBase, metaclass=StaticMeta):
353
376
 
354
377
 
355
378
  Bind = ServerBind
379
+ router_test = APIRouter()
380
+ router_public = APIRouter()
356
381
 
357
- router_base = APIRouter()
358
382
 
359
-
360
- @router_base.get('/test')
383
+ @router_test.get('/test')
361
384
  def test() -> Literal['test']:
362
385
  """
363
386
  Test.
@@ -373,8 +396,8 @@ def test() -> Literal['test']:
373
396
  return response
374
397
 
375
398
 
376
- @router_base.post('/test/echo')
377
- def echo(data: dict = Bind.i.body) -> dict:
399
+ @router_test.post('/test/echo')
400
+ def test_echo(data: dict = Bind.i.body) -> dict:
378
401
  """
379
402
  Echo test.
380
403
 
@@ -390,3 +413,41 @@ def echo(data: dict = Bind.i.body) -> dict:
390
413
  # Resposne.
391
414
 
392
415
  return data
416
+
417
+
418
+ @router_public.get('/')
419
+ def home(server: Bind.Server = Bind.server) -> HTMLResponse:
420
+ """
421
+ Home page.
422
+
423
+ Parameters
424
+ ----------
425
+ Home page HTML content.
426
+ """
427
+
428
+ # Parameter.
429
+ public_dir = server.api_public_dir
430
+ file_path = Folder(public_dir) + 'index.html'
431
+ file = File(file_path)
432
+
433
+ # Response.
434
+ response = HTMLResponse(file.str)
435
+
436
+ return response
437
+
438
+
439
+ @router_public.get('/public/{relpath}')
440
+ def get_public_file(relpath: str = Bind.i.path) -> FileResponse:
441
+ """
442
+ Get public file.
443
+
444
+ Parameters
445
+ ----------
446
+ relpath : Relative path of based on public directory.
447
+
448
+ Returns
449
+ -------
450
+ File.
451
+ """
452
+
453
+ ...
reyserver/rserver.py CHANGED
@@ -19,6 +19,7 @@ from starlette.middleware.base import _StreamingResponse
19
19
  from fastapi import FastAPI, Request
20
20
  from fastapi.staticfiles import StaticFiles
21
21
  from fastapi.middleware.gzip import GZipMiddleware
22
+ from fastapi.middleware.trustedhost import TrustedHostMiddleware
22
23
  from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
23
24
  from reydb import DatabaseAsync
24
25
  from reykit.rbase import CoroutineFunctionSimple, Singleton, throw
@@ -42,14 +43,12 @@ class Server(ServerBase, Singleton):
42
43
 
43
44
  def __init__(
44
45
  self,
45
- db: DatabaseAsync,
46
- public: str | None = None,
46
+ db: DatabaseAsync | None = None,
47
+ db_warm: bool = False,
47
48
  depend: CoroutineFunctionSimple | Sequence[CoroutineFunctionSimple] | None = None,
48
49
  before: CoroutineFunctionSimple | Sequence[CoroutineFunctionSimple] | None = None,
49
50
  after: CoroutineFunctionSimple | Sequence[CoroutineFunctionSimple] | None = None,
50
- ssl_cert: str | None = None,
51
- ssl_key: str | None = None,
52
- db_warm: bool = False,
51
+ to_https: bool = False,
53
52
  debug: bool = False
54
53
  ) -> None:
55
54
  """
@@ -58,19 +57,15 @@ class Server(ServerBase, Singleton):
58
57
  Parameters
59
58
  ----------
60
59
  db : Asynchronous database, must include database engines with APIs.
61
- public : Public directory.
60
+ db_warm : Whether database pre create connection to warm all pool.
62
61
  depend : Global api dependencies.
63
62
  before : Execute before server start.
64
63
  after : Execute after server end.
65
- ssl_cert : SSL certificate file path.
66
- ssl_key : SSL key file path.
67
- db_warm : Whether database pre create connection to warm all pool.
64
+ to_https : Whehter redirect http to https.
68
65
  debug : Whether use development mode debug server.
69
66
  """
70
67
 
71
68
  # Parameter.
72
- if type(ssl_cert) != type(ssl_key):
73
- throw(AssertionError, ssl_cert, ssl_key)
74
69
  if depend is None:
75
70
  depend = ()
76
71
  elif iscoroutinefunction(depend):
@@ -83,8 +78,6 @@ class Server(ServerBase, Singleton):
83
78
 
84
79
  # Build.
85
80
  self.db = db
86
- self.ssl_cert = ssl_cert
87
- self.ssl_key = ssl_key
88
81
  self.app = FastAPI(
89
82
  dependencies=depend,
90
83
  lifespan=lifespan,
@@ -92,22 +85,20 @@ class Server(ServerBase, Singleton):
92
85
  server=self
93
86
  )
94
87
 
95
- # Public file.
96
- if public is not None:
97
- subapp = StaticFiles(directory=public, html=True)
98
- self.app.mount('/', subapp)
99
-
100
88
  # Middleware
101
89
  self.wrap_middleware = self.app.middleware('http')
102
90
  'Decorator, add middleware to APP.'
103
91
  self.app.add_middleware(GZipMiddleware)
104
- if not debug:
92
+ self.app.add_middleware(TrustedHostMiddleware)
93
+ if to_https:
105
94
  self.app.add_middleware(HTTPSRedirectMiddleware)
106
95
  self.__add_base_middleware()
107
96
 
108
97
  # API.
109
98
  self.is_started_auth: bool = False
110
99
  'Whether start authentication.'
100
+ self.api_public_dir: str
101
+ 'Public directory.'
111
102
  self.api_auth_key: str
112
103
  'Authentication API JWT encryption key.'
113
104
  self.api_auth_sess_seconds: int
@@ -241,7 +232,9 @@ class Server(ServerBase, Singleton):
241
232
  host: str = '127.0.0.1',
242
233
  port: int = 8000,
243
234
  app: str | None = None,
244
- workers: int = 1
235
+ workers: int = 1,
236
+ ssl_cert: str | None = None,
237
+ ssl_key: str | None = None
245
238
  ) -> None:
246
239
  """
247
240
  Run server.
@@ -255,6 +248,8 @@ class Server(ServerBase, Singleton):
255
248
  - `Application`: format is `module[.sub....]:var[.attr....]` (e.g. `module.sub:server.app`).
256
249
  - `Function`: format is `module[.sub....]:func` (e.g. `module.sub:main`).
257
250
  workers: Number of server work processes.
251
+ ssl_cert : SSL certificate file path.
252
+ ssl_key : SSL key file path.
258
253
 
259
254
  Examples
260
255
  --------
@@ -269,6 +264,8 @@ class Server(ServerBase, Singleton):
269
264
  """
270
265
 
271
266
  # Parameter.
267
+ if type(ssl_cert) != type(ssl_key):
268
+ throw(AssertionError, ssl_cert, ssl_key)
272
269
  if app is None:
273
270
  app = self.app
274
271
  if workers == 1:
@@ -280,8 +277,8 @@ class Server(ServerBase, Singleton):
280
277
  host=host,
281
278
  port=port,
282
279
  workers=workers,
283
- ssl_certfile=self.ssl_cert,
284
- ssl_keyfile=self.ssl_key
280
+ ssl_certfile=ssl_cert,
281
+ ssl_keyfile=ssl_key
285
282
  )
286
283
 
287
284
 
@@ -323,15 +320,34 @@ class Server(ServerBase, Singleton):
323
320
  setattr(self.app, key, value)
324
321
 
325
322
 
326
- def add_api_base(self) -> None:
323
+ def add_api_test(self) -> None:
324
+ """
325
+ Add test API.
326
+ """
327
+
328
+ from .rbase import router_test
329
+
330
+ # Add.
331
+ self.app.include_router(router_test, tags=['test'])
332
+
333
+
334
+ def add_api_public(self, path: str) -> None:
327
335
  """
328
- Add base API.
336
+ Add public API,
337
+ mapping `{path}/index.html` to 'GET /',
338
+ mapping `{path}/{sub_path}` to `GET /public/{sub_path}`.
339
+
340
+ Parameters
341
+ path : Public directory.
329
342
  """
330
343
 
331
- from .rbase import router_base
344
+ from .rbase import router_public
332
345
 
333
346
  # Add.
334
- self.app.include_router(router_base, tags=['test'])
347
+ self.api_public_dir = path
348
+ self.app.include_router(router_public, tags=['public'])
349
+ subapp = StaticFiles(directory=path)
350
+ self.app.mount('/public', subapp)
335
351
 
336
352
 
337
353
  def add_api_auth(self, key: str | None = None, sess_seconds: int = 28800) -> None:
@@ -388,25 +404,4 @@ class Server(ServerBase, Singleton):
388
404
  self.app.include_router(router_file, tags=['file'], dependencies=(Bind.token,))
389
405
 
390
406
 
391
- async def depend_server(request: Request) -> Server:
392
- """
393
- Dependencie function of now Server instance.
394
-
395
- Parameters
396
- ----------
397
- request : Request.
398
-
399
- Returns
400
- -------
401
- Server.
402
- """
403
-
404
- # Get.
405
- app: FastAPI = request.app
406
- server = app.extra['server']
407
-
408
- return server
409
-
410
-
411
407
  Bind.Server = Server
412
- Bind.server = Bind.Depend(depend_server)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: reyserver
3
- Version: 1.1.66
3
+ Version: 1.1.68
4
4
  Summary: Backend server method set.
5
5
  Project-URL: homepage, https://github.com/reyxbo/reyserver/
6
6
  Author-email: Rey <reyxbo@163.com>
@@ -1,11 +1,11 @@
1
1
  reyserver/__init__.py,sha256=7GX64p7uI2eetJH9NJ-DTg-8iyQwOsGcviADFJCPxVA,373
2
2
  reyserver/rall.py,sha256=riyDRTUsigco_Bee1H4aZFb8IgvjnxdX9qcnVb9i9mE,270
3
3
  reyserver/rauth.py,sha256=mqyo5FsN4vdW5GRgvZssWcpfku1Dfo_Md8vvoo8JzhU,15122
4
- reyserver/rbase.py,sha256=0ECJ1zuUpJhwaNc0u5GvR5VyGxIAnKQep-EdotwnLoE,7752
4
+ reyserver/rbase.py,sha256=OKXZ_VOfPEVgO3oVn6j-pqHjnIbDL0UoZtp8GcN9hzw,8990
5
5
  reyserver/rclient.py,sha256=og5YuWm-PODkFn9njBwYQpGlk0j1BfqFuEarlCFSQYI,6229
6
6
  reyserver/rfile.py,sha256=6H5_7B9aiA3F56VToQDI9Trarkrl9gcIuFqYyCVCiCU,8877
7
- reyserver/rserver.py,sha256=3l6NoAfogeYli5lgHRfLpC9q5k7pwRCiacjN8Yt4fso,11199
8
- reyserver-1.1.66.dist-info/METADATA,sha256=njJDT00gu53ZHN4sFnbN29vl8qPli9hSvAyfP8bgJo4,1666
9
- reyserver-1.1.66.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
10
- reyserver-1.1.66.dist-info/licenses/LICENSE,sha256=UYLPqp7BvPiH8yEZduJqmmyEl6hlM3lKrFIefiD4rvk,1059
11
- reyserver-1.1.66.dist-info/RECORD,,
7
+ reyserver/rserver.py,sha256=L_a92THAZHca1WHdGczoRf-rnIw5-aGcFuAfvhd5r9w,11332
8
+ reyserver-1.1.68.dist-info/METADATA,sha256=9zPRRCTex-TayU1dBN7HqLvmTtKUwTgfwmflXJo0uK4,1666
9
+ reyserver-1.1.68.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
10
+ reyserver-1.1.68.dist-info/licenses/LICENSE,sha256=UYLPqp7BvPiH8yEZduJqmmyEl6hlM3lKrFIefiD4rvk,1059
11
+ reyserver-1.1.68.dist-info/RECORD,,