Skip to content

matjmiles/Bottle-on-Pythonanywhere-Tutorial

Repository files navigation

Bottle on Pythonanywhere Tutorial

How to create a basic database driven website with Bottle and MySQL

Contents

Create Pythonanywhere Account

  1. Go to Pythonanywhere Website (right click on this link to open in new window) and click on "Pricing and signup"

pricing and signup

  1. Click on the button "Create a Beginner account".

create beginner account

  1. Add your Username, Email, and create your password, the click "Register".

Note: Write down and remember this pythonanywhere password. You will need it later

create password

  1. After you have created your account, confirm your email.

confirm email

Create MySQL Database

  1. Instantiate a MySQL database by clicking on the "Databases" link.

create db

  1. By default, the MySQL tab is selected. You must now create a database password which is different from your pythonanywhere password.

Note: Write down and remember this database password. You will need it later

initialize mysql

  1. The system automatically creates a database called "default". The fully qualified database name is <your_pythonanywhere_account_name>$default. In this case "bottlejmj$default". Click on the db name to open a MySQL console

open mysql console

Create users Table From Script

  1. Copy the script below. We will paste it into the MySQL console to create the "users" table.

CREATE TABLE users ( id int NOT NULL AUTO_INCREMENT COMMENT 'primary key', first_name varchar(25) NOT NULL, last_name varchar(25) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

  1. Copy the script below. We will paste it into the MySQL console to create the "users" table. Then press "enter"

paste script

  1. You should get a message that the query ran OK.

table created

  1. At the MySQL prompt type "show tables" which should show you that the "users" table was successfully created.

show tables

Create Bottle Web Application

  1. Click on the python icon to return to the dashboard.

return to dashboard

  1. Click on the "Web" tab.

click on web tab

  1. Add a new web app.

add web ap

  1. Click "Next" to create your domain name.

create web ap domain

  1. Select the "Bottle" framework.

select bottle

  1. Select the latest Python version.

select python

  1. Accept the default path information for your Bottle project and click "Next".

accept bottle path defaults

  1. Once the site has been created, scroll down to see the file locations of your site.

scroll down

Configure Webb Application

  1. Let's click at the wsgi configuration file which holds important information about our project.

scroll down

  1. The first arrow points to the home location of our web application (/home/bottlemjm/mysite). The second arrow points to the location of the views or web templates that will display content (/home/bottlemjm/mysite/views) The third arrow points to "import application" which refers to the bottle_app information and how it will be imported into the controller. Many web applications follow the MVC framework or model, view, controller. In this project:

    Model = MySQL DB (the data structures for the project) Viewer = create_user.tpl, show_users.tpl (web templates used to display data to users) Controller = /home/bottlemjm/mysite/bottle_app.py (The program code)

wsgi_params

Create Web Templates

  1. Click on the menu bar, then click "Web"

wsgi_params

  1. Click on the "mysite" directory.

go to mysite directory

  1. Create a new directory by typing "views", then click "New directory".

create directory

  1. Create a new file by typing "create_user.tpl" and click "New file".

create user template

  1. You now have an empty template called "create_user.tpl".

add code

  1. Copy and paste the code snippet below into the template then click "Save".
<h2>Create a new User:</h2>
%# Send a GET request with the first and last names to the create_user
%# function which resides in ./mysite/bottle_app.py

<div width="250px">
<form action="/create_user" method="GET">
    First Name:
  <input type="text" size="100" maxlength="100" name="first_name">
  <br />
  Last Name:
  <input type="text" size="100" maxlength="100" name="last_name">
  <input type="submit" name="save" value="save">
</form>
</div>
  1. Click on the "views" folder.

go to views folder

  1. Create a new file by typing "show_users.tpl" and click "New file".

create show_users

  1. You now have an empty template called "show_users.tpl".

add code

  1. Copy and paste the code snippet below into the template then click "Save".
<h2>Below are a list of users</h2>
<table border="1">
  <tr>
    <td><strong>ID</strong></td>
     <td><strong>First Name</strong></td>
     <td><strong>Last Name</strong></td>
  </tr>

%# The % signs mark the beginning and end of python code.
%# The rows object is a recordset.
%# The row ojbect is a row in the recordset
%# The {{ }} outputs data from the row to the screen
%# The row[0] means the first column in the row and so on

%for row in rows:
  <tr>
    <td>{{row[0]}}</td>
     <td>{{row[1]}}</td>
     <td>{{row[2]}}</td>
  </tr>
%end

</table>
<div style="padding-top: 15px">
<a href="/create_user"><h3>Add a New User<h3></a>
</div>

Replace and configure bottle_app.py (The Controller)

  1. Click on the "mysite" folder.

go to mysite folder

  1. Click on the "bottle_app.py" folder. This is the controller file which will contain the functions necessary to retreive data from the database and pass it to the templates for display.

edit bottle app

  1. This is the default code that is found in "bottle_app.py".

go to mysite folder

  1. Let's replace this default code with the code shown below.
from bottle import default_app, get, template, request
import mysql.connector



####### configure mysql db connfiguration properties ###############

db_config = {
        "host":"<your pythonanywhere account name>.mysql.pythonanywhere-services.com",
        "user":"<your mysql username>",
        "password":"<your mysql password>",
        "database":"<your pythonanywere account name>$default"
        }

####### setup DB connection and cursor  ############################

mysqlConnection = mysql.connector.connect(**db_config)
cursor = mysqlConnection.cursor()


####### route definitions  #########################################

@get("/create_user", method='GET')
def create_user():

    if request.GET.save:

        var_first_name = request.query.first_name
        var_last_name = request.query.last_name

        insert_stmt = (
            "INSERT INTO users(first_name, last_name) VALUES (%s, %s)"
        )

        data = (var_first_name, var_last_name)

        cursor.execute(insert_stmt, data)
        new_id = cursor.lastrowid

        mysqlConnection.commit()


        return '<p>The new user created with ID %s</p> \
        <div style="padding-top: 5px"> <a href="/create_user"> \
        <h3>Add Another User<h3></a> </div> \
        <div style="padding-top: 5px"> <a href="/"> \
        <h3>Show All User<h3></a>'  % new_id

    else:
        return template('create_user.tpl')


@get("/")
def get_users():
    cursor.execute("SELECT * FROM users")
    rows = cursor.fetchall()
    output = template('show_users.tpl', rows=rows)
    return output


####### setting default app  #########################################
# All application settings are found in the wsgi.py file
application = default_app()
  1. We now need to finish editing the db_config parameters. Change the code <your pythonanywhere account name> to your pythonanywhere account name. So if your Pythonanywhere account name is jimPython, the host parameter would look like the code snippet below.
####### configure mysql db connfiguration properties ###############

db_config = {
        "host":"jimPython.mysql.pythonanywhere-services.com",
        ...

  1. Now add the MySQL username and password you setup earlier, and finally add your pythonanywhere account name to the database string
####### configure mysql db connfiguration properties ###############

db_config = {
        "host":"jimPython.mysql.pythonanywhere-services.com",
        "user":"mysqlUser",
        "password":"mysqlPasswd",
        "database":"jimPython$default"
        }
  1. Click "Save".

![save bottle_app.py](images/30%20click save.png)

Launch and Run the Application

  1. Click on the menu bar then select "Web".

click web

  1. Whenever we make a change to any of the files, we need to click on the reload button.

reload website

  1. Click on the web application address.

click web

  1. You now see a page with no users listed. Click on "Add a New User".

click web

  1. Add a first and last name and click "save".

click web

  1. You will see a message stating that the record was created with an ID number. Click "Show All Users".

click web

About

How to create a basic database driven website with Bottle and MySQL

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published