Cara menghosting aplikasi ringan secara gratis

Saat Anda mencari layanan web hosting, ada banyak pilihan gratis yang tersedia. Tetapi tidak banyak tempat di mana Anda dapat menghosting aplikasi web full stack yang melibatkan API, CGI, atau kueri backend AJAX - terutama jika Anda ingin menggunakan sesuatu selain PHP.

Artikel ini adalah panduan "berjalan sebelum Anda dapat berlari" yang sederhana namun bermakna tentang cara mulai menghosting skrip Anda di server cloud.

Kapan menggunakan Platform Aplikasi Cloud

Cloud Application Platforms bekerja dengan baik dalam skenario di mana Anda memerlukan sedikit kode untuk dijalankan di server. Banyak dari platform ini menawarkan rangkaian wadah aplikasi berbasis Linux (yang tampak seperti mesin virtual) tempat Anda menerapkan kode yang Anda kembangkan di komputer lokal dengan sekumpulan kata kunci baris perintah.

Heroku adalah salah satu layanan yang dapat Anda gunakan untuk menghosting kode Anda (dalam berbagai bahasa) dengan relatif mudah. Ini menawarkan model freemium di mana mereka memungkinkan Anda menggunakan sekitar 500 jam komputasi secara gratis (harga lengkap mereka ada di sini).

Setelah Anda menulis kode Anda di desktop lokal, Anda dapat menjalankan perintah yang menerapkan kode tersebut ke ruang kerja di Heroku. Kode kemudian dijalankan tergantung pada pemicu. Pemicu dapat berupa pekerjaan terjadwal, server web yang dipicu melalui permintaan halaman web, atau sesuatu yang berjalan terus-menerus dan memproses data - yang bisa menjadi sangat mahal.

Yang menyenangkan adalah Anda tidak perlu khawatir tentang sistem operasi (memori, penyimpanan, CPU, patch keamanan) karena semuanya dikelola untuk Anda - tetapi pada saat yang sama itu berarti Anda memiliki fleksibilitas terbatas karena Anda tidak dapat melakukannya. mengalokasikan sumber daya secara langsung.

Beberapa contoh spesifik di mana Heroku dapat bekerja dengan baik untuk Anda:

  • Hosting situs web Anda sendiri di mana Anda ingin menulis server web Anda sendiri
  • Mengambil data secara berkala dari sebuah situs web dan kemudian menyimpannya di database untuk dianalisis
  • Menawarkan server API untuk tugas tertentu. Hal-hal seperti menawarkan data cuaca, menyimpan data sensor Internet of Things, atau panggilan layanan web untuk model pembelajaran mesin
  • Layanan database (meskipun layanan seperti Firebase mungkin lebih cocok)

Arsitektur Heroku

Heroku menyediakan mesin virtual (VM) ringan bagi Anda untuk menerapkan kode Anda. Perhatikan bahwa di bawah opsi gratis, Anda dapat menerapkan hingga 5 aplikasi yang dianggap sebagai 5 VM ringan. Untuk aplikasi Anda yang sebenarnya, Anda diberikan subdomain URL terpisah di bawah Heroku. Jadi nama proyek Anda harus unik.

Ruang kerja ini memiliki ruang sendiri untuk komponen seperti: file kode dan sumber daya (bukan file data dinamis), database (Postgres), dan file log.

Di desktop lokal Anda, Heroku menggunakan nama direktori Anda untuk menentukan proyek Anda, dan juga agar Heroku memahami konteks Anda. Jadi Anda dapat memiliki banyak proyek di direktori yang berbeda dan ketika Anda menjalankan perintah Heroku - pastikan Anda melakukannya di folder yang benar.

Satu hal penting yang perlu Anda waspadai (yang saya temukan dengan susah payah selama berjam-jam debugging - saya harap saya lebih memperhatikan dokumentasi) adalah bahwa semuanya dijalankan dari memori. Tidak ada penyimpanan yang persisten. Saya akan mengatakannya lagi - Anda tidak dapat menyimpan file apa pun di server file! Untuk persistensi, Heroku menawarkan database SQL pasca-kemajuan tempat Anda dapat menambahkan record sesuai kebutuhan.

Contoh sederhana - deteksi perubahan situs web

Berikut adalah panduan langkah demi langkah untuk mendapatkan contoh kerja dari layanan sederhana yang akan mengirimkan email kepada Anda jika situs web telah berubah - pada dasarnya adalah tiruan dari www.changedetection.com. Akan ada beberapa komponen utama dari ini:

  1. Database yang akan menyimpan: (a) alamat email untuk memberi tahu situs web yang diubah; (b) situs web yang akan dilacak; (c) 'salinan' terakhir dari situs web
  2. Sepotong kode yang akan memeriksa situs web tertentu dari database di # 1 (skrip Python)
  3. Penjadwal pekerjaan yang akan menjalankan program di # 2 (setara dengan pekerjaan cron)
  4. Antarmuka pengguna web tempat Anda dapat menambah / menghapus situs web yang akan dipantau ke dalam database yang disebutkan di # 1
  5. Mekanisme untuk mengirim email

