Skip to content

Commit ecf0774

Browse files
authored
Merge pull request #50 from hadpro24/develop
[DM] Redirect #22
2 parents 7e5deb1 + dd61051 commit ecf0774

File tree

4 files changed

+70
-9
lines changed

4 files changed

+70
-9
lines changed

nimba/http/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from .utils import router, render, reverse
2+
from .utils import redirect
23
from .utils import ROUTES
34

45
all = [

nimba/http/utils.py

+41-3
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,28 @@
3939
REVERSE_ROUTE_INFO = {}
4040
PROJECT_MASK = 'PROJECT_MASK_PATH'
4141

42-
def reverse(name_path:str, *args, **kwargs) -> str:
43-
if not isinstance(name_path, str) or not re.match(r"^[^\d\W][\w-]*\Z", name_path):
42+
def reverse(name_path, *args, **kwargs):
43+
"""
44+
Reverse path using name or function name str
45+
Example:
46+
@router('/', name='home')
47+
def home(request):
48+
return 'welcom home'
49+
50+
@router('/article/<int:id>', name='article')
51+
def home(request, id):
52+
return 'welcom article'
53+
54+
@router('/about')
55+
def home(request):
56+
return 'welcom about'
57+
58+
reverse('name') ==> '/'
59+
reverse('article', id=5) ==> '/article/5'
60+
reverse('about') ==> '/about'
61+
"""
62+
if (not isinstance(name_path, str) or
63+
not re.match(r"^[^\d\W][\w-]*\Z", name_path)):
4464
raise ValueError("Name path must but a valid identifier name.")
4565

4666
args = kwargs.get('args') or args or {}
@@ -50,7 +70,7 @@ def reverse(name_path:str, *args, **kwargs) -> str:
5070
if args and kwargs:
5171
raise ValueError(("You can't mix *args and **kwargs."))
5272
if not isinstance(args, Iterable) or not isinstance(kwargs, dict):
53-
raise ValueError("*args or ** kwargs must be list and dict respectively")
73+
raise ValueError("*args or **kwargs must be list and dict respectively")
5474

5575
path, view = REVERSE_ROUTE_INFO.get(name_path) or (None, None)
5676
original_path = path
@@ -83,6 +103,22 @@ def reverse(name_path:str, *args, **kwargs) -> str:
83103
)
84104
return path
85105

106+
def redirect(to, partial=False):
107+
"""
108+
redirect http
109+
"""
110+
status = '302 Found' if partial else '301 Moved Permanently'
111+
path = reverse(to)
112+
headers = Headers()
113+
headers.add_header('Location', path)
114+
response = {
115+
'status': status,
116+
'content': [b''],
117+
'headers': headers,
118+
}
119+
print('kkkkkkkkkkkkkkkkkkk', response)
120+
return response
121+
86122
def load_static(value):
87123
return os.path.join('/staticfiles/', value)
88124

@@ -204,6 +240,8 @@ def application(environ, start_response):
204240
'content': content_response,
205241
'headers': headers,
206242
}
243+
# check if redirect
244+
# check if serializer
207245
else:
208246
response = render(*error_404(request, route, ROUTES))
209247
start_response(response['status'], response['headers'].items())

nimba/test/client.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,9 @@ def _run(self):
4646
self.host, self.port, self.app
4747
)
4848
# Don't to log
49-
log_request = httpd.RequestHandlerClass.log_request
50-
no_logging = lambda *args, **kwargs: None
51-
httpd.RequestHandlerClass.log_request = no_logging
49+
# log_request = httpd.RequestHandlerClass.log_request
50+
# no_logging = lambda *args, **kwargs: None
51+
# httpd.RequestHandlerClass.log_request = no_logging
5252

5353
self.ready.set()
5454
while True:
@@ -60,7 +60,7 @@ def _run(self):
6060

6161
if self.stop_read in ready:
6262
os.read(self.stop_read, len(self.__stop_marker))
63-
httpd.RequestHandlerClass.log_request = log_request
63+
# httpd.RequestHandlerClass.log_request = log_request
6464
break
6565

6666

@@ -121,7 +121,7 @@ def get(self, path, data=None, secure=False):
121121
url = path+'?'+query_string
122122
else:
123123
url = urllib.parse.quote(path)
124-
124+
125125
url = self.base_url+url
126126
res = {}
127127
f = open(os.devnull, 'w')

tests/test_router.py

+23-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import shutil
99
from unittest.mock import patch
1010

11-
from nimba.http import router, render, reverse
11+
from nimba.http import router, render, reverse, redirect
1212
from nimba.core.server import Application
1313
from nimba.core.exceptions import NoReverseFound
1414

@@ -39,6 +39,18 @@ def info(request):
3939
def me(request):
4040
return render('awesome_app/me.html')
4141

42+
@router('/to-redirect')
43+
def redirect_to(request):
44+
return 'Test direct'
45+
46+
@router('/move-partial')
47+
def move_partial(request):
48+
return redirect('redirect_to', partial=True)
49+
50+
@router('/move', name='move')
51+
def move(request):
52+
return redirect('redirect_to')
53+
4254
class TestRouterRender(TestCase):
4355
def setUp(self):
4456
os.environ['PROJECT_MASK_PATH'] = str(pathlib.Path(
@@ -134,6 +146,16 @@ def test_reverse_with_args(self):
134146
self.assertEqual(200, response['status_code'])
135147
self.assertEqual(name, response['text'])
136148

149+
def test_redirect_partial(self):
150+
response = self.get(reverse('move_partial'))
151+
self.assertEqual(200, response['status_code'])
152+
self.assertEqual('Test direct', response['text'])
153+
154+
def test_redirect_permanente(self):
155+
response = self.get(reverse('move'))
156+
self.assertEqual(200, response['status_code'])
157+
self.assertEqual('Test direct', response['text'])
158+
137159
def tearDown(self):
138160
try:
139161
shutil.rmtree('tests/templates')

0 commit comments

Comments
 (0)