# Then in handler you can use it asyncdefhandler(request): request.session["login_user"] = "bo"
Since this middleware used json to serialize and deserialize data, the data you saved in session need to be json serializiable. For example, if you save a ObjectId object (from MongoDB) in session, it wonβt know how to use json to serialize it, thus will raise exception and cannot save to cookie.
11, Request context
1) URL Object: request.url
Get request full url: url = str(request.url)
Get scheme: request.url.scheme (http, https, ws, wss)
Get netloc: request.url.netloc, e.g.: example.com:8080
Get path: request.url.path, e.g.: /search
Get query string: request.url.query, e.g.: kw=hello
Get hostname: request.url.hostname, e.g.: example.com
Get port: request.url.port, e.g.: 8080
If using secure scheme: request.url.is_secure, True is schme is https or wss
app.state.dbconn = get_db_conn() request.state.start_time = time.time() # use app-scope state variable in a request request.app.state.dbconn
13, Utility functions
1) Use State to wrap a dictionary
1 2 3 4 5 6 7 8 9 10
from starlette.datastructures import State
data = { "name": "Bo" } print(data["name"]) # now wrap it with State function wrapped = State(data) # You can use the dot syntaxt, but can't use `wrapped["name"]` any more. print(wrapped.name)
2) check if request is a ajax request
Depend on what client library you are using, the headerβs key and value might be different. Here is an example when use $.ajax function from jQuery.
asyncdefexc_handle_503(request, exc): return HTMLResponse("Failed, please try it later", status_code=exc.status_code)
# error is not exception, 500 is server side unexpected error, all other status code will be treated as Exception asyncdeferr_handle_500(request, exc): import traceback Log.error(traceback.format_exc()) return HTMLResponse("My 500 page", status_code=500)
# To add handler, we can add either status_code or Exception itself as key exception_handlers = { 403: exc_handle_403, 404: exc_handle_404, 503: exc_handle_503, 500: err_handle_500, #HTTPException: exc_handle_500, }
asyncdef__call__(self, scope, receive, send): # see above scope dictionary as reference headers = dict(scope["headers"]) # do something # pass to next middleware returnawait self.app(scope, receive, send)
2) Use BaseHTTPMiddleware
1 2 3 4 5 6 7 8 9
from starlette.middleware.base import BaseHTTPMiddleware
classCustomHeaderMiddleware(BaseHTTPMiddleware): asyncdefdispatch(self, request, call_next): # do something before pass to next middleware response = await call_next(request) # do something after next middleware returned response.headers['X-Author'] = 'John' return response