Skip to content

Commit

Permalink
added variables to Expross!
Browse files Browse the repository at this point in the history
  • Loading branch information
mauro-balades committed Dec 12, 2021
1 parent 1c868cd commit d1eb89e
Show file tree
Hide file tree
Showing 17 changed files with 162 additions and 11 deletions.
5 changes: 2 additions & 3 deletions TODO → TODO.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@

DOCS:
- Update docs with new functionalities
- Add set and get functrions

EXPROSS:
- Add more HTTP request modes
- Optional logging
- Add engines option
- https://expressjs.com/en/4x/api.html#app.engine
- Add app.route
- https://expressjs.com/en/4x/api.html#app.route
- https://expressjs.com/en/4x/api.html#app.engine
3 changes: 2 additions & 1 deletion example/app.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

from expross import Expross

app = Expross()
Expand All @@ -7,8 +6,10 @@
def index(req, res):
return "hello!"


def run():
print("Listening on http://localhost:8080/")


app.get("/", index)
app.listen(8080, run)
4 changes: 4 additions & 0 deletions expross/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,7 @@ class ErrorCodeExists(Exception):

class CustomBaseException(Exception):
"""Error used for server errors like 500 or 404"""


class VariableIsConstant(Exception):
"""Thrown when a variable is a constant and user tryes to change it."""
90 changes: 84 additions & 6 deletions expross/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from typing import Callable

from expross.routes import Route
from expross.errors import ErrorCodeExists, RouteAlreadyExists
from expross.errors import ErrorCodeExists, RouteAlreadyExists, VariableIsConstant
from expross.error import ErrorHandler

from wsgiref.simple_server import make_server
Expand Down Expand Up @@ -102,6 +102,8 @@ def __init__(self, *argv, **kwargs):
self.jinja_env.lstrip_blocks = True
self.jinja_env.rstrip_blocks = True

self.vars = []

# Add all middlewares
for i in self.middlewares:
self.use(i)
Expand Down Expand Up @@ -159,11 +161,73 @@ def use(self, middleware):
self.app.add_error_handler(e.error, handler.handle)
self.errors.append(handler)

for v in middleware.vars:
self.set_var(v["name"], v["value"], v["const"])

return

self.app.add_middleware(middleware)
self.middlewares.append(middleware)

def set_var(self, name: str, val: str, constant: bool = False):
"""Set a variable to the app's contenxt
Args:
name (str): Name of the variable
val (str): Value for the variable
constant (bool, optional): Declare if the value can be changed or not. Defaults to False.
Raises:
VariableIsConstant: If trying to change a variable's value but variable is constant
Returns:
dict: Variable object
"""

exists = False
for var in self.vars:
if var["name"] == name:
exists = True

if not exists:
self.vars.append(
{
"name": str(name),
"value": str(val),
"const": constant,
}
)

return True

for i, var in enumerate(self.vars):
if var["name"] == name:

if var["const"]:
raise VariableIsConstant(f"Variable {name} is a constant")

self.vars[i]["value"] = str(val)
self.vars[i]["const"] = constant

return True

def get_var(self, name: str):
"""Get an object from an app's variable
Args:
name (str): Name of the variable
Returns:
dict: Object of the variable
"""
ret = None

for var in self.vars:
if var["name"] == name:
ret = var

return ret

def error(self, error, func: Callable):
"""add an error handler to your app
Expand All @@ -186,11 +250,22 @@ def my_error():
self.app.add_error_handler(error, handler.handle)
self.errors.append(handler)

def all(self, _route: str, func: Callable):
"""add a route to the server with the all methods available
Args:
route (str): route to be added to the router's list
func (Callable): Function to be called when endpoint is being called
"""
for method in ["GET", "POST"]:
self._add_route(_route, func, method)

def get(self, _route: str, func: Callable):
"""add a route to the server with the GET method
Args:
route (str): route to be added to the router's list
func (Callable): Function to be called when endpoint is being called
"""
self._add_route(_route, func, "GET")

Expand All @@ -199,10 +274,16 @@ def post(self, _route: str, func: Callable):
Args:
route (str): route to be added to the router's list
func (Callable): Function to be called when endpoint is being called
"""
self._add_route(_route, func, "POST")

