Skip to content

Commit

Permalink
Merge 087ba86 into 10ca580
Browse files Browse the repository at this point in the history
  • Loading branch information
josephmancuso authored Sep 14, 2018
2 parents 10ca580 + 087ba86 commit 6adb4e6
Show file tree
Hide file tree
Showing 7 changed files with 176 additions and 158 deletions.
2 changes: 1 addition & 1 deletion masonite/helpers/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ def create_matchurl(router, route):
"""

# Compiles the given route to regex
regex = router.compile_route_to_regex(route)
regex = route.compile_route_to_regex(router)

if route.route_url.endswith('/'):
matchurl = re.compile(regex.replace(r'\/\/$', r'\/$'))
Expand Down
95 changes: 32 additions & 63 deletions masonite/providers/RouteProvider.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,49 +17,34 @@ def boot(self, router: Route, request: Request):
# All routes joined
for route in self.app.make('WebRoutes'):

"""
|--------------------------------------------------------------------------
| Make a better match for trailing slashes
|--------------------------------------------------------------------------
|
| Sometimes a user will end with a trailing slash. Because the user might
| create routes like `/url/route` and `/url/route/` and how the regex
| is compiled down, we may need to adjust for urls that end or dont
| end with a trailing slash.
|
"""Make a better match for trailing slashes
Sometimes a user will end with a trailing slash. Because the user might
create routes like `/url/route` and `/url/route/` and how the regex
is compiled down, we may need to adjust for urls that end or dont
end with a trailing slash.
"""

matchurl = create_matchurl(router, route)

"""
|--------------------------------------------------------------------------
| Houston, we've got a match
|--------------------------------------------------------------------------
|
| Check to see if a route matches the corresponding router url. If a match
| is found, execute that route and break out of the loop. We only need
| one match. Routes are executed on a first come, first serve basis
|
"""Houston, we've got a match
Check to see if a route matches the corresponding router url. If a match
is found, execute that route and break out of the loop. We only need
one match. Routes are executed on a first come, first serve basis
"""

if matchurl.match(router.url) and route.method_type == self.app.make('Environ')['REQUEST_METHOD']:
route.load_request(request)
if request.has_subdomain():
# check if the subdomain matches the routes domain
# Check if the subdomain matches the routes domain
if not route.has_required_domain():
self.app.bind('Response', 'Route not found. Error 404')
continue

"""
|--------------------------------------------------------------------------
| Get URL Parameters
|--------------------------------------------------------------------------
|
| This will create a dictionary of parameters given. This is sort of a short
| but complex way to retrieve the url parameters.
| This is the code used to convert /url/@firstname/@lastname
| to {'firstmane': 'joseph', 'lastname': 'mancuso'}.
|
"""Get URL Parameters
This will create a dictionary of parameters given. This is sort of a short
but complex way to retrieve the url parameters.
This is the code used to convert /url/@firstname/@lastname
to {'firstmane': 'joseph', 'lastname': 'mancuso'}.
"""

try:
Expand All @@ -71,64 +56,48 @@ def boot(self, router: Route, request: Request):
except AttributeError:
pass

"""
|--------------------------------------------------------------------------
| Execute Before Middleware
|--------------------------------------------------------------------------
|
| This is middleware that contains a before method.
|
"""Execute Before Middleware
This is middleware that contains a before method.
"""

# Loads the request in so the middleware
# specified is able to use the
# request object.
route.run_middleware('before')

"""Excute HTTP before middleware
Only those middleware that have a "before" method are ran.
"""

for http_middleware in self.app.make('HttpMiddleware'):
located_middleware = self.app.resolve(
http_middleware
)
if hasattr(located_middleware, 'before'):
located_middleware.before()

"""
|--------------------------------------------------------------------------
| Get Route Data
|--------------------------------------------------------------------------
"""

# Show a helper in the terminal of which route has been visited

if self.app.make('Application').DEBUG:
print(route.method_type + ' Route: ' + router.url)

# Get the data from the route. This data is typically the
# output of the controller method

if not request.redirect_url:
request.status('200 OK')

response = route.get_response()

# Get the response from the route. This data is typically the
# output of the controller method
self.app.bind(
'Response',
router.get(route.route, response)
route.get_response()
)

"""
|--------------------------------------------------------------------------
| Execute After Middleware
|--------------------------------------------------------------------------
|
| This is middleware with an after method.
|
"""Execute After Route Middleware
This is middleware that contains an after method.
"""

# Loads the request in so the middleware
# specified is able to use the
# request object.
route.run_middleware('after')

"""Excute HTTP after middleware
Only those middleware that have an "after" method are ran.
"""

