⌘BABAKOV.NET Let's code!
100% [dark] [ru]

Python Bottle Guide (Translation) Part 2 - Hello World

In the previous part, we considered the installation of Bottle:
Python Bottle Guide (Translation) Part 1 - Installation

In this part, we will go further and consider a simple example of a "Hello World" website application.

Here it is assumed that you have already installed Bottle, or the library has been copied to the project folder.

Let's start with a very simple example "Hello World!":

from bottle import route, run

@route(\'/hello\')
def hello():
    return "Hello World!"

run(host=\'localhost\', port=8080, debug=True)



That's it.
Run the script, go to the browser by address localhost:8080/hello and see in our browser on the page the inscription “Hello World!”.

Let's break it down:

The decorator route() binds the URL address to a code fragment. In our case, we bind the path /hello to the function hello(). This is called a route (route()) and is the most important part to understand in this structure. You can set up as many routes as you like. Each time the Web browser requests a specific URL address, the associated function will be called, and the returned value from this function will be returned back to the Web browser.
It's all simple - simple!

The method run() called at the end of the program, starts the built-in WEB-server. It starts on the address Localhost (127.0.0.1) on port 8080 and serves incoming requests until you press the key combination «Control-C». In the future, the server can be changed, but for development, the built-in server will be quite enough, it does not require installation and is incredibly easy to use - what you need for testing and debugging the application.

Also, in our first application, the debug mode «debug=True» is included, this mode is very useful for development and debugging, but it needs to be disabled when publishing the application (site). This needs to be remembered.

That's it for now, just a demonstration of the basic principles of how the application is set up using Bottle.

For simplicity, in most examples in this guide, the route() decorator is used at the module level to determine routes. Thus, routes are added to the global "default application", an instance of Bottle, which is automatically created when the first call to route() is made. If you prefer a more object-oriented approach, you can create a separate application object and use it instead of the global one:

from bottle import Bottle, run

app = Bottle()

@app.route(\'/hello\')
def hello():
    return "Hello World!"

run(app, host=\'localhost\', port=8080)



Object-oriented approach will be described later. Just keep in mind that you have a choice.

Continuation: Python Bottle Guide (Translation) Part 3 - Routing requests

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.