Memahami komponen ini akan membekali Anda dengan keterampilan untuk melakukan banyak hal. Saya mempelajari semua hal ini melalui berbagai sumber, jadi ini bertindak sebagai pos gabungan.

Asumsi

Panduan berikut membuat asumsi berikut:

  • Anda memiliki akun GitHub - jika belum, buat akun di sini. Anda juga harus membaca panduan sederhana ini.
  • Anda sudah memiliki akun Heroku - jika belum, buatlah di sini.
  • Anda menjalankan mesin Windows - jika tidak, tidak masalah, instruksinya sangat mirip di lingkungan lain
  • Anda sudah menginstal Python - jika belum, buka di sini untuk menginstalnya
  • Anda sudah dapat memprogram dengan Python - jika belum, saya sarankan Anda mempelajari beberapa dasar-dasarnya terlebih dahulu. Beberapa panduan ada di sini.
  • Anda tahu SQL - jika tidak, silakan buka di sini.

Gambaran umum langkah-langkahnya

Saya menemukan bahwa melalui pendekatan 'berjalan sebelum Anda dapat berlari' membantu proses pembelajaran. Ini juga berfungsi sebagai dokumentasi untuk Anda sendiri tentang cara menyelesaikan setiap bagian dari proses yang lebih besar. Dengan begitu, jika sesuatu gagal dalam usaha masa depan Anda, Anda memiliki kesempatan lebih baik untuk mencari tahu di mana kesalahannya.

Langkah 1 : Kembangkan antarmuka pengguna web - buat Hello World terlebih dahulu

Langkah 2 : Ketekunan - buat database

Langkah 3 : Periksa situs web untuk melihat adanya perubahan

Langkah 4: Kirim pemberitahuan email tentang perubahan

Langkah 5 : Buat daftar output di halaman web

Langkah 6: Terapkan

Langkah 1: Kembangkan antarmuka pengguna web - buat Hello World terlebih dahulu

