You can download this code by clicking the button below.
This code is now available for download.
This function creates a web service based on Starlette, which includes a random route handler that returns a JSON response containing a message. It also sets up CORS (Cross-Origin Resource Sharing) middleware.
Technology Stack : Starlette
Code Type : Web service
Code Difficulty : Intermediate
from starlette.responses import JSONResponse
from starlette.routing import Route, Routes
from starlette.middleware.cors import CORSMiddleware
import random
def random_route_handler(request):
response = JSONResponse({"message": "Hello, World!"})
response.headers["Content-Type"] = "application/json"
return response
def create_custom_route():
routes = Routes()
routes.add Route(path="/random-route", endpoint=random_route_handler, methods=["GET"])
app = Starlette(debug=True, routes=routes)
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])
return app