How to create a basic database driven website with Bottle and MySQL
- Create Pythonanywhere Account
- Create MySQL Database
- Create users Table From Script
- Create Bottle Web Application
- Configure Web Application
- Create Web Templates
- Replace and configure bottle_app.py (The Controller)
- Launch and Run the Application
- Go to Pythonanywhere Website (right click on this link to open in new window) and click on "Pricing and signup"
- Click on the button "Create a Beginner account".
- Add your Username, Email, and create your password, the click "Register".
Note: Write down and remember this pythonanywhere password. You will need it later
- After you have created your account, confirm your email.
- Instantiate a MySQL database by clicking on the "Databases" link.
- 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
- 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
- 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;
- Copy the script below. We will paste it into the MySQL console to create the "users" table. Then press "enter"
- You should get a message that the query ran OK.
- At the MySQL prompt type "show tables" which should show you that the "users" table was successfully created.
- Click on the python icon to return to the dashboard.
- Click on the "Web" tab.
- Add a new web app.
- Click "Next" to create your domain name.
- Select the "Bottle" framework.
- Select the latest Python version.
- Accept the default path information for your Bottle project and click "Next".
- Once the site has been created, scroll down to see the file locations of your site.
- Let's click at the wsgi configuration file which holds important information about our project.
-
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)
- Click on the menu bar, then click "Web"
- Click on the "mysite" directory.
- Create a new directory by typing "views", then click "New directory".
- Create a new file by typing "create_user.tpl" and click "New file".
- You now have an empty template called "create_user.tpl".
- 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>
- Click on the "views" folder.
- Create a new file by typing "show_users.tpl" and click "New file".
- You now have an empty template called "show_users.tpl".
- 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>
- Click on the "mysite" folder.
- 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.
- This is the default code that is found in "bottle_app.py".
- 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()
- 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",
...
- 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"
}
- Click "Save".

- Click on the menu bar then select "Web".
- Whenever we make a change to any of the files, we need to click on the reload button.
- Click on the web application address.
- You now see a page with no users listed. Click on "Add a New User".
- Add a first and last name and click "save".
- You will see a message stating that the record was created with an ID number. Click "Show All Users".




































