כיצד לבנות יישום אינטרנט באמצעות Flask ולפרוס אותו לענן

מבוא

בכל חלק, אראה פיסות קוד שתוכלו לעקוב אחריהם. כל הקוד המשמש במדריך זמין במאגר GitHub זה.

מה זה HTTP ומה הקשר בין Flask?

HTTP הוא הפרוטוקול לאתרים. האינטרנט משתמש בו כדי לתקשר ולתקשר עם מחשבים ושרתים. תן לי לתת לך דוגמה לאופן שבו אתה משתמש בה כל יום.

כאשר אתה מקליד את שם האתר בשורת הכתובת של הדפדפן שלך ולחץ על Enter. מה שקורה הוא שבקשת HTTP נשלחה לשרת.

לדוגמא, כשאני נכנס לשורת הכתובת שלי ומקליד google.com ואז מקיש Enter, בקשת HTTP נשלחת לשרת של גוגל. שרת Google מקבל את הבקשה ועליו להבין כיצד לפרש את הבקשה. שרת Google שולח בחזרה תגובת HTTP המכילה את המידע שקבל דפדפן האינטרנט שלי. ואז הוא מציג את מה שביקשת בדף בדפדפן.

כיצד מעורב פלסק?

נכתוב קוד שידאג לעיבוד צד השרת. הקוד שלנו יקבל בקשות. זה יבין במה עוסקות בקשות אלו ובמה הם מבקשים. זה גם יבין איזו תגובה לשלוח למשתמש.

כדי לעשות את כל זה נשתמש ב- Flask.

מהי Flask?

זה הופך את תהליך עיצוב יישום האינטרנט לפשוט יותר. בקבוק מאפשר לנו להתמקדעל מה המשתמשים מבקשים ואיזה סוג תגובה להחזיר.

למידע נוסף על מסגרות מיקרו.

איך אפליקציית Flask עובדת?

הקוד מאפשר לנו להפעיל יישום אינטרנט בסיסי שנוכל להגיש, כאילו היה אתר.

from flask import Flask app = Flask(__name__) @app.route("/") def home(): return "Hello, World!" if __name__ == "__main__": app.run(debug=True)

פיסת הקוד הזו שמורה ב- main.py.

שורה 1: כאן אנו מייבאים את מודול ה- Flask ויוצרים שרת אינטרנט Flask ממודול ה- Flask.

שורה 3: __name__ פירושו הקובץ הנוכחי הזה . במקרה זה, זה יהיה main.py. קובץ נוכחי זה ייצג את יישום האינטרנט שלי.

אנו יוצרים מופע של מחלקת Flask וקוראים לזה אפליקציה. כאן אנו יוצרים יישום אינטרנט חדש.

שורה 5: הוא מייצג את דף ברירת המחדל. לדוגמא, אם אני נכנס לאתר כמו "google.com/" בלי שום דבר אחרי הנטייה. אז זה יהיה דף ברירת המחדל של גוגל.

שורה 6–7 : כאשר המשתמש נכנס לאתר שלי והם עוברים לדף ברירת המחדל (שום דבר אחרי קו נטוי), אז הפונקציה שלמטה תופעל.

שורה 9: כאשר אתה מריץ את סקריפט ה- Python שלך, Python מקצה את השם "__main__" לסקריפט בעת ביצועו.

אם אנו מייבאים סקריפט אחר, הצהרת ה- if תמנע את הפעלת סקריפטים אחרים. כשאנחנו מריצים main.py, הוא ישנה את שמו ל- __main__ ורק אז ההצהרה הזו תופעל.

שורה 10: פעולה זו תריץ את היישום. לאחר debug=Trueמאפשרת להופיע שגיאות פיתון בדף האינטרנט. זה יעזור לנו להתחקות אחר השגיאות.

בואו ננסה להריץ main.py

במסוף או בשורת הפקודה שלך עבור לתיקיה המכילה את main.py שלך.ואז עשה py main.pyאו python main.py. במסוף או בשורת הפקודה שלך אתה אמור לראות את הפלט הזה.

החלק החשוב הוא המקום בו כתוב Running on //127.0.0.1:5000/.

