2024-08-06 01:10:00 -04:00
|
|
|
from spiderweb import WebServer
|
2024-08-12 11:54:16 -04:00
|
|
|
from spiderweb.exceptions import ServerError
|
2024-08-14 17:28:01 -04:00
|
|
|
from spiderweb.response import (
|
|
|
|
HttpResponse,
|
|
|
|
JsonResponse,
|
|
|
|
TemplateResponse,
|
|
|
|
RedirectResponse,
|
|
|
|
)
|
2024-08-06 01:10:00 -04:00
|
|
|
|
2024-08-09 12:02:46 -04:00
|
|
|
|
|
|
|
app = WebServer(
|
|
|
|
templates_dirs=["templates"],
|
|
|
|
middleware=[
|
2024-08-14 17:27:21 -04:00
|
|
|
"spiderweb.middleware.csrf.CSRFMiddleware",
|
2024-08-09 12:02:46 -04:00
|
|
|
"example_middleware.TestMiddleware",
|
2024-08-09 14:15:32 -04:00
|
|
|
"example_middleware.RedirectMiddleware",
|
|
|
|
"example_middleware.ExplodingMiddleware",
|
2024-08-09 12:02:46 -04:00
|
|
|
],
|
2024-08-14 17:28:01 -04:00
|
|
|
append_slash=False, # default
|
2024-08-09 12:02:46 -04:00
|
|
|
)
|
2024-08-06 01:10:00 -04:00
|
|
|
|
|
|
|
|
|
|
|
@app.route("/")
|
|
|
|
def index(request):
|
|
|
|
return TemplateResponse(request, "test.html", context={"value": "TEST!"})
|
|
|
|
|
|
|
|
|
|
|
|
@app.route("/redirect")
|
|
|
|
def redirect(request):
|
|
|
|
return RedirectResponse("/")
|
|
|
|
|
|
|
|
|
2024-08-09 12:02:46 -04:00
|
|
|
@app.route("/json")
|
|
|
|
def json(request):
|
|
|
|
return JsonResponse(data={"key": "value"})
|
|
|
|
|
|
|
|
|
|
|
|
@app.route("/error")
|
|
|
|
def error(request):
|
2024-08-12 11:54:16 -04:00
|
|
|
raise ServerError
|
2024-08-09 12:02:46 -04:00
|
|
|
|
|
|
|
|
|
|
|
@app.route("/middleware")
|
|
|
|
def middleware(request):
|
|
|
|
return HttpResponse(
|
|
|
|
body="We'll never hit this because it's redirected in middleware"
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2024-08-09 14:15:32 -04:00
|
|
|
@app.route("/example/<int:id>")
|
|
|
|
def example(request, id):
|
|
|
|
return HttpResponse(body=f"Example with id {id}")
|
|
|
|
|
|
|
|
|
2024-08-14 17:27:21 -04:00
|
|
|
@app.error(405)
|
|
|
|
def http405(request) -> HttpResponse:
|
|
|
|
return HttpResponse(body="Method not allowed", status_code=405)
|
|
|
|
|
|
|
|
|
|
|
|
@app.route("/form", allowed_methods=["POST"])
|
|
|
|
def form(request):
|
|
|
|
if request.method == "POST":
|
|
|
|
return JsonResponse(data=request.POST)
|
|
|
|
else:
|
|
|
|
return TemplateResponse(request, "form.html")
|
|
|
|
|
|
|
|
|
2024-08-06 01:10:00 -04:00
|
|
|
if __name__ == "__main__":
|
2024-08-09 12:02:46 -04:00
|
|
|
# can also add routes like this:
|
2024-08-06 01:10:00 -04:00
|
|
|
# app.add_route("/", index)
|
2024-08-09 12:02:46 -04:00
|
|
|
app.start()
|