def listen(self, serverPort: int = default_port, cb: Callable = None, hostName: str = default_host_name):
def listen(
self,
serverPort: int = default_port,
cb: Callable = None,
hostName: str = default_host_name,
):
"""Start a web server
Args:
Expand Down Expand Up @@ -341,10 +422,7 @@ def _check_for_mentioned_route(self, name):

def _check_for_repeated_route(self, name, method, function):
for route in self.routes:
if (
name == str(route)
and method in route.methods
):
if name == str(route) and method in route.methods:
raise RouteAlreadyExists(
f"Router with name {name} ({method}) already exists"
)
Expand Down
1 change: 1 addition & 0 deletions tests/test_404.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,6 @@
def test(req, res):
return "this should return 404", 404


app.error("/", test)
app.listen()
2 changes: 2 additions & 0 deletions tests/test_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,10 @@

app = Expross()


def args(req, res):
return req.args


app.get("/", args)
app.listen()
2 changes: 2 additions & 0 deletions tests/test_cors.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,11 @@

cors = CORS(allow_origins_list=["*"])


def main(req, res):
return {"test": "hey"}


app.get("/", main)

app.use(cors.middleware)
Expand Down
2 changes: 2 additions & 0 deletions tests/test_default_enpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,10 @@

app = Expross(endpoint="/endpoint")


def test(req, res):
return "/endpoint"


app.get("/", test)
print(app.routes)
2 changes: 2 additions & 0 deletions tests/test_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,10 @@

app = Expross()


def json(req, res):
return {"test": "test"}


app.get("/json", json)
app.listen()
3 changes: 3 additions & 0 deletions tests/test_multifile_route_1.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,15 @@

app = Expross()


def err():
return "<h1>ups! 404</h1>"


def main(req, res):
return "<h1>Hello, world!</h1>"


app.get("/", main)
app.error(HTTPNotFound, err)

Expand Down
4 changes: 3 additions & 1 deletion tests/test_multifile_route_2.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@

test_routes = Expross()


def test(req, res):
return "this is a multifile test!"

test_routes.get("/test", test)

test_routes.get("/test", test)
3 changes: 3 additions & 0 deletions tests/test_post.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,15 @@

app = Expross()


def main(req, res):
return app.render_template("post.html")


def test(req, res):
return app.req.post_data


app.get("/", main)
app.post("/test", test)

Expand Down
2 changes: 2 additions & 0 deletions tests/test_redirect.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,10 @@

app = Expross()


def template(req, res):
return app.redirect("https://google.com")


app.get("/", template)
app.listen()
3 changes: 3 additions & 0 deletions tests/test_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,17 @@

app = Expross()


def template(req, res):
return app.render_template("test.html", test_string="This is my test string")


def min(req, res):
return app.render_template(
"test.html", test_string="This is my test string", _minified=True
)


app.get("/", template)
app.get("/min", min)
app.listen()
2 changes: 2 additions & 0 deletions tests/test_url_for.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@
def main(req, res):
return app.url_for("other_route") # /test


def other_route(req, res):
return "Hi!"


app.get("/", main)
app.get("/test", other_route)

Expand Down
43 changes: 43 additions & 0 deletions tests/test_vars.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""
The MIT License (MIT)
Copyright (c) 2021 expross
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

from expross import Expross
from expross.errors import VariableIsConstant

app = Expross()

# Return 404, this is not for display a 404 page
app.set_var("hello", "world")
print(app.get_var("hello"))
app.set_var("hello", "Hi!")
print(app.get_var("hello"))
app.set_var("hello", "Constant var", True) # Var is now a constant
print(app.get_var("hello"))

try:
app.set_var("hello", "Can't change!")
except VariableIsConstant:
print("Constant change can't be done!!!")

print(app.get_var("hello")) # value: Constant Var (did not change)
2 changes: 2 additions & 0 deletions tests/test_xml.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@

app = Expross()


def test_xml(req, res):

_xml = """<?xml version="1.0" encoding="UTF-8"?>
Expand All @@ -40,5 +41,6 @@ def test_xml(req, res):

return xml(_xml)


app.get("/", test_xml)
app.listen()

0 comments on commit d1eb89e

Please sign in to comment.