First, let’s get a simple program deployed onto Heroku to get things started. This program will be a precursor to the web user interface (item #4) in the components list above. In order to serve up a page, we could simply have an HTML page, but then we would need to have a web server to server that file. In other words, when you type in the URL of the website, a program would need to interpret the request, then provide the contents of the HTML file. You can create your own mini web server with the Flask Python library, which is what we’ll do.

  • Create a folder called webchecker and go into that directory (this directory name does not have to be the same as the Heroku application name)
  • Install the Flask library. Enter the command: npm Flask
  • Create the following Python program and name it showchecks.py:

Before you deploy to Heroku, test that it works on your local PC. You can test it with the following steps:

  • Run the program: python webchecker.com
  • Open up your browser on your local pc and open up the page: //localhost:5000/hello

Next, let’s deploy this to Heroku. Before you can deploy, there needs to be a few more files that need to be included to help Heroku know more about your application.

First, the requirements.txt

Second, the file to tell Heroku what to run when a webrequest is made:

Finally, the runtime version of Python to use (default is 2.7, but we want to specify the latest version of Python):

Hence, you should have four files:

  1. showchecker.py which is the code
  2. requirements.txt for the list of non-standard library dependencies. Whenever you have new libraries which are not part of the Python Standard Library — i.e. you need to install them using a tool such as “pip” — then add these here. You can find the version of an installed library such as Flask by running the command: pip show Flask in the command line
  3. Procfile which is the actual Python script to run when the website is called — make sure to update this if you change the Python file
  4. runtime.txt which is the actual version of python to use

You can deploy with the following steps from the command line:

  1. heroku create webchecker01 — buildpack heroku/python
  2. git add *.* *
  3. git status
  4. git commit -m “all files”
  5. git push heroku master

For the command #1 (heroku create…), the “webechecker01” part is the unique name you’ll need to provide for the name of the app.

For command #3 (git status) this will tell you what files are ready to be deployed. Make sure all files are there, if not add them using git add me>.

Now you can check your website: .herokuapp.com/hello

Original text


Let’s also make sure we can see the logs since this is a great way to see what’s going on with your app server. On your PC and in the webchecker directory, run the command: heroku logs

You’ll see the last execution steps. If things aren’t working as expected, this is your first stop to find out more detail.

You can also go to the Heroku dashboard to see your consumption:

//dashboard.heroku.com

Step 2: Persistence — create a database

In order to make more useful programs, you’ll need to have a data store of sorts. This is where the Postgres database service comes into play. You first need to deploy the Heroku database service, then create your tables, and finally be able to connect to the database from your code locally (for testing).

To deploy a database service, first create it using the following command:

heroku addons:create heroku-postgresql:hobby-dev

Next, access the database from the command line and create your tables. The database is created on the Heroku cloud service and not locally. However, you can access it through the command line. To log on to the database via the console, run the command heroku pg:psql. Remember, you have to do it in your webchecker folder so that Heroku knows that it is the database for the webchecker site.

To see the list of tables type the command \d

To create a table, you need to use normal SQL statements. For our webchecker program, let’s create a table with the following columns:

  • ID — automatically generated ID for each entry (this will be the primary key). This is done by using the type “serial”
  • website — the website to monitor
  • emailaddress — the email address to send the notification that a change has occurred
  • lasthashcode — we won’t store a copy of the whole webpage, instead we will generate a hash based on the HTML of the page, and then compare this each time. This is more efficient storage-wise, but will not tell us what actually changed
  • lastchangedate — the date that the web changed last time. Hence we will get the database to default this with the current date

To create this table, enter the following command in the Heroku Postgres database console:

CREATE TABLE webcheckerdb (id serial, website varchar(250), emailaddress varchar(250), lasthashcode varchar(32), lastchangedate timestamp DEFAULT current_date );

(Make sure you include the semicolon at the end!)

Next, let’s insert a single record in the database to ensure we have something to work with prior to getting our web UI up and running (you can use your own email address so it works in the future):

INSERT into webcheckerdb values(DEFAULT, 'news.google.com', '[email protected]', '', DEFAULT);

(Make sure you include the semicolon at the end!)

You can quit with \q.

Step 3: Check websites for changes

First, let’s get a piece of code to at least check if a hardcoded site can be retrieved (following on the concept of walking before running).

Hence, first step is to see if we can retrieve a webpage, hash it, and then compare it to a hardcoded hash. Create a new Python file called checkwebsite.py. Code here:

Running this will output the following:

If you have any errors with missing libraries, you can add them via: pip install ry> from the command line.

Next, let’s connect to the database with the following code:

When you try to run this code, you are likely going to get an error of the form KeyError: ‘DATABASE_URL’. This is because your Python code is trying to locate the web address of the Postgres database hosted on Heroku. This is automatically updated to the environment variable DATABASE_URL in the Heroku server. However, on your local PC you will have to do this manually:

  1. heroku config
  2. set DATABASE_URL=

Step 4: Send an email notification on changes

Final step is to send an email. To do this, you’ll need to install an Addon that has the ability to send emails — you can find these via the Heroku marketplace: //elements.heroku.com/addons

In here, there is an Addon called SendGrid: //elements.heroku.com/addons/sendgrid

You can add SendGrid to your app in the command line by typing:

heroku addons:create sendgrid:starter

When you go to your dashboard you can see the new Addon in the Resources section:

Before using it, you’ll need to create an API key. Double click the SendGrid component above and go into Settings->API Key->Create Key (blue button on top right).

Once you create the key, copy it and go back to the command prompt and enter:

heroku config:set SENDGRID_API_KEY=ve>

This will only register it on the server, you need to add it locally to your desktop with:

set SENDGRID_API_KEY=in>

Once done, you can test your code in a new Python script called sendmail.py. Install the library via pip install sendgrid:

To confirm the email was sent and delivered, you can go back to the SendGrid dashboard and checking the Statistics Overview screen:

When checking your email, remember to check your spam.

Once it is working, there are only two lines of code you need to add to your main checkwebsite.py script. It is:

import sendmail #import the send email subroutine you wrote above
...
#call the subroutine after find the hashcode has changedsendmail.sendemail(webrecord['emailaddress'], 'Website changed', webrecord['website'] + ' changed')

The full code is here:

Step 5: List the output on the web page and schedule the job

The next step is to list the output on the webpage.

This involves querying the database, and then cycling through and showing the data on your screen. Hence, it takes the ‘Hello World’ code above, and makes the modification. I also created a different path for this, so to test this out you’ll need to go to the URL: //localhost:5000/list

And here’s the output:

Step 6: Deploy

The final step is to deploy everything to Heroku and then schedule the job so that it checks email.

You should have the following files:

  1. Procfile — the file which points to showchecker.py
  2. requirements.txt — the file which contains the library dependencies
  3. runtime.txt — the version of python
  4. showchecker.py — the python code which shows the database output on the web via .herokuapp.com/list
  5. checkwebsite.py — the python code that checks for any changes on the websites

For the requirements.txt, you will need to make amendments to add the latest libraries:

Deploy these all to Heroku:

  1. git add *.* *
  2. git commit -m “deployment”
  3. git push heroku master

Test each component:

  1. Go to .herokuapp.com/hello
  2. Go to .herokuapp.com/list

If there are any errors, then run heroku logs in the command line to see what is going on.

Next, run the checkwebsite.py directly on Heroku to make sure there are no issues. To do this, you can type:

heroku run python checkwebsite.py

Finally, you can now schedule your job. Again, you need to include an Addon to do this.

heroku addons:create scheduler:standard

And you should be able to see the scheduler in your resources page:

You can simply use the command line to run the program, in our case it is: python checkwebsite.py (this is the same as what we tested above with the heroku run command).

Summary

And that’s it… the first time it is a little complex, but hopefully the above incremental steps will help you understand what’s going on under the hood. There are a lot more resources on Heroku as well as a wealth of information on Stack Overflow. These resources should make a lot more sense after going through the above.

Good Luck!

Thanks for reading! If you like what you read, hit the❤ button below so that others may find this (you can also find me on Twitter )