This commit is contained in:
2024-03-18 03:13:40 +03:00
parent a106129417
commit aff8c9b58d
7 changed files with 174 additions and 37 deletions

20
docs/Makefile Normal file
View File

@@ -0,0 +1,20 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = source
BUILDDIR = build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

28
docs/source/conf.py Normal file
View File

@@ -0,0 +1,28 @@
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
project = 'router'
copyright = '2023-2024, RemiZOffAlex'
author = 'RemiZOffAlex'
release = '0.1.0'
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
extensions = []
templates_path = ['_templates']
exclude_patterns = []
language = 'ru'
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
html_theme = 'alabaster'
html_static_path = ['_static']

View File

@@ -0,0 +1,22 @@
Абстракция
Брокер на основе правил принимает решение что вызывать,
как вызывать и какие параметры передать при вызове
Описание
Правила (rule) - содержит описание правил
comparator - функция, которая имеет правила и которой передаются параметры запроса
Компаратор возвращает функцию и извлечённые из запроса параметры
endpoint - вызываемая функция, которой передаются параметры
rule = {
'url': '/'
}
@broker.route(
comparator = comparator_flask(rule=rule)
)
def foo():
return 'foo'

20
docs/source/index.rst Normal file
View File

@@ -0,0 +1,20 @@
.. router documentation master file, created by
sphinx-quickstart on Mon Oct 2 02:47:03 2023.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Документация маршрутизатора
===========================
.. toctree::
:maxdepth: 2
:caption: Содержание:
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

105
progon.py
View File

@@ -3,35 +3,64 @@
__author__ = 'RemiZOffAlex'
__email__ = 'remizoffalex@mail.ru'
import logging
from router.broker import Broker
from router.compiler import Compiler
from router.syntetic.url import rule_comparator
log = logging.getLogger(__name__)
broker = Broker()
def comparator(rule, query):
print('comparator')
print(rule['url'])
print(rule)
print(query['url'])
if rule['url']['value'] == query['url']:
return {}
@broker.route(
rule = {
'domain': {
'value': '',
'isregex': True
class Comparator:
def __init__(self, rule):
self.rule = rule
def __call__(self, query):
log.error('Comparator.__call__')
log.error(self.rule)
compiler = Compiler()
log.error(compiler)
expression = compiler(self.rule)
log.error(expression)
result = expression(query)
log.error('result')
log.error(result)
return result
# if self.condition == 'AND':
# return all(map(lambda x: RuleGroup.get_rule_object(x).evaluate(obj), self.rules))
# else:
# return any(map(lambda x: RuleGroup.get_rule_object(x).evaluate(obj), self.rules))
rule={
'operator': 'and',
'rules': [
{
'key': 'domain',
'operator': 'regex',
'value': '.*'
},
'url': {
'value': '',
'isregex': True
{
'key': 'url',
'operator': 'equal',
'value': '/'
}
},
comparator = comparator
]
}
@broker.route(
comparator=Comparator(rule=rule)
)
def foo():
def foo(request):
return 'foo'
@@ -45,30 +74,54 @@ def comparator_flask(rule, query):
return result
@broker.route(
rule = {
'url': '/'
},
comparator = comparator_flask
)
def foo():
return 'foo'
# rule={
# 'key': 'url',
# 'operator': 'equal',
# 'value': '/'
# }
# @broker.route(
# comparator=comparator_flask(rule=rule)
# )
# def foo(request):
# return 'foo'
request = {
'url': '/'
'url': '/',
'domain': 'example.org'
}
broker_response = broker(request)
print('broker_response', broker_response)
if broker_response is not None:
method, params = broker_response
print('method', 'params')
print(method, params)
method, response = broker_response
print(method)
if method is None:
print('Маршрут не найден')
response = None
else:
response = method(**params)
response = method(request)
print(response)
print('#'*80)
print('CICD')
import os
request = os.environ
print(request)
broker = Broker()
rule={
'key': 'DESKTOP_SESSION',
'operator': 'equal',
'value': 'xfce'
}
@broker.route(
comparator=Comparator(rule=rule)
)
def foo(request):
return 'foo'
broker_response = broker(request)
method, response = broker_response
print(method)

View File

@@ -20,8 +20,7 @@ class Broker:
"""
for route in self.routes:
log.debug(route)
comparator = route.comparator
output = comparator(route.rule, query)
output = route.comparator(query)
if output:
return (route.endpoint, output)
@@ -45,14 +44,11 @@ class Broker:
def __repr__(self):
return repr(self.methods)
def route(self, rule: dict, comparator: Callable, *args):
def route(self, comparator: Callable, *args):
"""Декоратор
"""
assert rule is not None, 'Не указано имя метода'
def wrap(function):
_route = Route(
rule=rule,
comparator=comparator,
endpoint=function
)

View File

@@ -3,13 +3,11 @@ __email__ = 'remizoffalex@mail.ru'
class Route:
def __init__(self, rule, comparator, endpoint):
def __init__(self, comparator, endpoint):
"""
:param rule: С чем сравнивать
:param : Как сравнивать
:param : Куда отправить
:param comparator: Как и с чем сравнивать
:param endpoint: Куда отправить
"""
print('Route.__init__')
self.rule = rule
self.comparator = comparator
self.endpoint = endpoint