Cara menggunakan pythonanywhere flask

PythonAnywhere adalah layanan web hosting dan IDE online berbasis python. Kita dapat mengunggah dan memasang aplikasi web berbasis Python yang menggunakan WSGI, misalnya Django dan Flask.

Pada contoh ini, aplikasi web Django yang akan diuji telah diunggah terlebih dahulu di repository online git (bisa menggunakan GitHub maupun Bitbucket). Pastikan web app bisa berjalan di komputer lokal dan semua migrasi model basis data sudah siap di-apply di web hosting. Sistem basis data yang akan digunakan pada contoh ini adalah SQLite (berbasis file), yang merupakan default Django sehingga kita tidak perlu setup basis data lagi.

Langkah-langkah

  • Pada menu 'Console', buka bash console, lalu pastikan telah berada di direktori home (misalnya /home/username).

Cara menggunakan pythonanywhere flask

$ pwd
/home/username
  • Lakukan git clone repository aplikasi web Django yang akan di deploy, lalu tuju direktori proyek.
$ git clone https://alamat/repo/online/...
$ cd nama_proyek_django
  • Buat dan aktifkan virtualenv (opsional). Kita bisa menggunakan cara ini untuk menginstal modul-modul python berbeda di setiap virtualenv. Saya sudah pernah membuat ringkasan langkah-langkah menginstal virtualenv dan virtualenvwrapper sebelumnya. Catat lokasi virtualenv (biasanya di /home/nama_user/.virtualenvs/nama_virtualenv).

  • Instal modul-modul python yang dibutuhkan aplikasi web Django. Biasanya, di komputer lokal kita menjalankan perintah pip freeze > requirements.txt lalu menyertakan file txt tersebut di repository bersama aplikasi web kita.

Di komputer lokal:

(my_virtualenv) $ pip freeze
beautifulsoup4==4.6.0
Django==2.0.4
pytz==2018.4
requests==2.12.4
(my_virtualenv) $ pip freeze > reqs.txt

Kemudian dilanjutkan dengan git commit ... ,

$ git clone https://alamat/repo/online/...
$ cd nama_proyek_django
0 , dan lain-lain.

Di web hosting PythonAnywhere (via bash) setelah melakukan

$ git clone https://alamat/repo/online/...
$ cd nama_proyek_django
1 atau
$ git clone https://alamat/repo/online/...
$ cd nama_proyek_django
2 :

(my_hosting_virtualenv) $ pip install -r reqs.txt

(Karena kita akan menjalankan aplikasi Django, sudah pasti kita membutuhkan paket Django.)

  • Catat lokasi file wsgi.py aplikasi web Django (biasanya

    $ git clone https://alamat/repo/online/...
    $ cd nama_proyek_django
    
    3).

  • Pada PythonAnywhere, tuju menu 'Web'. Pada bagian 'Code', pastikan 'Working directory' dan 'Python version' sudah sesuai (misalnya python 3.5). Pada 'WSGI configuration file', ubah dengan kode berikut:

import os
import sys

# Direktori aplikasi web
sys.path.append('/home/nama_user/nama_proyek')

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "nama_proyek.settings")

application = get_wsgi_application()
  • Pada bagian 'Virtualenv', isi dengan direktori virtualenv yang valid (langkah 3).

  • Untuk menampilkan file static (css, javascript, gambar, dan lain-lain), kita bisa mengisi nilai variabel

    $ git clone https://alamat/repo/online/...
    $ cd nama_proyek_django
    
    4 pada file settings.py dengan direktori absolut pada web hosting (misalnya
    $ git clone https://alamat/repo/online/...
    $ cd nama_proyek_django
    
    5). Kemudian jalankan perintah
    $ git clone https://alamat/repo/online/...
    $ cd nama_proyek_django
    
    6. Isikan direktori tersebut pada bagian 'Static files'. Untuk URL-nya, biasanya sama dengan nilai
    $ git clone https://alamat/repo/online/...
    $ cd nama_proyek_django
    
    7 pada file settings.py.

  • Tentukan apakah kita akan memproteksi aplikasi web dengan password pada bagian 'Password protection'.

  • Terakhir, pada bagian atas laman pengaturan, klik tombol 'Reload'. Cek dengan mengakses URL aplikasi web kita, misalnya username.pythonanywhere.com.

