Routing
The routing system is the heart of a JsWeb application, responsible for mapping incoming URL paths to the Python functions (views) that handle them. This is primarily managed through the @app.route()
decorator on your JsWebApp
instance.
Defining a Route
The most basic use of the router is to decorate a view function with the path it should handle.
from jsweb.response import html
@app.route('/')
def index(req, res):
return html('<h1>Home Page</h1>')
@app.route('/about')
def about(req, res):
return html('<p>This is the about page.</p>')
HTTP Methods
By default, routes only respond to GET requests. You can specify which HTTP methods a route should accept using the methods
argument.
@app.route('/submit', methods=['GET', 'POST'])
def submit(req, res):
if req.method == 'POST':
# Process submitted data from req.form
return html('Form submitted!')
# Show the form for GET requests
return html('<form method="post"><button type="submit">Submit</button></form>')
Dynamic Routes with Path Parameters
You can capture parts of the URL path and pass them as arguments to your view function. JsWeb supports typed parameters to automatically convert the captured value and ensure it matches the expected format.
The syntax is <converter:variable_name>
.
Available Converters:
str
: (Default) Accepts any text without a slash.int
: Accepts positive integers.path
: Accepts any text, including slashes. This is useful for capturing file paths.
Example
@app.route('/user/<str:username>')
def user_profile(req, res, username):
# The username variable will be a string
return html(f'<h1>Profile for {username}</h1>')
@app.route('/post/<int:post_id>')
def show_post(req, res, post_id):
# The post_id variable will be an integer
# post = Post.query.get(post_id) ...
return html(f'<p>Showing post with ID: {post_id}</p>')
@app.route('/files/<path:filepath>')
def serve_file(req, res, filepath):
# The filepath variable can contain slashes, e.g., 'documents/report.pdf'
return html(f'<p>Serving file: {filepath}</p>')
The captured variables are passed as keyword arguments to your view function, so the parameter names in the function signature must match the names in the URL path.