Kako besplatno ugostiti lagane aplikacije

Kada tražite usluge web hostinga, dostupno je mnogo besplatnih opcija. Ali nema toliko mjesta na kojima možete ugostiti web aplikacije s cjelovitim hrpom koje uključuju API-je, CGI ili AJAX pozadinske upite - pogotovo ako želite koristiti nešto drugo osim PHP-a.

Ovaj je članak jednostavan, ali smislen vodič "hodajte prije nego što uspijete pokrenuti" o tome kako započeti s hostingom svojih skripti na poslužiteljima u oblaku.

Kada koristiti Cloud Application Platform

Cloud Application Platforme dobro funkcioniraju u scenarijima gdje vam treba malo koda za pokretanje na poslužitelju. Mnoge od ovih platformi nude niz kontejnera aplikacija zasnovanih na Linuxu (koji se pojavljuju poput virtualnih strojeva) gdje kôd koji ste razvili rasporedite na svoje lokalno računalo pomoću skupa ključnih riječi naredbenog retka.

Heroku je jedna od takvih usluga koju biste mogli relativno lako poslužiti za hostiranje svog koda (na raznim jezicima). Nudi freemium model gdje vam omogućuju besplatno korištenje oko 500 sati računanja (njihova puna cijena nalazi se ovdje).

Nakon što napišete kôd na lokalnoj radnoj površini, možete izvršavati naredbe kojima se kôd raspoređuje u radni prostor u Herokuu. Tada se kôd izvršava ovisno o okidaču. Okidači mogu biti planirani posao, web poslužitelj koji se pokreće putem zahtjeva za web stranicu ili nešto što se stalno izvodi i obrađuje podatke - što može postati prilično skupo.

Ono što je zaista lijepo je da ne morate brinuti o operativnom sustavu (memorija, pohrana, CPU, sigurnosne zakrpe) jer se time upravlja sve za vas - ali u isto vrijeme to znači da imate ograničenu fleksibilnost jer ne možete alocirati izravno resurse.

Neki konkretni primjeri gdje Heroku može lijepo raditi za vas:

  • Hostiranje vlastite web stranice na kojoj želite napisati vlastiti web poslužitelj
  • Povremeno struganje podataka s web mjesta i pohranjivanje u bazu podataka za analizu
  • Ponuda API poslužitelja za određeni zadatak. Stvari poput ponude vremenskih podataka, pohrane podataka senzora za Internet of Things ili poziva web usluge za model strojnog učenja
  • Usluga baze podataka (iako je usluga kao što je Firebase možda prikladnija)

Heroku Arhitektura

Heroku nudi lagani virtualni stroj (VM) za vašu primjenu koda. Imajte na umu da prema besplatnoj opciji možete postaviti do 5 aplikacija koje se smatraju 5 laganih VM-ova. Za vašu stvarnu prijavu, pod Heroku ste dobili zasebnu URL poddomenu. Dakle, nazivi vaših projekata moraju biti jedinstveni.

Ti radni prostori imaju vlastiti prostor za komponente kao što su: datoteke koda i resursa (ne datoteke dinamičkih podataka), baza podataka (Postgres) i datoteke dnevnika.

Na vašoj lokalnoj radnoj površini, Heroku koristi naziv vašeg direktorija za definiranje vašeg projekta, a također i za Heroku da razumije vaš kontekst. Dakle, možete imati više projekata u različitim direktorijima, a kada pokrenete Heroku naredbe - samo pazite da to učinite u pravoj mapi.

Ključna stvar koje morate biti svjesni (a koju sam na teži način otkrio kroz sate otklanjanja pogrešaka - volio bih da više pažnje posvećujem dokumentaciji) jest da se sve pokreće iz memorije. Nema trajne pohrane. Ponovit ću - ne možete pohraniti nijednu datoteku na poslužitelj datoteka! Za ustrajnost, Heroku nudi post-SQL SQL bazu podataka u koju možete dodavati zapise prema potrebi.

Jednostavan primjer - otkrivanje promjena na web mjestu

Evo detaljnog vodiča za dobivanje radnog primjera jednostavne usluge koja će vam poslati e-poštu ako se web mjesto promijenilo - u osnovi klon www.changedetection.com. Bit će nekoliko ključnih sastavnica ovoga:

  1. Baza podataka koja će pohraniti: (a) adresu e-pošte za obavještavanje o promijenjenom web mjestu; (b) web mjesto za praćenje; (c) zadnja "kopija" web stranice
  2. Dio koda koji će provjeriti određeno web mjesto iz baze podataka u # 1 (Python skripta)
  3. Planer poslova koji će pokrenuti program u # 2 (ekvivalent cron poslu)
  4. Web korisničko sučelje gdje možete dodavati / brisati web stranice za nadgledanje u bazu podataka spomenutu u # 1
  5. Mehanizam za slanje e-pošte

Razumijevanje ovih komponenata naoružat će vas vještinama za već puno stvari. Sve sam te stvari naučio iz više izvora, pa ovo djeluje kao objedinjeni post.

Pretpostavke

Sljedeći vodič donosi sljedeće pretpostavke:

  • Imate GitHub račun - ako ga nemate, stvorite ga ovdje. Također biste trebali pročitati ovaj jednostavan vodič.
  • Već imate račun Heroku - ako ga ne napravite, otvorite ga ovdje.
  • Koristite Windows sustav - ako ne, u redu je, upute su prilično slične u drugim okruženjima
  • Već imate instaliran Python - ako ne, idite ovdje da ga instalirate
  • Već možete programirati na Pythonu - ako ne, onda bih vam predložio da prvo naučite neke osnove. Ovdje su neki vodiči.
  • Znate SQL - ako ne, molim vas idite ovdje.

Pregled koraka

Smatram da prolazak kroz šetnju prije nego što pokrenete pomaže u procesu učenja. Također vam služi kao dokumentacija za rješavanje svakog dijela većeg postupka. Na taj način, ako vam se nešto pokvari u budućem pothvatu, imate veće šanse otkriti gdje je pošlo po zlu.

Korak 1 : Razvijte web korisničko sučelje - prvo izgradite Hello World

Korak 2 : Postojanost - stvorite bazu podataka

Korak 3 : Provjerite ima li web stranica promjena

Korak 4: Pošaljite obavijest e-poštom o promjenama

Korak 5 : Navedite izlaz na web stranici

Korak 6: Razmještanje

Korak 1: Razvijte web korisničko sučelje - prvo izgradite Hello World

Prvo, postavimo jednostavan program postavljen na Heroku kako bismo pokrenuli stvari. Ovaj program bit će preteča web korisničkog sučelja (stavka # 4) na gornjem popisu komponenata. Da bismo poslužili stranicu, mogli bismo jednostavno imati HTML stranicu, ali tada bismo trebali imati web poslužitelj za posluživanje te datoteke. Drugim riječima, kada upišete URL web stranice, program će trebati protumačiti zahtjev, a zatim pružiti sadržaj HTML datoteke. Možete stvoriti vlastiti mini web poslužitelj s knjižnicom Flask Python, što ćemo i učiniti.

  • Stvorite mapu koja se zove webchecker i idite u taj direktorij (ovaj naziv direktorija ne mora biti isti kao naziv aplikacije Heroku)
  • Instalirajte knjižnicu Flask. Unesite naredbu: npm tikvica
  • Stvorite sljedeći program Python i nazovite ga 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 )