Cara menghoskan aplikasi ringan secara percuma

Apabila anda mencari perkhidmatan hosting web, terdapat banyak pilihan percuma yang tersedia. Tetapi tidak banyak tempat di mana anda boleh menjadi tuan rumah aplikasi web tumpukan penuh yang melibatkan API, CGI, atau pertanyaan backend AJAX - terutamanya jika anda ingin menggunakan sesuatu selain PHP.

Artikel ini adalah panduan "berjalan sebelum anda dapat berjalan" yang mudah tetapi bermakna tentang cara memulakan hosting skrip anda di pelayan awan.

Bila hendak menggunakan Platform Aplikasi Awan

Platform Aplikasi Awan berfungsi dengan baik dalam senario di mana anda memerlukan sedikit kod untuk dijalankan di pelayan. Sebilangan besar platform ini menawarkan serangkaian wadah aplikasi berasaskan Linux (yang muncul seperti mesin maya) di mana anda menggunakan kod yang anda kembangkan di komputer tempatan anda dengan sekumpulan kata kunci baris perintah.

Heroku adalah salah satu perkhidmatan yang boleh anda gunakan untuk menghoskan kod anda (dalam pelbagai bahasa) dengan mudah. Ia menawarkan model freemium di mana mereka membenarkan anda menggunakan kira-kira 500 jam pengkomputeran secara percuma (harga penuh mereka ada di sini).

Sebaik sahaja anda menulis kod anda di desktop tempatan, anda boleh menjalankan perintah yang menyebarkan kod tersebut ke ruang kerja di Heroku. Kod tersebut kemudian dilaksanakan bergantung pada pencetus. Pencetus boleh menjadi pekerjaan yang dijadwalkan, pelayan web yang dipicu melalui permintaan halaman web, atau sesuatu yang terus berjalan dan memproses data - yang dapat menjadi sangat mahal.

Apa yang benar-benar bagus ialah anda tidak perlu bimbang tentang sistem operasi (memori, storan, CPU, patch keselamatan) kerana semuanya dikendalikan untuk anda - tetapi pada masa yang sama ia bermaksud bahawa anda mempunyai fleksibiliti terhad kerana anda tidak dapat memperuntukkan sumber secara langsung.

Beberapa contoh khusus di mana Heroku dapat berfungsi dengan baik untuk anda:

  • Mengehoskan laman web anda sendiri di mana anda ingin menulis pelayan web anda sendiri
  • Mengumpulkan data dari laman web secara berkala dan kemudian menyimpannya di pangkalan data untuk dianalisis
  • Menawarkan pelayan API untuk tugas tertentu. Perkara seperti menawarkan data cuaca, menyimpan data sensor Internet of Things, atau panggilan perkhidmatan web untuk model pembelajaran mesin
  • Perkhidmatan pangkalan data (walaupun perkhidmatan seperti Firebase mungkin lebih sesuai)

Senibina Heroku

Heroku menyediakan mesin maya ringan (VM) untuk anda menggunakan kod anda. Perhatikan bahawa di bawah pilihan percuma, anda dapat menggunakan hingga 5 aplikasi yang dianggap sebagai 5 VM ringan. Untuk aplikasi sebenar anda, anda diberikan subdomain URL berasingan di bawah Heroku. Oleh itu, nama projek anda mesti unik.

Ruang kerja ini mempunyai ruang tersendiri untuk komponen seperti: fail kod dan sumber (bukan fail data dinamik), pangkalan data (Postgres), dan fail log.

Pada desktop tempatan anda, Heroku menggunakan nama direktori anda untuk menentukan projek anda, dan juga untuk Heroku memahami konteks anda. Oleh itu, anda boleh mempunyai banyak projek dalam direktori yang berbeza dan semasa anda menjalankan perintah Heroku - pastikan anda melakukannya di folder yang betul.

Satu perkara penting yang perlu anda perhatikan (yang saya dapati dengan susah payah melalui proses debug berjam-jam - saya harap saya lebih memperhatikan dokumentasi) adalah semuanya berjalan dari ingatan. Tidak ada simpanan berterusan. Saya akan mengatakannya lagi - anda tidak dapat menyimpan fail apa pun di pelayan fail! Untuk kegigihan, Heroku menawarkan pangkalan data SQL pasca proses di mana anda boleh menambah rekod seperti yang diperlukan.

Contoh mudah - pengesanan perubahan laman web

Berikut adalah panduan langkah demi langkah untuk mendapatkan contoh berfungsi dari perkhidmatan mudah yang akan menghantar e-mel kepada anda jika laman web telah berubah - pada dasarnya klon www.changedetection.com. Terdapat beberapa komponen penting ini:

  1. Pangkalan data yang akan menyimpan: (a) alamat e-mel untuk memberitahu laman web yang telah berubah; (b) laman web untuk dijejaki; (c) 'salinan' laman web terakhir
  2. Sebilangan kod yang akan memeriksa laman web tertentu dari pangkalan data dalam # 1 (skrip Python)
  3. Penjadual kerja yang akan menjalankan program di # 2 (setara dengan pekerjaan cron)
  4. Antara muka pengguna web di mana anda dapat menambah / menghapus laman web untuk memantau ke dalam pangkalan data yang disebutkan di # 1
  5. Mekanisme untuk menghantar e-mel

Memahami komponen ini akan memberi anda kemahiran untuk melakukan banyak perkara. Saya mempelajari semua perkara ini melalui pelbagai sumber, jadi ini berfungsi sebagai catatan gabungan.

Andaian

Panduan berikut membuat andaian berikut:

  • Anda mempunyai akaun GitHub - jika tidak, sila buat di sini. Anda juga harus membaca panduan ringkas ini.
  • Anda sudah mempunyai akaun Heroku - jika anda tidak membuatnya di sini.
  • Anda menjalankan mesin Windows - jika tidak, tidak apa-apa, arahannya agak serupa di persekitaran lain
  • Anda sudah memasang Python - jika tidak, sila ke sini untuk memasangnya
  • Anda sudah boleh memprogram di Python - jika tidak, maka saya cadangkan anda mempelajari beberapa asasnya terlebih dahulu. Beberapa panduan ada di sini.
  • Anda tahu SQL - jika tidak, sila ke sini.

Gambaran keseluruhan langkah-langkahnya

Saya dapati bahawa melalui pendekatan 'jalan sebelum anda boleh berlari' membantu proses pembelajaran. Ini juga berfungsi sebagai dokumentasi untuk diri anda sendiri bagaimana menyelesaikan setiap proses yang lebih besar. Dengan cara itu, jika sesuatu berlaku di masa depan anda, anda mempunyai peluang yang lebih baik untuk mengetahui di mana ia salah.

Langkah 1 : Kembangkan antara muka pengguna web - bina Hello World terlebih dahulu

Langkah 2 : Kegigihan - buat pangkalan data

Langkah 3 : Periksa laman web untuk perubahan

Langkah 4: Hantarkan pemberitahuan e-mel mengenai perubahan

Langkah 5 : Senaraikan output di laman web

Langkah 6: Sebarkan

Langkah 1: Kembangkan antara muka pengguna web - bina 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

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 )