Table of contents
1.
✨Introduction
2.
Bottle Framework
2.1.
🔶Dictionaries
2.2.
🔶Empty Strings, False, None, or other non-true Values
2.3.
🔶Unicode Strings
2.4.
🔶Byte Strings
2.5.
🔶Instances of HTTPError or HTTPResponse
2.6.
🔶File Objects
2.7.
🔶Iterables and generators
3.
✨STATIC FILES
3.1.
🔶Forced Downloads
4.
✨HTTP ERRORS AND REDIRECTS
5.
✨The Response Object
5.1.
🔶Status Code
5.2.
🔶Response Header
6.
✨Cookies
6.1.
🔶Signed Cookies
7.
Frequently Asked Questions
7.1.
Is bottle an MVC framework?
7.2.
What is bottle API?
7.3.
Is Flask better than bottle?
7.4.
What is bottle used for in Python?
7.5.
How do you run Python bottle?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Generating Content in Bottle framework

Author soham Medewar
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

✨Introduction

The kinds that your application can return are extremely constrained in pure WSGI. Applications must provide a byte string-yielding iterable as a response. The majority of servers transmit your content char by char even if you return a string because strings can be iterated. Strings in Unicode are not permitted at all. This is not a very useful thing.

Bottle image

In this article, we will be discussing generating the content in the bottle framework. So, without any delay, let's get started!

Bottle Framework

Bottle supports a large variety of sorts and is much more adaptable. Even better, it automatically encodes Unicode and, if possible, inserts a Content-Length header so you don't have to. The list of data types that may be returned from application callbacks is provided below, along with a brief explanation of how the framework handles each type:

🔶Dictionaries

Python dictionaries (or their subclasses) are automatically converted into JSON strings and delivered to the browser with the Content-Type header set to application/json, as was previously described. JSON-based API implementation is made simple by this. Other data formats outside JSON are also accepted.

🔶Empty Strings, False, None, or other non-true Values

This result has empty and has a Content-Length header of 0.

🔶Unicode Strings

Unicode strings (or iterables generating Unicode strings) are regarded as regular byte strings after being automatically encoded with the codec given in the Content-Type header (utf8 by default).

🔶Byte Strings

Bottle adds a Content-Length header based on the string length and returns strings as a whole (instead of iterating over each character). First, byte string lists are joined. We avoid joining other iterables that produce byte strings because they can become too large to fit in memory. In this instance, the Content-Length header is not set.

🔶Instances of HTTPError or HTTPResponse

Returning these have the same effect as when raising them as an exception. When an HTTPError occurs, the error handler is used.

🔶File Objects

Everything with a.read() method is considered as a file or file-like object and sent to the WSGI server framework's wsgi.file wrapper callable. To send files more effectively, some WSGI server implementations can employ optimized system calls (sendfile). In other circumstances, this just loops over pieces that fit in memory. Optional headers like Content-Length and Content-Type are are not automatically set. If feasible, use send file().

🔶Iterables and generators

You may use yield in callbacks or return an iterable as long as the iterable returns unicode strings, byte strings, HTTPResponse, or HTTPError instances. Unfortunately, nested iterables are not supported. Please keep in mind that the HTTP status code and headers are provided to the browser as soon as the iterable returns a non-empty item. Changes made afterward have no effect.

✨STATIC FILES

Static files

You can return file objects directly, but the static file() is the preferred method for serving static files. It detects the mime type automatically, inserts a Last-Modified header, restricts paths to the root directory for security reasons, and creates appropriate error answers (403 on permission errors, 404 on missing files). It even accepts the If-Modified-Since header and returns a 304 Not Modified response. To prevent guessing, you can specify a specific MIME type.

from bottle import static_file
@route('/images/<filename:re:.*\.png>')
def send_image(filename):
    return static_file(filename, root='/path/to/image/files', mimetype='image/png')

@route('/static/<filename:path>')
def send_static(filename):
    return static_file(filename, root='/path/to/static/files')
You can also try this code with Online Python Compiler
Run Code


You can also raise the return value of static_file() as an exception.

🔶Forced Downloads

If the MIME type is known and allocated to an application, most browsers attempt to access downloaded files (e.g. PDF files). If this is not what you want, you may force a download dialogue and even offer the user a filename:

@route('/download/<filename:path>')
def download(filename):
    return static_file(filename, root='/path/to/static/files', download=filename)
You can also try this code with Online Python Compiler
Run Code


If the download parameter is set to True, the original filename is used.

✨HTTP ERRORS AND REDIRECTS

HTTP ERRORS & CODE

The abort() function is used to generate HTTP error pages.

from bottle import route, abort
@route('/restricted')
def restricted():
    abort(401, "Sorry, access denied.")
