User’s Guide¶
This guide introduces you to the concepts and features of the Bottle web framework and covers basic and advanced topics alike. You can read it from start to end, or use it as a reference later on. The automatically generatedAPI Reference may be interesting for you, too. It covers more details, but explains less than this tutorial. Solutions for the most common questions can be found in ourF.A.Q. collection or on theF.A.Q. page. If you need any help, join ourmailing list or visit us in ourIRC channel.
Installation¶
Bottle does not depend on any external libraries. You can just downloadbottle.py into your project directory and start coding:
$wgethttps://bottlepy.org/bottle.py
This will get you the latest development snapshot that includes all the new features. If you prefer a more stable environment, you should stick with the stable releases. These are available onPyPI and can be installed viapip (recommended) or your package manager:
$pipinstall--userbottle# better use a venv, see below$sudoapt-getinstallpython-bottle# works for debian, ubuntu, ...
It is usually a better idea to create avirtualenv per project and use that to install packages:
$python3-mvenvvenv# Create virtual environment$sourcevenv/bin/activate# Change default python to virtual one(venv)$pipinstall-Ubottle# Install bottle to virtual environment
Hello World!¶
This tutorial assumes you have Bottle eitherinstalled or copied into your project directory. Let’s start with a very basic “Hello World” example:
frombottleimportroute,run@route('/hello')defhello():return"Hello World!"if__name__=='__main__':run(host='localhost',port=8080,debug=True)
This is it. Run this script, visithttp://localhost:8080/hello and you will see “Hello World!” in your browser. Here is how it works:
Theroute() decorator binds a piece of code to an URL path. In this case, we link the/hello path to thehello() function. This is called aroute (hence the decorator name) and is the most important concept of this framework. You can define as many routes as you want. Whenever a browser requests a URL, the associated function is called and the return value is sent back to the browser. It’s as simple as that.
Therun() call in the last line starts a built-in development server. It runs onlocalhost port8080 and serves requests until you hitControl-c. You can switch the server backend later (seeDeployment), but for now a development server is all we need. It requires no setup at all and is an incredibly painless way to get your application up and running for local tests.
Debug Mode is very helpful during early development, but should be switched off for public applications. Keep that in mind.
This is just a demonstration of the basic concept of how applications are built with Bottle. Continue reading and you’ll see what else is possible.
The Application Object¶
For the sake of simplicity, most examples in this tutorial use a module-levelroute() and other decorators to define routes. Those refer to a global “default application”, an instance ofBottle that is automatically created the first time you callroute() or its friends. If you prefer a more explicit approach and don’t mind the extra typing, you can create a separate application object and use that instead of the global one:
frombottleimportBottle,runapp=Bottle()@app.route('/hello')defhello():return"Hello World!"if__name__=='__main__':app.run(host='localhost',port=8080)
The object-oriented approach is further described in theStructuring Applications section. Just keep in mind that you have a choice.
Debug Mode¶
During early development, the debug mode can be very helpful.
# Enable debug at runtimebottle.debug(True)# or during startuprun(...,debug=True)
In this mode, Bottle is much more verbose and provides helpful debugging information whenever an error occurs. It also disables some optimisations that might get in your way and adds some checks that warn you about possible misconfiguration. Here is an incomplete list of things that change in debug mode:
The default error page shows a traceback.
Templates are not cached.
Plugins are applied immediately.
Just make sure not to use the debug mode on a production server.
Auto Reloading¶
Tired of restarting the server every time you change your code?The auto reloader can do this for you. Every time you edit a modulefile, the reloader restarts the server process and loads the newestversion of your code.
run(...,debug=True,reloader=True)
How it works: the main process will not start a server, but spawn a newchild process using the same command line arguments used to start themain process. All module-level code is executed at least twice! Becareful.
The child process will haveos.environ['BOTTLE_CHILD'] set toTrueand start as a normal non-reloading app server. As soon as any of theloaded modules changes, the child process terminates and is re-spawned bythe main process. Changes in template files will not trigger a reload.Please use debug mode to deactivate template caching.
Command Line Interface¶
Bottle is not only a module, but also a command line executable that can be used to start your app instead of callingrun() programmatically. If you installed bottle viapip or similar tools, there will also be a handybottle command on your path. Try one of the following:
bottle --helppython3 -m bottle --help./path/to/bottle.py --help
Here is a quick example:
$bottle--debug--reloadmymoduleBottle v0.13-dev server starting up (using WSGIRefServer())...Listening on http://localhost:8080/Hit Ctrl-C to quit.
Changed in version 0.13:The executable script installed into (virtual) environments was namedbottle.py, which could result in circular imports. The old name is now deprecated and the new executable ist named justbottle.
Request Routing¶
In the last chapter we built a very simple web application with only a single route. Here is the routing part of the “Hello World” example again:
@route('/hello')defhello():return"Hello World!"
Theroute() decorator links an URL path to a callback function, and adds a new route to thedefault application. An application with just one route is kind of boring, though. Let’s add some more (don’t forgetfrombottleimporttemplate):
@route('/')@route('/hello/<name>')defgreet(name='Stranger'):returntemplate('Hello {{name}}, how are you?',name=name)
This example demonstrates two things: You can bind more than one route to a single callback, and you can add wildcards to URLs and access them via keyword arguments.
Dynamic Routes¶
Routes that contain wildcards are calleddynamic routes (as opposed tostatic routes) and match more than one URL at the same time. A simple wildcard consists of a name enclosed in angle brackets (e.g.<name>) and accepts one or more characters up to the next slash (/). For example, the route/hello/<name> accepts requests for/hello/alice as well as/hello/bob, but not for/hello,/hello/ or/hello/mr/smith.
Each wildcard passes the covered part of the URL as a keyword argument to the request callback. You can use them right away and implement RESTful, nice-looking and meaningful URLs with ease. Here are some other examples along with the URLs they’d match:
@route('/wiki/<pagename>')# matches /wiki/Learning_Pythondefshow_wiki_page(pagename):...@route('/<action>/<user>')# matches /follow/defnulldefuser_api(action,user):...
Filters can be used to define more specific wildcards, and/or transform the covered part of the URL before it is passed to the callback. A filtered wildcard is declared as<name:filter> or<name:filter:config>. The syntax for the optional config part depends on the filter used.
The following filters are implemented by default and more may be added:
:int matches (signed) digits only and converts the value to integer.
:float similar to :int but for decimal numbers.
:path matches all characters including the slash character in a non-greedy way and can be used to match more than one path segment.
:re allows you to specify a custom regular expression in the config field. The matched value is not modified.
Let’s have a look at some practical examples:
@route('/object/<id:int>')defcallback(id):assertisinstance(id,int)@route('/show/<name:re:[a-z]+>')defcallback(name):assertname.isalpha()@route('/static/<path:path>')defcallback(path):returnstatic_file(path,...)
You can add your own filters as well. SeeRequest Routing for details.
HTTP Request Methods¶
The HTTP protocol defines severalrequest methods (sometimes referred to as “verbs”) for different tasks. GET is the default for all routes with no other method specified. These routes will match GET requests only. To handle other methods such as POST, PUT, DELETE or PATCH, add amethod keyword argument to theroute() decorator or use one of the five alternative decorators:get(),post(),put(),delete() orpatch().
The POST method is commonly used for HTML form submission. This example shows how to handle a login form using POST:
frombottleimportget,post,request# or route@get('/login')# or @route('/login')deflogin():return''' <form action="/login" method="POST"> Username: <input name="username" type="text" /> Password: <input name="password" type="password" /> <input value="Login" type="submit" /> </form> '''@post('/login')# or @route('/login', method='POST')defdo_login():username=request.forms.usernamepassword=request.forms.passwordifcheck_login(username,password):return"<p>Your login information was correct.</p>"else:return"<p>Login failed.</p>"
In this example the/login URL is linked to two distinct callbacks, one for GET requests and another for POST requests. The first one displays a HTML form to the user. The second callback is invoked on a form submission and checks the login credentials the user entered into the form. The use ofRequest.forms<BaseRequest.forms>isfurtherdescribedinthe:ref:`tutorial-request section.
Special Methods: HEAD and ANY
The HEAD method is used to ask for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information about a resource without having to download the entire document. Bottle handles these requests automatically by falling back to the corresponding GET route and cutting off the request body, if present. You don’t have to specify any HEAD routes yourself.
Additionally, the non-standard ANY method works as a low priority fallback: Routes that listen to ANY will match requests regardless of their HTTP method but only if no other more specific route is defined. This is helpful forproxy-routes that redirect requests to more specific sub-applications.
To sum it up: HEAD requests fall back to GET routes and all requests fall back to ANY routes, but only if there is no matching route for the original request method. It’s as simple as that.
Serving Assets¶
Static files or assets such as images or CSS files are not served automatically. You have to add a route and a callback to control which files get served and where to find them. Bottle comes with a handystatic_file() function that does most of the work and serves files in a safe and convenient way:
frombottleimportstatic_file@route('/static/<filepath:path>')defserver_static(filepath):returnstatic_file(filepath,root='/path/to/your/static/files')
Note that we used the:path route filter here to allow slash characters infilepath and serve files from sub-directories, too.
Thestatic_file() helper function has a lot of benefits compared to handling files manually. Most importantly it preventsdirectory traversal attacks (e.g.GET/static/../../../../etc/secrets) by restricting file access to the specifiedroot directory. Make sure to use an absolut path forroot, though. Relative paths (staring with./) are resolved against the current work directory which may not always be the same as your project directory.
Thestatic_file() function returnsHTTPResponse orHTTPError, which can be raised as an exception if you need to.
File downloads
Most browsers try to open downloaded files with the associated application if the MIME type is known (e.g. PDF files). If this is not what you want, you can force a download dialog and even suggest a filename to the user:
@route('/download/<filename>')defdownload(filename):returnstatic_file(filename,root='/path/to/static/files',download=f"download-{filename}")
If thedownload parameter is justTrue, the original filename is used.
Generating content¶
We already learned that route callbacks can return strings as content, but there is more: Bottle supports a bunch of other data types and even addsContent-Length and other headers if possible, so you don’t have to. Here is a list of data types you may return from your application callbacks and a short description of how these are handled by the framework:
- Dictionaries
Python dictionaries (or subclasses thereof) are automatically transformed into JSON strings and returned to the browser with the
Content-Typeheader set toapplication/json. This makes it easy to implement JSON-based APIs and is actually implemented by theJsonPluginwhich is applied to all routes automatically. You can configure and disable JSON handling if you need to.- Empty Strings,
False,Noneor other non-true values: These will produce an empty response.
- Lists of strings
Lists of byte or unicode strings are joined into a single string then processed as usual (see blow).
- Unicode strings
Unicode strings are automatically encoded with the codec specified in the
Content-Typeheader (utf8by default) and then processed as byte strings (see below).- Byte strings
Raw byte strings are written to the response as-is.
- Instances of
HTTPErrororHTTPResponse Raising or returning an instance of
HTTPResponsewill overwrite any changes made to the globalrequestobject and then continue as usual. In case of anHTTPError, error handler are applied first. SeeError handling for details.- Files or file-like objects
Anything that has a
.read()method is treated as a file or file-like object and passed to thewsgi.file_wrappercallable defined by the WSGI server framework. Some WSGI server implementations can make use of optimized system calls (e.g. sendfile) to transmit files more efficiently. In other cases this just iterates over chunks that fit into memory. Optional headers such asContent-LengthorContent-Typearenot set automatically. For security and other reasons you should always preferstatic_file()over returning raw files, though. SeeServing Assets for details.- Iterables or generators
You can
yieldeither byte- or unicode strings (not both) from your route callback and bottle will write those to the response in a streaming fashion. TheContent-Lengthheader is not set in this case, because the final response size is not known. Nested iterables are not supported, sorry. Please note that HTTP status code and headers are sent to the browser as soon as the iterable yields its first non-empty value. Changing these later has no effect. If the first element of the iterable is eitherHTTPErrororHTTPResponse, the rest of the iterator is ignored.
The ordering of this list is significant. You may for example return a subclass ofstr with aread() method. It is still treated as a string instead of a file, because strings are handled first.
Changing the Default Encoding
Bottle uses thecharset parameter of theContent-Type header to decide how to encode unicode strings. This header defaults totext/html;charset=UTF8 and can be changed using theResponse.content_type attribute or by setting theResponse.charset attribute directly. (TheResponse object is described in the sectionThe response Object.)
frombottleimportresponse@route('/iso')defget_iso():response.charset='ISO-8859-15'returnu'This will be sent with ISO-8859-15 encoding.'@route('/latin9')defget_latin():response.content_type='text/html; charset=latin9'returnu'ISO-8859-15 is also known as latin9.'
In some rare cases the Python encoding names differ from the names supported by the HTTP specification. Then, you have to do both: first set theResponse.content_type header (which is sent to the client unchanged) and then set theResponse.charset attribute (which is used to encode unicode).
Error handling¶
If anything goes wrong, Bottle displays an informative but fairly plain error page. It contains a stacktrace ifdebug() mode is on. You can override the default error page and register an error handler for a specific HTTP status code with theerror() decorator:
frombottleimporterror@error(404)deferror404(error):return'Nothing here, sorry'
From now on,404 (File not found) errors will display a custom error page to the user. The only parameter passed to the error-handler is an instance ofHTTPError. Apart from that, an error-handler is quite similar to a regular request callback. You can read fromrequest, write toresponse and return any supported data-type except forHTTPError instances.
Error handlers are used only if your application returns or raises anHTTPError exception (abort() does just that). SettingResponse.status to an error code or returningHTTPResponse won’t trigger error handlers.
Triggering errors withabort()
Theabort() function is a shortcut for triggering HTTP errors.
frombottleimportroute,abort@route('/restricted')defrestricted():abort(401,"Sorry, access denied.")
You do not need to return anything when usingabort(). It raises anHTTPError exception.
Other Exceptions
All exceptions other thanHTTPResponse orHTTPError will result in a500InternalServerError response, so they won’t crash your WSGI server. You can turn off this behavior to handle exceptions in your middleware by settingbottle.app().catchall toFalse.
Theresponse Object¶
Response metadata such as the HTTP status code, response headers and cookies are stored in an object calledresponse up to the point where they are transmitted to the browser. You can manipulate these metadata directly or use the predefined helper methods to do so. The full API and feature list is described in the API section (seeBaseResponse), but the most common use cases and features are covered here, too.
Status Code
The HTTP status code controls the behavior of the browser and defaults to200OK. In most scenarios you won’t need to set theResponse.status attribute manually, but use theabort() helper or return anHTTPResponse instance with the appropriate status code. Any integer is allowed, but codes other than the ones defined by theHTTP specification will only confuse the browser and break standards.
Response Headers
Response headers such asCache-Control orLocation are defined viaResponse.set_header. This method takes two parameters, a header name and a value. The name part is case-insensitive:
@route('/wiki/<page>')defwiki(page):response.set_header('Content-Language','en')...
Most headers are unique, meaning that only one header per name is send to the client. Some special headers however are allowed to appear more than once in a response. To add an additional header, useResponse.add_header instead ofResponse.set_header:
response.set_header('Set-Cookie','name=value')response.add_header('Set-Cookie','name=value2')
Please note that this is just an example. If you want to work with cookies, readahead.
Redirects
To redirect a client to a different URL, you can send a303SeeOther response with theLocation header set to the new URL.redirect() does that for you:
frombottleimportroute,redirect@route('/wrong/url')defwrong():redirect("/right/url")
Cookies¶
A cookie is a named piece of text stored in the user’s browser profile. You can access previously defined cookies viaRequest.get_cookie and set new cookies withResponse.set_cookie:
@route('/hello')defhello_again():ifrequest.get_cookie("visited"):return"Welcome back! Nice to see you again"else:response.set_cookie("visited","yes")return"Hello there! Nice to meet you"
TheResponse.set_cookie method accepts a number of additional keyword arguments that control the cookies lifetime and behavior. Some of the most common settings are described here:
max_age: Maximum age in seconds. (default:
None)expires: A datetime object or UNIX timestamp. (default:
None)domain: The domain that is allowed to read the cookie. (default: current domain)
path: Limit the cookie to a given path (default:
/)secure: Limit the cookie to HTTPS connections (default: off).
httponly: Prevent client-side javascript to read this cookie (default: off, requires Python 2.7 or newer).
samesite: Disables third-party use for a cookie. Allowed attributes:lax andstrict. In strict mode the cookie will never be sent. In lax mode the cookie is only sent with a top-level GET request.
If neitherexpires normax_age is set, the cookie expires at the end of the browser session or as soon as the browser window is closed. There are some other gotchas you should consider when using cookies:
Cookies are limited to 4 KB of text in most browsers.
Some users configure their browsers to not accept cookies at all. Most search engines ignore cookies too. Make sure that your application still works without cookies.
Cookies are stored at client side and are not encrypted in any way. Whatever you store in a cookie, the user can read it. Worse than that, an attacker might be able to steal a user’s cookies throughXSS vulnerabilities on your side. Some viruses are known to read the browser cookies, too. Thus, never store confidential information in cookies.
Cookies are easily forged by malicious clients. Do not trust cookies.
Signed Cookies
As mentioned above, cookies are easily forged by malicious clients. Bottle can cryptographically sign your cookies to prevent this kind of manipulation. All you have to do is to provide a signature key via thesecret keyword argument whenever you read or set a cookie and keep that key a secret. As a result,Request.get_cookie will returnNone if the cookie is not signed or the signature keys don’t match:
@route('/login')defdo_login():username=request.forms.get('username')password=request.forms.get('password')ifcheck_login(username,password):response.set_cookie("account",username,secret='some-secret-key')returntemplate("<p>Welcome {{name}}! You are now logged in.</p>",name=username)else:return"<p>Login failed.</p>"@route('/restricted')defrestricted_area():username=request.get_cookie("account",secret='some-secret-key')ifusername:returntemplate("Hello {{name}}. Welcome back.",name=username)else:return"You are not logged in. Access denied."
In addition, Bottle automatically pickles and unpickles any data stored to signed cookies. This allows you to store any pickle-able object (not only strings) to cookies, as long as the pickled data does not exceed the 4 KB limit.
Warning
Signed cookies are not encrypted (the client can still see the content) and not copy-protected (the client can restore an old cookie). The main intention is to make pickling and unpickling safe and prevent manipulation, not to store secret information at client side.
Request Data¶
Cookies, HTTP header, form data and other request data is available through the globalrequest object. This special object always refers to thecurrent request, even in multi-threaded environments where multiple client connections are handled at the same time:
frombottleimportrequest,route,template@route('/hello')defhello():name=request.cookies.usernameor'Guest'returntemplate('Hello {{name}}',name=name)
Therequest object is a subclass ofBaseRequest and has a very rich API to access data. We only cover the most commonly used features here, but it should be enough to get started.
HTTP Headers¶
All HTTP headers sent by the client (e.g.Referer,Agent orAccept-Language) are stored in aWSGIHeaderDict and accessible through theRequest.headers attribute. AWSGIHeaderDict is basically a dictionary with case-insensitive keys:
frombottleimportroute,request@route('/is_ajax')defis_ajax():ifrequest.headers.get('X-Requested-With')=='XMLHttpRequest':return'This is an AJAX request'else:return'This is a normal request'
Cookies¶
Cookies are small pieces of text stored in the clients browser and sent back to the server with each request. They are useful to keep some state around for more than one request (HTTP itself is stateless), but should not be used for security related stuff. They can be easily forged by the client.
All cookies sent by the client are available throughRequest.cookies (aFormsDict). This example shows a simple cookie-based view counter:
frombottleimportroute,request,response@route('/counter')defcounter():count=int(request.cookies.get('counter','0'))count+=1response.set_cookie('counter',str(count))return'You visited this page%d times'%count
TheRequest.get_cookie method is a different way do access cookies. It supports decodingsigned cookies as described in a separate section.
Query parameters, Forms and File uploads¶
Query and form data is parsed on demand and accessible viarequest properties and methods. Some of those properties combine values from different sources for easier access. Have a look at the following table for a quick overview.
Property | Data source |
|---|---|
Query parameters | |
Alias for | |
orm fields and file uploads combined | |
orm fields | |
File uploads or very large form fields | |
Query parameters and form fields combined |
IntroducingFormsDict
Bottle uses a special type of dictionary to store those parameters.FormsDict behaves like a normal dictionary, but has some additional features to make your life easier.
First of all,FormsDict is a subclass ofMultiDict and can store more than one value per key. Only the first value is returned by default, butMultiDict.getall() can be used to get a (possibly empty) list of all values for a specific key:
forchoiceinrequest.forms.getall('multiple_choice'):do_something(choice)
Attribute-like access is also supported, returning empty strings for missing values. This simplifies code a lot whend ealing with lots of optional attributes:
name=request.query.name# may be an empty string
A word on unicode and character encodings
Unicode characters in the request path, query parameters or cookies are a bit tricky. HTTP is a very old byte-based protocol that predates unicode and lacks explicit encoding information. This is why WSGI servers have to fall back onISO-8859-1 (akalatin1, a reversible input encoding) for those estrings. Modern browsers default toutf8, though. It’s a bit much to ask application developers to translate every single user input string to the correct encoding manually. Bottle makes this easy and just assumesutf8 for everything. All strings returned by Bottle APIs support the full range of unicode characters, as long as the webpage or HTTP client follows best practices and does not break with established standards.
Query Parameters¶
The query string (as in/forum?id=1&page=5) is commonly used to transmit a small number of key/value pairs to the server. You can use theRequest.query attribute (aFormsDict) to access these values and theRequest.query_string attribute to get the whole string.
frombottleimportroute,request,response,template@route('/forum')defdisplay_forum():forum_id=request.query.idpage=request.query.pageor'1'returntemplate('Forum ID: {{id}} (page {{page}})',id=forum_id,page=page)
HTML<form> Handling¶
Let us start from the beginning. In HTML, a typical<form> looks something like this:
<formaction="/login"method="post"> Username:<inputname="username"type="text"/> Password:<inputname="password"type="password"/><inputvalue="Login"type="submit"/></form>
Theaction attribute specifies the URL that will receive the form data.method defines the HTTP method to use (GET orPOST). Withmethod="get" the form values are appended to the URL and available throughRequest.query as described above. This is sometimes considered insecure and has other limitations, so we usemethod="post" here. If in doubt, usePOST forms.
Form fields transmitted viaPOST are stored inRequest.forms as aFormsDict. The server side code may look like this:
frombottleimportroute,request@route('/login')deflogin():return''' <form action="/login" method="post"> Username: <input name="username" type="text" /> Password: <input name="password" type="password" /> <input value="Login" type="submit" /> </form> '''@route('/login',method='POST')defdo_login():username=request.forms.usernamepassword=request.forms.passwordifcheck_login(username,password):return"<p>Your login information was correct.</p>"else:return"<p>Login failed.</p>"
File Uploads¶
To support file uploads, we have to change the<form> tag a bit. First, we tell the browser to encode the form data in a different way by adding anenctype="multipart/form-data" attribute to the<form> tag. Then, we add<inputtype="file"/> tags to allow the user to select a file. Here is an example:
<formaction="/upload"method="post"enctype="multipart/form-data"> Category:<inputtype="text"name="category"/> Select a file:<inputtype="file"name="upload"/><inputtype="submit"value="Start upload"/></form>
Bottle stores file uploads inRequest.files asFileUpload instances, along with some metadata about the upload. Let us assume you just want to save the file to disk:
@route('/upload',method='POST')defdo_upload():category=request.forms.categoryupload=request.files.get('upload')name,ext=os.path.splitext(upload.filename)ifextnotin('.png','.jpg','.jpeg'):return'File extension not allowed.'save_path=get_save_path_for_category(category)upload.save(save_path)# appends upload.filename automaticallyreturn'OK'
FileUpload.filename contains the name of the file on the clients file system, but is cleaned up and normalized to prevent bugs caused by unsupported characters or path segments in the filename. If you need the unmodified name as sent by the client, have a look atFileUpload.raw_filename.
TheFileUpload.save method is highly recommended if you want to store the file to disk. It prevents some common errors (e.g. it does not overwrite existing files unless you tell it to) and stores the file in a memory efficient way. You can access the file object directly viaFileUpload.file. Just be careful.
JSON¶
For JavaScript and REST APIs it is very common to sendapplication/json to the server instead of from data.TheRequest.json attribute contains the parsed data structure if available, orNone for emptyrequests or those that did not containapplication/json data. Parsing errors trigger an appropiateHTTPError.
Raw Request Data¶
You can access the raw body data as a file-like object viaRequest.body. This is aio.BytesIO buffer or a temporary file depending on the content length andRequest.MEMFILE_MAX setting. In both cases the body is completely buffered before you can access the attribute. If you expect huge amounts of data and want to get direct unbuffered access to the stream, have a look atrequest['wsgi.input'].
WSGI Environment¶
EachBaseRequest instance wraps a WSGI environment dictionary which is stored inRequest.environ. Most of the interesting information is also exposed through special methods or properties, but if you want to access the rawWSGI environ directly, you can do so:
@route('/my_ip')defshow_ip():ip=request.environ.get('REMOTE_ADDR')# or ip = request.get('REMOTE_ADDR')# or ip = request['REMOTE_ADDR']returntemplate("Your IP is: {{ip}}",ip=ip)
Templates¶
Bottle comes with a fast and powerful built-in template engine calledSimpleTemplate. To render a template you can use thetemplate() function or theview() decorator. All you have to do is to provide the name of the template and the variables you want to pass to the template as keyword arguments. Here’s a simple example of how to render a template:
@route('/hello')@route('/hello/<name>')defhello(name='World'):returntemplate('hello_template',name=name)
This will load the template filehello_template.tpl and render it with thename variable set. Bottle will look for templates in the./views/ folder or any folder specified in thebottle.TEMPLATE_PATH list.
Theview() decorator allows you to return a dictionary with the template variables instead of callingtemplate():
@route('/hello')@route('/hello/<name>')@view('hello_template')defhello(name='World'):returndict(name=name)
Syntax
The template syntax is a very thin layer around the Python language. Its main purpose is to ensure correct indentation of blocks, so you can format your template without worrying about indentation. Follow the link for a full syntax description:SimpleTemplateHere is an example template:
%if name == 'World':<h1>Hello{{name}}!</h1><p>This is a test.</p>%else:<h1>Hello{{name.title()}}!</h1><p>How are you?</p>%end
Caching
Templates are cached in memory after compilation. Modifications made to the template files will have no affect until you clear the template cache. Callbottle.TEMPLATES.clear() to do so. Caching is disabled in debug mode.
Structuring Applications¶
Bottle maintains a global stack ofBottle instances and uses the top of the stack as a default for some of the module-level functions and decorators. Theroute() decorator orrun() function for example are shortcuts forBottle.route() orBottle.run() on the default application:
@route('/')defhello():return'Hello World'if__name__=='__main__':run()
This is very convenient for small applications and saves you some typing, but also means that, as soon as your module is imported, routes are installed to the global default application. To avoid this kind of import side-effects, Bottle offers a second, more explicit way to build applications:
app=Bottle()@app.route('/')defhello():return'Hello World'app.run()
Separating the application object improves re-usability a lot, too. Other developers can safely import theapp object from your module and useBottle.mount() to merge applications together.
Added in version 0.13.
Starting with bottle-0.13 you can useBottle instances as context managers:
app=Bottle()withapp:# Our application object is now the default# for all shortcut functions and decoratorsassertmy_appisdefault_app()@route('/')defhello():return'Hello World'# Also useful to capture routes defined in other modulesimportsome_package.more_routes
Glossary¶
- callback¶
Programmer code that is to be called when some external action happens.In the context of web frameworks, the mapping between URL paths andapplication code is often achieved by specifying a callback functionfor each URL.
- decorator¶
A function returning another function, usually applied as a function transformation using the
@decoratorsyntax. Seepython documentation for function definition for more about decorators.- environ¶
A structure where information about all documents under the root issaved, and used for cross-referencing. The environment is pickledafter the parsing stage, so that successive runs only need to readand parse new and changed documents.
- handler function¶
A function to handle some specific event or situation. In a webframework, the application is developed by attaching a handler functionas callback for each specific URL comprising the application.
- source directory¶
The directory which, including its subdirectories, contains allsource files for one Sphinx project.
