Skip to content

Commit

Permalink
Merge pull request #39 from hadpro24/develop
Browse files Browse the repository at this point in the history
fix [DM] named_url_path #31
  • Loading branch information
hadpro24 authored Jul 22, 2021
2 parents 4ddf24a + 1a4e00e commit fcdc3d6
Show file tree
Hide file tree
Showing 7 changed files with 105 additions and 11 deletions.
2 changes: 1 addition & 1 deletion docs/tutorial/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ from nimba.http import router

@router('/about')
def about(request):
return "<h1> Hello, <h2> Welcom to my app page"
return "<h1> Hello, World </h1>"
```

Each life is decorated by a road indicating a path
Expand Down
6 changes: 5 additions & 1 deletion nimba/core/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,8 @@ class AppNameIncorrect(Exception):
pass

class CommandError(Exception):
pass
pass

class NoReverseFound(Exception):
pass

3 changes: 2 additions & 1 deletion nimba/http/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from .utils import router, render
from .utils import router, render, path_reverse
from .utils import ROUTES

all = [
'router',
'render'
'path_reverse',
'ROUTES',
]
3 changes: 0 additions & 3 deletions nimba/http/resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,4 @@ def is_valid_method(methods:list) -> None:
if not isinstance(methods, list) or len(methods) > 2 or len(methods) < 0:
raise ImproperlyMethodsConfig('ErrorConfig : methods must be list and use the valid element GET or POST.')


def reverse(name_path:str) -> str:
pass

41 changes: 40 additions & 1 deletion nimba/http/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import http.client
from wsgiref.headers import Headers
import pathlib
import urllib.parse

import traceback
import mimetypes
Expand All @@ -29,10 +30,44 @@
error_404,
error_500
)
from nimba.core.exceptions import (
NoReverseFound
)

ROUTES = {}
REVERSE_ROUTE_INFO = {}
PROJECT_MASK = 'PROJECT_MASK_PATH'

def path_reverse(name_path:str, args=None, kwargs=None) -> str:
if not isinstance(name_path, str) or not re.match(r"^[^\d\W][\w-]*\Z", name_path):
raise ValueError("Name path must but a valid identifier name.")
args = args or {}
kwargs = kwargs or {}
if args and kwargs:
raise ValueError(("Don't use *args and **kwargs."
"*args is for get and **kwargs for post method."))
path = REVERSE_ROUTE_INFO.get(name_path)
if not path:
raise NoReverseFound(f"Reverse for {name_path} not found.")

if args:
path = path +'?'+ urllib.parse.urlencode(args)
else:
regex = r'<(?:(?P<converter>[^>:]+):)?(?P<parameter>[^>]+)>'
url = re.compile(regex, 0)
helper_path = path
for match in url.finditer(path):
value = kwargs.get(match['parameter'])
if not value:
raise NoReverseFound((f"Reverse for {name_path} not found. "
"Keyword arguments '%s' not found." % match['parameter']))
path = re.sub(
helper_path[match.start():match.end()],
str(value),
path
)
return path

def load_static(value):
return os.path.join('/staticfiles/', value)

Expand All @@ -58,6 +93,7 @@ def render(template, contexts=None, status=200, charset='utf-8', content_type='t
)
#load env jinja2
contexts['load_static'] = load_static
contexts['path_reverse'] = path_reverse
with open(path, 'r') as content_file:
content = content_file.read()
html_render = env.from_string(content)
Expand All @@ -75,7 +111,7 @@ def render(template, contexts=None, status=200, charset='utf-8', content_type='t
return response


def router(path, methods=['GET']):
def router(path, methods=['GET'], name=None):
"""
Routing app
"""
Expand All @@ -87,6 +123,9 @@ def request_response_application(callback):
#format url value url
new_path, converters = resolve_pattern(path, callback)
ROUTES[new_path] = (callback, converters, path, methods)

# if: pass
REVERSE_ROUTE_INFO[name or callback.__name__] = path
def application(environ, start_response):
request = Request(environ)
#authorized
Expand Down
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[metadata]
name = nimba
version = 0.0.7
version = 0.0.8
description = Nimba is a modern, fast coding, web framework with Python.
long_description = file: README.rst
keywords = python, python3, framework, nimba, nimba-solution, web
Expand Down
59 changes: 56 additions & 3 deletions tests/test_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@
import shutil
from unittest.mock import patch

from nimba.http import router, render
from nimba.http import router, render, path_reverse
from nimba.core.server import Application
from nimba.core.exceptions import NoReverseFound

from nimba.test.client import TestCase

Expand All @@ -22,14 +23,19 @@ def about(request):
return 'yes'
return TEST

@router('/articles')
@router('/articles', name='articles')
def articles(request):
return TEST

@router('/article/<int:id>')
@router('/article/<int:id>', name='article')
def article(request, id):
return str(id)

@router('/info', name='info')
def info(request):
name = request.GET.get('name', '')
return name

@router('/me')
def me(request):
return render('awesome_app/me.html')
Expand Down Expand Up @@ -79,6 +85,53 @@ def test_route_with_template(self):
self.assertEqual(200, response['status_code'])
self.assertIn("hello, world", response['text'])

def test_path_reverse_with_function_name(self):
url = path_reverse('about')
response = self.get(url)
self.assertEqual(200, response['status_code'])
self.assertEqual(TEST, response['text'])

def test_path_reverse_with_name(self):
url = path_reverse('articles')
response = self.get(url)
self.assertEqual(200, response['status_code'])
self.assertEqual(TEST, response['text'])

def test_path_reverse_with_name_and_kwargs(self):
#error type name path
with self.assertRaises(ValueError) as error:
path_reverse(57885)
self.assertEqual(str(error.exception), "Name path must but a valid identifier name.")
#bad name give
invalid_path = 'invalid-article'
with self.assertRaises(NoReverseFound) as error:
path_reverse(invalid_path)
self.assertEqual(str(error.exception), f"Reverse for {invalid_path} not found.")
#give kwargs and args
with self.assertRaises(ValueError) as error:
path_reverse('article', kwargs={'id': 5}, args={'name': 'test'})
self.assertEqual(str(error.exception), ("Don't use *args and **kwargs."
"*args is for get and **kwargs for post method."))
#invalid parmas name
invalid_params = 'id_wrong'
with self.assertRaises(NoReverseFound) as error:
path_reverse('article', kwargs={invalid_params: 5})
self.assertEqual(str(error.exception), ("Reverse for article not found. "
"Keyword arguments 'id' not found."))
#valid
_id = 5
url = path_reverse('article', kwargs={'id': _id})
response = self.get(url)
self.assertEqual(200, response['status_code'])
self.assertEqual(str(_id), response['text'])

def test_path_reverse_with_args(self):
name = 'Harouna Diallo'
url = path_reverse('info', args={'name': name})
response = self.get(url)
self.assertEqual(200, response['status_code'])
self.assertEqual(name, response['text'])

def tearDown(self):
try:
shutil.rmtree('tests/templates')
Expand Down

0 comments on commit fcdc3d6

Please sign in to comment.