127.0.0.1 פירושו מחשב מקומי זה. אם אינך יודע את המשמעות של זה (כמו שלא ידעתי כשהתחלתי - מאמר זה ממש מועיל), הרעיון העיקרי הוא ש- 127.0.0.1 ו- localhost מתייחסים למחשב מקומי זה.

עבור לכתובת זו ועליך לראות את הדברים הבאים:

יותר כיף עם בקבוק

מוקדם יותר ראית מה קרה כאשר רצנו main.py עם מסלול אחד שהיה app.route (“/”).

בואו נוסיף מסלולים נוספים כדי שתוכלו לראות את ההבדל.

from flask import Flask app = Flask(__name__) @app.route("/") def home(): return "Hello, World!" @app.route("/salvador") def salvador(): return "Hello, Salvador" if __name__ == "__main__": app.run(debug=True)

בשנת קווי 9-11 . הוספנו מסלול חדש, הפעם ל / סלבדור.

כעת הפעל את main.py שוב ועבור אל// localhost: 5000 / סלבדור.

עד כה החזרנו טקסט. בואו נראה לאתר שלנו להיראות נחמד יותר על ידי הוספת HTML ו- CSS.

HTML, CSS וסביבות וירטואליות

HTML ותבניות בבקבוק

ראשית צור קובץ HTML חדש. התקשרתי לבית שלי .html.

הנה קצת קוד כדי להתחיל.

    Flask Tutorial   

My First Try Using Flask

Flask is Fun

נקודה חשובה לזכור

מסגרת הבקבוק מחפשת קבצי HTML בתיקייה הנקראת תבניות. עליכם ליצור תיקיית תבניות ולשים שם את כל קבצי ה- HTML שלכם.

כעת עלינו לשנות את ה- main.py שלנו כדי שנוכל להציג את קובץ ה- HTML שיצרנו.

from flask import Flask, render_template app = Flask(__name__) @app.route("/") def home(): return render_template("home.html") @app.route("/salvador") def salvador(): return "Hello, Salvador" if __name__ == "__main__": app.run(debug=True) We made two new changes

Line 1: We imported render_template() method from the flask framework. render_template() looks for a template (HTML file) in the templates folder. Then it will render the template for which you ask. Learn more about render_templates() function.

Line 7: We change the return so that now it returns render_template(“home.html”). This will let us view our HTML file.

Now visit your localhost and see the changes: //localhost:5000/.

Let’s add more pages

Let’s create an about.html inside the templates folder.

    About Flask   

About Flask

Flask is a micro web framework written in Python.

Applications that use the Flask framework include Pinterest, LinkedIn, and the community web page for Flask itself.

Let’s make a change similar to what we did before to our main.py.