You can also try this code with Online Python Compiler
Run Code


Sending a 303 See Other response with the Location header set to the new URL will drive a client to the new URL. That's what redirect() does for you:

from bottle import route, redirect
@route('/wrong/url')
def wrong():
    redirect("/right/url")
You can also try this code with Online Python Compiler
Run Code


As a second parameter, you can give a different HTTP status code.

✨The Response Object

 Response Object

Up to the moment at which they are communicated to the browser, response metadata like as the HTTP status code, response headers, and cookies are held in an object named response. You can directly change these metadata or utilize the specified helper methods.

🔶Status Code

The HTTP status code governs browser behavior and is set to 200 OK by default. In most cases, you'll want to use the abort() helper or return an HTTPResponse instance with the proper status code instead of manually setting the Response.status parameter. Any number is permitted, but using codes other than those established by the HTTP specification would merely confuse the browser and violate standards.

🔶Response Header

Response.set header is used to define response headers such as Cache-Control and Location (). This method accepts two parameters: the name of the header and its value. The first portion of the name is case-insensitive:

@route('/wiki/<page>')
def wiki(page):
    response.set_header('Content-Language', 'en')
    ...
You can also try this code with Online Python Compiler
Run Code


Because most headers are unique, only one header per name is sent to the client. However, some special headers may occur more than once in a response. Use Response.add header() instead of Response.set header() to add a new header:

response.set_header('Set-Cookie', 'name=value')
response.add_header('Set-Cookie', 'name2=value2'
You can also try this code with Online Python Compiler
Run Code

✨Cookies

Website Cookies

A cookie is a chunk of text with a unique name that is saved in the user's browser profile. Request.get cookie() can be used to access previously defined cookies, and Response.set cookie() can be used to set new cookies:

@route('/hello')
def hello_again():
    if request.get_cookie("visited"):
        return "Welcome again!"
    else:
        response.set_cookie("visited", "yes")
        return "Hi there, pleased to meet you"
You can also try this code with Online Python Compiler
Run Code


The Response.set cookie() method accepts a variety of additional keyword arguments that govern the duration and behavior of the cookie. Some of the most common settings are max_age, expires, domain, path, secure, etc.

🔶Signed Cookies

As previously stated, malevolent clients can readily counterfeit cookies. To prevent this type of exploitation, Bottle can cryptographically sign your cookies. When you read or set a cookie, all you have to do is give a signature key via the secret keyword parameter and keep that key hidden. As a result, if the cookie is not signed or the signature keys do not match, Request.get cookie() will return None:

@route('/login')
def do_login():
    username = request.forms.get('username')
    password = request.forms.get('password')
    if check_login(username, password):
        response.set_cookie("account", username, secret='some-secret-key')
        return template("<h1>Hello {{name}}! Successful login.</h1>", name=username)
    else:
        return "<h1>Login failed.</h1>"

@route('/restricted')
def restricted_area():
    username = request.get_cookie("account", secret='some-secret-key')
    if username:
        return template("Hi {{name}}. Welcome again.", name=username)
    else:
        return "Access denied."
You can also try this code with Online Python Compiler
Run Code


Furthermore, Bottle pickles and unpickles any data stored in signed cookies. This allows you to pickle any object (not just strings) and save it in cookies as long as the pickled data does not exceed the 4 KB restriction.

Frequently Asked Questions

Is bottle an MVC framework?

Similar to most frameworks, Bottle uses an MVC software paradigm. Model, View, and Controller, or MVC, is an acronym for the choice to divide a user interface's various functions.

What is bottle API?

Bottle is a Python WSGI micro web framework that is quick, easy, and lightweight. It is supplied as a single file module and only requires the Python Standard Library as a dependency.

Is Flask better than bottle?

Bottle and Flask are both extensively used as Python's backend web frameworks. In any case, Flask is thought to be more effective, and as a result, programmers frequently select it over Bottle.

What is bottle used for in Python?

It is supplied as a single file module and only requires the Python Standard Library as a dependency. Routing: Support for clean and dynamic URLs and requests to function-call mapping

How do you run Python bottle?

Go to http://localhost:8080/ in your browser after running the script or pasting it into a Python console. Use pip install bottle to install the most recent stable version, or download bottle.py (unstable) and place it in your project directory.

Conclusion

In this article, we have learned about plugins in the bottle framework. Also, we have discussed different types of plugins that are generally used while dealing with the bottle framework. That’s all from the article.

Be curious to learn

To learn more about different frameworks, you can refer to 19 best python frameworksflask introduction. That's the end of the article. I hope you all like this article. 

Do upvote our blogs if you find them helpful and engaging!

Happy Learning, Ninjas!

Thankyou image
Live masterclass