The Response Object
In JsWeb, every view function must return a Response
object. This section covers the different types of responses you can send back to the client.
Helper Functions
For convenience, JsWeb provides helper functions that are the most common way to create response objects.
from jsweb.response import html, json, redirect, render
@app.route('/')
def home(req, res):
# Render a Jinja2 template
return render(req, 'index.html', {'page_title': 'Home'})
@app.route('/api/items')
def api_items(req, res):
items = [{'id': 1, 'name': 'Item 1'}, {'id': 2, 'name': 'Item 2'}]
# Send a JSON response
return json(items)
@app.route('/old-page')
def old_page(req, res):
# Redirect to a new page
return redirect('/new-page', status=301) # Permanent redirect
@app.route('/plain')
def plain_text(req, res):
# Send a simple HTML string
return html("<h1>Hello World</h1>")
Cookie Management
You can set and delete cookies on any Response
object.
from jsweb.response import HTMLResponse
@app.route('/set-theme')
def set_theme(req, res):
response = HTMLResponse("Theme set!")
response.set_cookie('theme', 'dark', max_age=3600 * 24 * 365) # Cookie for 1 year
return response
@app.route('/clear-theme')
def clear_theme(req, res):
response = HTMLResponse("Theme cleared!")
response.delete_cookie('theme')
return response
URL Generation with url_for
The url_for
function is essential for avoiding hard-coded URLs in your application. It generates a URL for a given endpoint name and is automatically available inside templates rendered with the render()
function.
<!-- In a template -->
<a href="{{ url_for('auth.login') }}">Login</a>
<a href="{{ url_for('user_profile', user_id=5) }}">Profile for User 5</a>
<img src="{{ url_for('static', filename='logo.png') }}">