from flask import Flask, render_template app = Flask(__name__) @app.route("/") def home(): return render_template("home.html") @app.route("/about) def about(): return render_template("about.html") if __name__ == "__main__": app.run(debug=True)

We made three new changes:

Line 9: Change the route to"/about".

Line 10: Change the function so it is nowdef about():

Line 11: Change the return so that now it returns render_template("about.html").

Now see the changes: //localhost:5000/about.

Let’s Connect Both Pages with a Navigation

To connect both pages we can have a navigation menu on the top. We can use Flask to make the process of creating a navigation menu easier.

First, let’s create a template.html. This template.html will serve as a parent template. Our two child templates will inherit code from it.

     Flask Parent Template 

First Web App

  • Home
  • About
{% block content %} {% endblock %}

Line 13–14: We use the function calledurl_for(). It accepts the name of the function as an argument. Right now we gave it the name of the function. More information on url_for() function.

The two lines with the curly brackets will be replaced by the content of home.html and about.html. This willdepend on the URL in which the user is browsing.

These changes allow the child pages (home.html and about.html) to connect to the parent (template.html). This allows us to not have to copy the code for the navigation menu in the about.html and home.html.

Content of about.html:

    About Flask   {% extends "template.html" %} {% block content %} 

About Flask

Flask is a micro web framework written in Python.

Applications that use the Flask framework include Pinterest, LinkedIn, and the community web page for Flask itself.

{% endblock %}

Content of home.html:

    Flask Tutorial   {% extends "template.html" %} {% block content %} 

My First Try Using Flask

Flask is Fun

{% endblock %}

Let’s try adding some CSS.

Adding CSS to Our Website

An important note to remember

In the same way as we created a folder called templates to store all our HTML templates, we need a folder called static.

In static, we will store our CSS, JavaScript, images, and other necessary files. That is why it is important that you should create a CSSfolder to store your stylesheets. After you do this, your project folder should look like this:

Linking our CSS with our HTML file

Our template.html is the one that links all pages. We can insert the code here and it will be applicable to all child pages.

    Flask Parent Template 

First Web App

  • Home
  • About
{% block content %} {% endblock %}

Line 7: Here we are giving the path to where the template.css is located.

Now see the changes: //localhost:5000/about.

Moving Forward with Flask and virtualenv

Now that you are familiar with using Flask, you may start using it in your future projects. One thing to always do is use virtualenv.

Why use virtualenv?

You may use Python for others projects besides web-development.

Your projects might have different versions of Python installed, different dependencies and packages.

We use virtualenv to create an isolated environment for your Python project. This means that each project can have its own dependencies regardless of what dependencies every other project has.

Getting started with virtualenv

First, run this command on your command prompt or terminal:

pip install virtualenv

Second, do the following:

virtualenv “name of virtual environment”

Here you can give a name to the environment. I usually give it a name of virtual. It will look like this: virtualenv virtual.

After setting up virtual environment, check your project folder. It should look like this. The virtual environment needs to be created in the same directory where your app files are located.

Activating the virtual environment

Now go to your terminal or command prompt. Go to the directory that contains the file called activate. The file called activate is found inside a folder called Scripts for Windows and bin for OS X and Linux.

For OS X and Linux Environment:

$ name of virtual environmnet/bin/activate

For Windows Environment:

name of virtual environment\Scripts\activate

Since I am using a Windows machine, when I activate the environment it will look like this:

The next step is to install flask on your virtual environment so that we can run the application inside our environment. Run the command:

pip install flask

Run your application and go to //localhost:5000/

We finally made our web application. Now we want to show the whole world our project.

(More information on virtualenv can be found in the following guides on virtualenv and Flask Official Documentation)

Let’s send it to the Cloud

To show others the project we made, we will need to learn how to use Cloud Services.

Deploy Your Web Application to the Cloud

To deploy our web application to the cloud, we will use Google App Engine (Standard Environment). This is an example of a Platform as a Service (PaaS).

PaaS מתייחס למסירת מערכות הפעלה ושירותים נלווים דרך האינטרנט ללא הורדות או התקנה . הגישה מאפשרת ללקוחות ליצור ולפרוס יישומים ללא צורך להשקיע בתשתית הבסיסית (מידע נוסף על PaaS עיין ב- TechTarget).

מנוע האפליקציות של גוגל הוא פלטפורמה כמוצעת שירות המאפשרת למפתחים ולעסקים לבנות ולהפעיל יישומים באמצעות התשתית המתקדמת של גוגל - TechOpedia.

לפני שאתה מתחיל:

תזדקק לחשבון Google . לאחר שתיצור חשבון, עבור למסוף פלטפורמת הענן של Google וצור פרויקט חדש. כמו כן, עליך להתקין את Google Cloud SDK.

בסוף הדרכה זו מבנה הפרויקט שלך ייראה כך.

We will need to create three new files: app.yaml, appengine_config.py, and requirements.txt.

Content of app.yaml:

runtime: python27 api_version: 1 threadsafe: true handlers: - url: /static static_dir: static - url: /.* script: main.app libraries: - name: ssl version: latest

If you were to check Google’s Tutorial in the part where they talk about content of the app.yaml, it does not include the section where I wrote about libraries.

When I first attempted to deploy my simple web app, my deployment never worked. After many attempts, I learned that we needed to include the SSL library.

The SSL Library allows us to create secure connections between the client and server. Every time the user goes to our website they will need to connect to a server run by Google App Engine. We need to create a secure connection for this. (I recently learned this, so if you have a suggestions for this let me know!)

Content of appengine_config.py:

from google.appengine.ext import vendor # Add any libraries installed in the "lib" folder. vendor.add('lib')

Content of requirements.txt:

Flask Werkzeug

Now inside our virtual environment (make sure your virtualenv is activated),we are going to install the new dependencies we have in requirements.txt. Run this command:

pip install -t lib -r requirements.txt

-t lib: This flag copies the libraries into a lib folder, which uploads to App Engine during deployment.

-r requirements.txt: Tells pip to install everything from requirements.txt.

Deploying the Application

To deploy the application to Google App Engine, use this command.

gcloud app deploy

I usually include — project [ID of Project]

This specifies what project you are deploying. The command will look like this:

gcloud app deploy --project [ID of Project]

The Application

Now check the URL of your application. The application will be store in the following way:

"your project id".appspot.com

My application is here: //sal-flask-tutorial.appspot.com

Conclusion

From this tutorial, you all learned how to:

  • Use the framework called Flask to use Python as a Server Side Language.
  • Learned how to use HTML, CSS, and Flask to make a website.
  • Learned how to create Virtual Environments using virtualenv.
  • Use Google App Engine Standard Environment to deploy an application to the cloud.

What I learned

I learned three important things from this small project.

First, I learned about the difference between a static website and a web application

Static Websites:

  • Means that the server is serving HTML, CSS, and JavaScript files to the client. The content of the site does not change when the user interacts with it.

Web Applications:

  • A web application or dynamic website generates content based on retrieved data (most of the time is a database) that changes based on a user’s interaction with the site. In a web application, the server is responsible for querying, retrieving, and updating data. This causes web applications to be slower and more difficult to deploy than static websites for simple applications (Reddit).

Server Side and Client Side:

  • I learned that a web application has two sides. The client side and the server side. The client side is what the user interacts with and the server side is where the all the information that the user inputted is processed.

Second, I learned about Cloud Services

Most of my previous projects were static websites, and to deploy them I used GitHub Pages. GitHub Pages is a free static site hosting service designed to host projects from a GitHub Repository.

When working with web applications, I could not use GitHub Pages to host them. GitHub Pages is only meant for static websites not for something dynamic like a web application that requires a server and a database. I had to use Cloud Services such as Amazon Web Services or Heroku

Third, I learned how to use Python as a Server Side Language

To create the server side of the web application we had to use a server side language. I learned that I could use the framework called Flask to use Python as the Server Side Language.

Next Steps:

You can build all sorts of things with Flask. I realized that Flask helps make the code behind the website easier to read. I have made the following applications during this summer of 2018 and I hope to make more.

Personal Projects

  • A Twilio SMS App
  • My Personal Website

During my internship

  • Part of a project where I learned about Docker and Containers

Here is the list of resources that helped me create this tutorial:

  • “App Engine — Build Scalable Web & Mobile Backends in Any Language | App Engine | Google Cloud.” Google, Google, cloud.google.com/appengine/.
  • “Building a Website with Python Flask.” PythonHow, pythonhow.com/building-a-website-with-python-flask/.
  • “Flask — Lecture 2 — CS50’s Web Programming with Python and JavaScript.” YouTube, 6 Feb. 2018, youtu.be/j5wysXqaIV8.
  • “Getting Started with Flask on App Engine Standard Environment | App Engine Standard Environment for Python | Google Cloud.” Google, Google, cloud.google.com/appengine/docs/standard/python/getting-started/python-standard-env.
  • “Installation.” Welcome | Flask (A Python Microframework), flask.pocoo.org/docs/0.12/installation/.
  • “Python — Deploying Static Flask Sites for Free on Github Pages.” Reddit, www.reddit.com/r/Python/comments/1iewqt/deploying_static_flask_sites_for_free_on_github/.
  • Real Python. “Python Virtual Environments: A Primer — Real Python.” Real Python, Real Python, 7 Aug. 2018, realpython.com/python-virtual-environments-a-primer/.
  • “What Is Cloud Services? — Definition from WhatIs.com.” SearchITChannel, searchitchannel.techtarget.com/definition/cloud-services.
  • “What Is Google App Engine (GAE)? — Definition from Techopedia.” Techopedia.com, www.techopedia.com/definition/31267/google-app-engine-gae.

If you have any suggestions or questions, feel free to leave a comment.