for http_middleware in self.app.make('HttpMiddleware'):
located_middleware = self.app.resolve(
http_middleware
Expand All @@ -137,7 +106,7 @@ def boot(self, router: Route, request: Request):
located_middleware.after()

# Breaks the loop because the incoming route is found and executed.
# There is no need to continue searching WebRoutes.
# There is no need to continue searching the route list.
break
else:
self.app.bind('Response', 'Route not found. Error 404')
14 changes: 5 additions & 9 deletions masonite/providers/SassProvider.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,11 @@ class SassProvider(ServiceProvider):
wsgi = False

def register(self):
"""
|--------------------------------------------------------------------------
| Compile Sass
|--------------------------------------------------------------------------
|
| Compile Sass if the libsass module is installed. Once installed, all
| Sass files are compiled when the server is ran. This will only run
| once when the server is first started.
|

"""Compile Sass
Compile Sass if the libsass module is installed. Once installed, all
Sass files are compiled when the server is ran. This will only run
once when the server is first started.
"""

Storage().compile_sass()
Expand Down
5 changes: 3 additions & 2 deletions masonite/providers/WhitenoiseProvider.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ def register(self):
pass

def boot(self):
""" Wraps the WSGI server in a whitenoise container """

"""Wraps the WSGI server in a whitenoise container
"""

self.app.bind('WSGI', WhiteNoise(
self.app.make('WSGI'), root=self.app.make('Application').STATIC_ROOT))

Expand Down
126 changes: 78 additions & 48 deletions masonite/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,14 @@
from masonite.exceptions import RouteMiddlewareNotFound, InvalidRouteCompileException
from masonite.view import View


class Route:
"""Route class used to handle routing.
"""

route_compilers = {
'int': r'(\d+)',
'integer': r'(\d+)',
'integer': r'(\d+)',
'string': r'([a-zA-Z]+)',
'default': r'([\w.-]+)'
}
Expand Down Expand Up @@ -117,51 +118,6 @@ def is_not_get_request(self):

return False

def compile_route_to_regex(self, route):
"""Compiles the given route to a regex string
Arguments:
route {string} -- URI of the route to compile.
Returns:
string -- Compiled URI string.
"""

# Split the route
split_given_route = route.route_url.split('/')

# compile the provided url into regex
url_list = []
regex = '^'
for regex_route in split_given_route:
if '@' in regex_route:
if ':' in regex_route:
try:
regex += self.route_compilers[regex_route.split(':')[
1]]
except KeyError:
raise InvalidRouteCompileException(
'Route compiler "{}" is not an available route compiler. ' \
'Verify you spelled it correctly or that you have added it using the compile() method.'.format(
regex_route.split(':')[1])
)
else:
regex += self.route_compilers['default']

regex += r'\/'

# append the variable name passed @(variable):int to a list
url_list.append(
regex_route.replace('@', '').replace(
':int', '').replace(':string', '')
)
else:
regex += regex_route + r'\/'

self.url_list = url_list
regex += '$'
return regex

def compile(self, key, to=''):
self.route_compilers.update({key: to})
return self
Expand Down Expand Up @@ -204,6 +160,10 @@ def route(self, route, output):
self.route_url = route
return self

def view(self, route, template, dictionary={}):
view_route = ViewRoute(self.method_type, route, template, dictionary)
return view_route

def _find_controller(self, controller):
"""Finds the controller to attach to the route.
Expand Down Expand Up @@ -251,7 +211,7 @@ def _find_controller(self, controller):

except Exception as e:
print('\033[93mWarning in routes/web.py!', e, '\033[0m')

def get_response(self):
# Resolve Controller Constructor
controller = self.request.app().resolve(self.controller)
Expand All @@ -262,7 +222,7 @@ def get_response(self):

if isinstance(response, View):
response = response.rendered_template

return response

def domain(self, domain):
Expand Down Expand Up @@ -366,6 +326,51 @@ def run_middleware(self, type_of_middleware):
raise RouteMiddlewareNotFound(
"Could not find the '{0}' route middleware".format(arg))

def compile_route_to_regex(self, router):
"""Compiles the given route to a regex string
Arguments:
route {string} -- URI of the route to compile.
Returns:
string -- Compiled URI string.
"""

# Split the route
split_given_route = self.route_url.split('/')

# compile the provided url into regex
url_list = []
regex = '^'
for regex_route in split_given_route:
if '@' in regex_route:
if ':' in regex_route:
try:
regex += router.route_compilers[regex_route.split(':')[
1]]
except KeyError:
raise InvalidRouteCompileException(
'Route compiler "{}" is not an available route compiler. '
'Verify you spelled it correctly or that you have added it using the compile() method.'.format(
regex_route.split(':')[1])
)
else:
regex += router.route_compilers['default']

regex += r'\/'

# append the variable name passed @(variable):int to a list
url_list.append(
regex_route.replace('@', '').replace(
':int', '').replace(':string', '')
)
else:
regex += regex_route + r'\/'

router.url_list = url_list
regex += '$'
return regex


class Get(BaseHttpRoute):
"""Class for specifying GET requests
Expand Down Expand Up @@ -402,6 +407,7 @@ def __init__(self):
self.method_type = 'PUT'
self.list_middleware = []


class Patch(BaseHttpRoute):
"""Class for specifying Patch requests
"""
Expand All @@ -413,6 +419,7 @@ def __init__(self):
self.method_type = 'PATCH'
self.list_middleware = []


class Delete(BaseHttpRoute):
"""Class for specifying Delete requests
"""
Expand All @@ -424,6 +431,29 @@ def __init__(self):
self.method_type = 'DELETE'
self.list_middleware = []


class ViewRoute(BaseHttpRoute):

def __init__(self, method_type, route, template, dictionary):
"""Class used for view routes. This class should be returned when a view is called on an HTTP route.
This is useful when returning a view that doesn't need any special logic and only needs a dictionary.
Arguments:
method_type {string} -- The method type (GET, POST, PUT etc)
route {string} -- The current route (/test/url)
template {string} -- The template to use (dashboard/user)
dictionary {dict} -- The dictionary to use to render the template.
"""
self.list_middleware = []
self.method_type = method_type
self.route_url = route
self.template = template
self.dictionary = dictionary

def get_response(self):
return self.request.app().make('ViewClass').render(self.template, self.dictionary).rendered_template


class RouteGroup():
"""Class for specifying Route Groups
"""
Expand Down
Loading

0 comments on commit 6adb4e6

Please sign in to comment.