-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
89 lines (55 loc) · 1.93 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
from webnyx.app import WebNyxApp
from webnyx.middleware import BaseMiddleware
app = WebNyxApp()
# Below code is the same as following handler registering codes
"""
decorator = app.route("/about")
home = decorator(home)
"""
@app.route("/home")
def home(request, response):
response.text = "Hello from the HOME page"
@app.route("/about")
def about(request, response):
response.text = "Hello from the ABOUT page"
@app.route("/create-book", allowed_methods=["post"])
def book_create_handler(request, response):
response.text = "Book created successfully"
request.status_code = 201
@app.route("/hello/{name}")
def greeting(request, response, name):
response.text = f"Hello, {name}!"
@app.route("/books")
class Books:
def get(self, request, response):
response.text = "Books page"
def post(self, request, response):
response.text = "Endpoint to create a book"
def new_handler(request, response):
response.text = "It is new handler"
app.add_handler("/new-handler", new_handler)
@app.route("/template")
def template_handler(request, response):
context = {"title": "Best title", "body": "It is html rendered page"}
response.body = app.template(
"test_template.html",
context=context
)
@app.route("/json")
def json_handler(request, response):
data = {"title": "json response", "type": "json"}
response.json_body = data
# Custom Exception
def on_handler(request, response, exc):
response.text = "Something bad happened"
app.add_exception_handler(on_handler)
@app.route("/exception")
def exception_throwing_handler(request, response):
raise AttributeError("some exception")
# adding middlewares
class LoggingMiddleware(BaseMiddleware):
def process_request(self, request):
print("Processing request", request.url)
def process_response(self, request, response):
print("Processing response", request.url)
app.add_middleware(LoggingMiddleware)