Forwarding a Shortened URL
main.py to implement a
RedirectResponse. For the redirecting behavior your app needs, you need to use the
RedirectResponse classes, so these are added to the imports.
RedirectResponse returns an HTTP redirect that forwards the request of the client.
Next you add the
raise_not_found() function. Similar to the
raise_bad_request() function that was added earlier on, you’ll use
raise_not_found() if the provided
URL.key doesn’t match any URLs in your database.
Next you create the
forward_to_target_url() function with an
@app.get decorator. When you use the
@app.get decorator, you allow GET requests for the URL that you provide as an argument. With the argument provided, the
forward_to_target_url() function will be called any time a client requests the URL that matches the host and key pattern.
If a database entry is found, then you return the
target_url. If no matching database entry is found, then you raise the
HTTPException. In your browser, try out the behavior you just implemented.
In the example seen on-screen, the URL forwards successfully to realpython.com. That’s almost perfect, but why only almost? Well, although the code works, both
forward_to_target_url() have shortcomings.
Become a Member to join the conversation.