-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathwith_decorators.py
70 lines (54 loc) · 1.79 KB
/
with_decorators.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
# generic imports
import functools
# web imports
from flask import Flask, Response, abort, g, request
from flask_executor import Executor
from flask_shell2http import Shell2HTTP
# Flask application instance
app = Flask(__name__)
# application factory
executor = Executor(app)
shell2http = Shell2HTTP(app, executor, base_url_prefix="/cmd/")
# few decorators [1]
def logging_decorator(f):
@functools.wraps(f)
def decorator(*args, **kwargs):
print("*" * 64)
print(
"from logging_decorator: " + request.url + " : " + str(request.remote_addr)
)
print("*" * 64)
return f(*args, **kwargs)
return decorator
def login_required(f):
@functools.wraps(f)
def decorator(*args, **kwargs):
if not hasattr(g, "user") or g.user is None:
abort(Response("You are not logged in.", 401))
return f(*args, **kwargs)
return decorator
shell2http.register_command(
endpoint="public/echo", command_name="echo", decorators=[logging_decorator]
)
shell2http.register_command(
endpoint="protected/echo",
command_name="echo",
decorators=[login_required, logging_decorator], # [2]
)
# [1] View Decorators:
# https://flask.palletsprojects.com/en/1.1.x/patterns/viewdecorators/
# [2] remember that decorators are applied from left to right in a stack manner.
# But are executed in right to left manner.
# Put logging_decorator first and you will see what happens.
# Test Runner
if __name__ == "__main__":
app.testing = True
c = app.test_client()
# request 1
data = {"args": ["hello", "world"]}
r1 = c.post("cmd/public/echo", json=data)
print(r1.json, r1.status_code)
# request 2
data = {"args": ["Hello", "Friend!"]}
r2 = c.post("cmd/protected/echo", json=data)
print(r2.data, r2.status_code)