Jangan lupa melakukan migrasi basis data di web hosting jika diperlukan (

$ git clone https://alamat/repo/online/...
$ cd nama_proyek_django
8 dan
$ git clone https://alamat/repo/online/...
$ cd nama_proyek_django
9). Jika menggunakan sistem basis data selain SQLite, lakukan pengaturan di menu 'Databases'.

The first option works well if you're just playing around and want to throw something together from scratch. Go to the Web Tab and hit Add a new Web App, and choose Flask and the Python version you want.

The second option is described in more detail below

Getting your code onto PythonAnywhere

This guide assumes you've already managed to get your code onto PythonAnywhere. Check out the uploading and downloading files guide if you need to.

For the purposes of these examples, we'll assume your code lives at

$ workon my-virtualenv
(my-virtualenv)$
0

Check your config

If you're importing existing code, review all of your Flask configuration settings to ensure that they match their new home. For instance, if you've specified a SERVER_NAME in your config, make sure that it matches the web app name.

Setting up your virtualenv

Open up a new Bash console from your Dashboard and run

mkvirtualenv --python=/usr/bin/python3.6 my-virtualenv  # use whichever python version you prefer
pip install flask

You'll see the prompt changes from a

$ workon my-virtualenv
(my-virtualenv)$
1 to saying
$ workon my-virtualenv
(my-virtualenv)$
2 -- that's how you can tell your virtualenv is active. Whenever you want to work on your project in the console, you need to make sure the virtualenv is active. You can reactivate it at a later date with

$ workon my-virtualenv
(my-virtualenv)$

You can also install any other dependencies you may have at this point, like Sqlalchemy, using

$ workon my-virtualenv
(my-virtualenv)$
3, or
$ workon my-virtualenv
(my-virtualenv)$
4, if you have a requirements.txt

Setting up the Web app using Manual configuration

Go to the Web Tab and hit Add a new web app. Choose Manual Configuration, and then choose the Python version -- make sure it's the same version as the one you used in your virtualenv

Now go to the Virtualenv section, and enter your virtualenv name: my-virtualenv. When you hit enter, you'll see it updates to the full path to your virtualenv (/home/yourusername/.virtualenvs/my-virtualenv).

Finally, go edit the wsgi configuration file. You'll find a link to it near the top of the Web tab.

Configuring the WSGI file

To configure this file, you need to know which file your flask app lives in. The flask app usually looks something like this:

app = Flask(__name__)

Make a note of the path to that file, and the name of the app variable (is it "app"? Or "application"?) -- in this example, let's say it's

$ workon my-virtualenv
(my-virtualenv)$
5, and the variable is "app".

In your WSGI file, skip down to the flask section, uncomment it, and make it looks something like this:

import sys
path = '/home/yourusername/mysite'
if path not in sys.path:
   sys.path.insert(0, path)

from flask_app import app as application

Do not use $ workon my-virtualenv (my-virtualenv)$ 6

When you're using Flask on your own PC, you'll often "run" flask using a line that looks something like this:

app.run(host='127.0.0.1',port=8000,debug=True)

That won't work on PythonAnywhere -- the only way your app will appear on the public internet is if it's configured via the web tab, with a wsgi file.

More importantly, if

$ workon my-virtualenv
(my-virtualenv)$
6 gets called when we import your code, it will crash your app, and you'll see a 504 or a 502 error on your site, as detailed in this help page.

Thankfully, most Flask tutorials out there suggest you put the

$ workon my-virtualenv
(my-virtualenv)$
6 inside an
$ workon my-virtualenv
(my-virtualenv)$
9 clause, which will be OK, because that won't get run when we import it.

This is OK:

app = Flask(__name__)

@app.route('/')
def home():
    # etc etc, flask app code

if __name__ == '__main__':
    app.run()

This is not OK:

app = Flask(__name__)
@app.route('/')
def home():
    # etc etc, flask app code

app.run()

What about my database config?

Many guides on the Internet also suggest you put your database setup inside the

app = Flask(__name__)
0 clause, like this:

if __name__ == '__main__':
    db.create_all()
    app.run()

That will work fine on your machine, but, again, we don't want to use app.run() on PythonAnywere. But you'll still want to be able to run

app = Flask(__name__)
1 every so often on PythonAnywhere, to update your database tables or whatever it may be.

Two solutions -- either just run it from a Bash console (remembering to activate your virtualenv first) and then Ctrl+C the flask server when it runs