Cara menggunakan pythonanywhere mysql version

This post will go through setting up a virtual environment for python 3.6 and using the MySQL database, which comes with pythonanywhere. I will be using flask_sqlalchemy as a medium to pull and insert data to the MySQL database provided by pythonanywhere. The virtual environment will help contain the relevant modules and keep the application more reliable and portable.

Creating the virtualenvironment

In bash type the following command to locate the python3.6 file, as we will need it to create the virtualenv specific to that python version.

which python3.6

This was the output

/home/danielc92/mysite/python3.6-venv/bin/python3.6

So in order to create the virtual environment I’ll use the virtualenv command, specifying the python location.

virtualenv --python=/home/danielc92/mysite/python3.6-venv/bin/python3.6 python3.6-venv

After its created it can be activated (in order to install requirements).

From the folder, where the virtual environment resides use this command.

source python3.6-venv/bin/activate

I have to install the following modules in order to connect to MySQL, and for flask to talk to MySQL.

pip install flask flask_sqlalchemy mysqlclient

In order for the web app to use the virtual environment you have to link it in the web dashboard. After reloading the application the virtualenv will be in use.

Cara menggunakan pythonanywhere mysql version

Creating the database

In the database tab, I created a MySQL database, as well as a password. You can connect to the database via ‘Start a console’ under the ‘Your Databases’ area. In my case I have two but I’ll be using default for this application.

Cara menggunakan pythonanywhere mysql version

You can check the status of the database like so.

Cara menggunakan pythonanywhere mysql version

You can also check databases and tables which currently exist, this is good for verifying events caused by the application. The output shows I have two databases, default and test, as well as one table ‘people’.

Cara menggunakan pythonanywhere mysql version

Connecting application to the database

First I edit the index.html template (from the mysite directory).

nano templates/index.html

This template will be called by the application, which will except an SQLAlchemy result set, iterate through the results and display them into a table.

Cara menggunakan pythonanywhere mysql version

Cara menggunakan pythonanywhere mysql version

In the flask_app.py file. A few things are happening in this file:

  • Connection to mysql database uri using flask_sqlalchemy
  • Setting up the model for the ‘people’ table in default database.
  • Calling create_all() to create the table if it doesnt exist.
  • / route (home) which calls all the results from the people table and passes the result set as a variable into the index template.
  • /insert route which retrieves parameters from a url and inserts them into people table using the ORM defined above.

Note that you do not have to specify the id because it will auto-increment by default if set to primary_key=True.

from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
import os

app = Flask(__name__)
URI = "mysql://{username}:{password}@{hostname}/{databasename}".format(username='danielc92',
password='secret',
hostname='danielc92.mysql.pythonanywhere-services.com:3306',
databasename='danielc92$default')
app.config['SQLALCHEMY_DATABASE_URI']= URI
app.config['SQLALCHEMY_POOL_RECYCLE'] = 280

db = SQLAlchemy(app)

class People(db.Model):
  __tablename__='people'

  id=db.Column(db.Integer, primary_key=True)
  name=db.Column(db.Text)
  food=db.Column(db.Text)
  occupation=db.Column(db.Text)
  country=db.Column(db.Text)

db.create_all()
db.session.commit()

@app.route('/')
def home():
    results = People.query.all()
    return render_template('index.html', results = results)

@app.route('/insert')
def insert():
    name = request.args.get('name')
    food = request.args.get('food')
    occupation = request.args.get('occupation')
    country = request.args.get('country')

    insert_this = People(name=name, food=food, occupation=occupation, country=country)

    db.session.add(insert_this)
    db.session.commit()
    return 'Successfully inserted record'

Testing – Inserting and viewing data

Before testing reload the application in the Web tab.

By using the following urls I can insert data, I avoided using a form for this example because it’s too time consuming.