How To Create A Delivery Service App
by Salvador Villalon
Introduction
In each department, I volition show pieces of code for yous to follow along. All the lawmaking used in the tutorial is available in this GitHub Repository.
What is HTTP and What Does it Have to do with Flask?
HTTP is the protocol for websites. The internet uses it to interact and communicate with computers and servers. Let me give you an case of how you lot utilise it everyday.
When you lot type the name of a website in the address bar of your browser and you hit enter. What happens is that an HTTP request has been sent to a server.
For example, when I become to my address bar and type google.com, then hit enter, an HTTP request is sent to a Google Server. The Google Server receives the asking and needs to effigy how to interpret that asking. The Google Server sends back an HTTP response that contains the data that my spider web browser receives. Then information technology displays what you asked for on a page in the browser.
How is Flask involved?
We will write code that volition take intendance of the server side processing. Our code will receive requests. It will effigy out what those requests are dealing with and what they are asking. Information technology will too figure out what response to send to the user.
To practice all this we will use Flask.
What is Flask?
It makes the process of designing a web application simpler. Flask lets us focus on what the users are requesting and what sort of response to requite back.
Learn more about micro frameworks.
How Does a Flask App Work?
The code lets us run a basic web awarding that we can serve, as if it were a website.
from flask import Flask app = Flask(__name__) @app.route("/") def dwelling house(): return "Hello, World!" if __name__ == "__main__": app.run(debug=Truthful)
This piece of code is stored in our main.py.
Line 1: Hither we are importing the Flask module and creating a Flask web server from the Flask module.
Line 3: __name__ means this current file. In this instance, it will be principal.py. This current file volition represent my web application.
We are creating an instance of the Flask course and calling it app. Here we are creating a new web awarding.
Line 5: Information technology represents the default page. For example, if I get to a website such as "google.com/" with nix later the slash. Then this will be the default page of Google.
Line vi–7: When the user goes to my website and they go to the default page (cypher after the slash), and then the function below will get activated.
Line 9: When you run your Python script, Python assigns the proper name "__main__" to the script when executed.
If we import another script, the if statement will prevent other scripts from running. When nosotros run main.py, it will modify its proper noun to __main__ and only and then volition that if statement actuate.
Line 10: This will run the awarding. Having debug=True
allows possible Python errors to appear on the web page. This volition aid us trace the errors.
Let's Try Running main.py
In your Terminal or Command Prompt get to the binder that contains your main.py. So do py main.py
or python chief.py
. In your final or command prompt you should see this output.
The of import role is where information technology says Running on http://127.0.0.1:5000/
.
127.0.0.1 means this local estimator. If you practice not know the pregnant of this (similar I didn't when I started — this article is really helpful), the main idea is that 127.0.0.one and localhost refer to this local estimator.
Become to that address and you should run across the following:
More than Fun with Flask
Before you saw what happened when we ran main.py with i route which was app.road("/").
Let's add together more than routes so y'all can see the divergence.
from flask import Flask app = Flask(__name__) @app.road("/") def home(): return "Hello, World!" @app.road("/salvador") def salvador(): return "Howdy, Salvador" if __name__ == "__main__": app.run(debug=True)
In lines nine–eleven. we added a new route, this time to /salvador.
Now run the chief.py again and go to http://localhost:5000/salvador.
Then far we accept been returning text. Permit's make our website look nicer by calculation HTML and CSS.
HTML, CSS, and Virtual Environments
HTML and Templates in Flask
First create a new HTML file. I called mine abode.html.
Here is some code to get you started.
<!DOCTYPE html> <html lang="en" dir="ltr"> <caput> <meta charset="utf-viii"> <title>Flask Tutorial</championship> </head> <body> <h1> My First Try Using Flask </h1> <p> Flask is Fun </p> </body> </html>
Of import Point To Remember
The Flask Framework looks for HTML files in a folder chosen templates. You need to create a templates folder and put all your HTML files in there.
At present we need to modify our primary.py and then that we can view the HTML file we created.
from flask import Flask, render_template app = Flask(__name__) @app.road("/") def home(): return render_template("home.html") @app.route("/salvador") def salvador(): return "Hello, Salvador" if __name__ == "__main__": app.run(debug=True) We made 2 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 information technology will render the template for which you ask. Larn more about render_templates() function.
Line 7: We change the return then that now it returns render_template("home.html")
. This will permit us view our HTML file.
Now visit your localhost and run across the changes: http://localhost:5000/.
Let'due south add more than pages
Let's create an about.html inside the templates folder.
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-viii"> <title>Nearly Flask</title> </head> <body> <h1> About Flask </h1> <p> Flask is a micro web framework written in Python.</p> <p> Applications that employ the Flask framework include Pinterest, LinkedIn, and the community web page for Flask itself.</p> </body> </html>
Permit's make a alter similar to what we did earlier to our primary.py.
from flask import Flask, render_template app = Flask(__name__) @app.road("/") def dwelling house(): return render_template("home.html") @app.road("/well-nigh) def near(): render render_template("near.html") if __name__ == "__main__": app.run(debug=True)
We made 3 new changes:
Line 9: Change the route to"/about"
.
Line 10: Change the part so it is now def about():
Line 11: Change the render so that now it returns render_template("almost.html")
.
Now meet the changes: http://localhost:5000/about.
Allow's Connect Both Pages with a Navigation
To connect both pages nosotros can have a navigation menu on the top. Nosotros can use Flask to make the procedure of creating a navigation menu easier.
First, permit'due south create a template.html. This template.html will serve every bit a parent template. Our ii child templates will inherit code from information technology.
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Flask Parent Template</championship> <link rel="stylesheet" href="{{ url_for('static', filename='css/template.css') }}"> </head> <torso> <header> <div class="container"> <h1 class="logo">First Web App</h1> <strong><nav> <ul grade="bill of fare"> <li><a href="{{ url_for('abode') }}">Home</a></li> <li><a href="{{ url_for('about') }}">Most</a></li> </ul> </nav></stiff> </div> </header> {% cake content %} {% endblock %} </trunk> </html>
Line 13–14: We use the part called url_for()
. Information technology accepts the name of the function as an argument. Right now we gave it the proper name of the part. More information on url_for() function .
The two lines with the curly brackets will be replaced by the content of home.html and virtually.html. This will depend on the URL in which the user is browsing.
These changes let the child pages (home.html and about.html) to connect to the parent (template.html). This allows us to not have to re-create the code for the navigation menu in the about.html and home.html.
Content of near.html:
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-viii"> <title>Near Flask</title> </caput> <body> {% extends "template.html" %} {% block content %} <h1> Almost Flask </h1> <p> Flask is a micro web framework written in Python.</p> <p> Applications that apply the Flask framework include Pinterest, LinkedIn, and the customs web page for Flask itself.</p> {% endblock %} </trunk> </html>
Content of domicile.html:
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <championship>Flask Tutorial</title> </caput> <body> {% extends "template.html" %} {% block content %} <h1> My First Try Using Flask </h1> <p> Flask is Fun </p> {% endblock %} </body> </html>
Let's attempt 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 binder chosen static.
In static, nosotros will shop our CSS, JavaScript, images, and other necessary files. That is why it is important that you should create a CSS binder to store your stylesheets. After you lot exercise this, your projection binder should await like this:
Linking our CSS with our HTML file
Our template.html is the one that links all pages. We can insert the lawmaking here and information technology will exist applicative to all child pages.
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <championship>Flask Parent Template</title> <link rel="stylesheet" href="{{ url_for('static', filename='css/template.css') }}"> </head> <body> <header> <div class="container"> <h1 class="logo">First Web App</h1> <strong><nav> <ul class="carte"> <li><a href="{{ url_for('domicile') }}">Home</a></li> <li><a href="{{ url_for('nearly') }}">About</a></li> </ul> </nav></stiff> </div> </header> {% block content %} {% endblock %} </body> </html>
Line seven: Here we are giving the path to where the template.css is located.
Now see the changes: http://localhost:5000/about.
Moving Forward with Flask and virtualenv
Now that you are familiar with using Flask, you may get-go using it in your future projects. One thing to e'er do is utilise virtualenv.
Why use virtualenv?
Y'all may utilise Python for others projects also web-evolution.
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 take its own dependencies regardless of what dependencies every other project has.
Getting started with virtualenv
Kickoff, run this command on your command prompt or terminal:
pip install virtualenv
2d, practise the following:
virtualenv "proper noun of virtual surround"
Here you tin give a name to the environment. I usually give it a name of virtual. It will await similar this: virtualenv virtual
.
After setting upward virtual surround, check your projection folder. It should look similar this. The virtual environment needs to be created in the aforementioned directory where your app files are located.
Activating the virtual surroundings
Now go to your terminal or command prompt. Go to the directory that contains the file chosen activate. The file called activate is constitute inside a folder chosen Scripts for Windows and bin for OS X and Linux.
For Bone X and Linux Environment:
$ name of virtual environmnet/bin/activate
For Windows Environment:
proper noun of virtual environment\Scripts\activate
Since I am using a Windows machine, when I activate the environment it volition look like this:
The next step is to install flask on your virtual surroundings then that we tin run the application within our environment. Run the command:
pip install flask
Run your application and get to http://localhost:5000/
We finally fabricated our web awarding. 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 transport it to the Cloud
To testify others the project we made, we will need to learn how to utilise Cloud Services.
Deploy Your Web Awarding to the Cloud
To deploy our spider web awarding to the cloud, we volition use Google App Engine (Standard Environment). This is an case of a Platform as a Service (PaaS).
PaaS refers to the delivery of operating systems and associated services over the internet without downloads or installation. The approach lets customers create and deploy applications without having to invest in the underlying infrastructure (More than info on PaaS cheque out TechTarget).
Google App Engine is a platform as a service offering that allows developers and businesses to build and run applications using Google'south advanced infrastructure — TechOpedia.
Before you Start:
You will demand a Google Account. Once you create an business relationship, become to the Google Cloud Platform Console and create a new project. Also, you need to install the Google Cloud SDK.
At the cease of this tutorial your project structure will wait like this.
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: truthful handlers: - url: /static static_dir: static - url: /.* script: main.app libraries: - name: ssl version: latest
If you lot were to check Google's Tutorial in the part where they talk most content of the app.yaml, it does not include the section where I wrote almost libraries.
When I starting time attempted to deploy my simple web app, my deployment never worked. After many attempts, I learned that nosotros needed to include the SSL library.
The SSL Library allows us to create secure connections betwixt 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 demand to create a secure connexion for this. (I recently learned this, and then 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 within our virtual environment (make sure your virtualenv is activated), we are going to install the new dependencies nosotros accept 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, employ this command.
gcloud app deploy
I normally include — project [ID of Projection]
This specifies what project you are deploying. The command volition wait similar this:
gcloud app deploy --project [ID of Project]
The Application
Now check the URL of your awarding. The application volition be store in the post-obit way:
"your projection id".appspot.com
My application is here: http://sal-flask-tutorial.appspot.com
Conclusion
From this tutorial, y'all all learned how to:
- Use the framework called Flask to utilize Python as a Server Side Language.
- Learned how to employ 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 3 important things from this small project.
Get-go, I learned virtually the deviation between a static website and a spider 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 alter when the user interacts with it.
Spider web Applications:
- A web awarding or dynamic website generates content based on retrieved data (nearly 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 exist slower and more than difficult to deploy than static websites for simple applications (Reddit).
Server Side and Customer Side:
- I learned that a web application has 2 sides. The customer side and the server side. The client side is what the user interacts with and the server side is where the all the data that the user inputted is processed.
Second, I learned about Cloud Services
Nigh 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 utilise GitHub Pages to host them. GitHub Pages is merely meant for static websites not for something dynamic similar a web application that requires a server and a database. I had to use Cloud Services such equally Amazon Web Services or Heroku
Third, I learned how to utilise Python equally a Server Side Language
To create the server side of the web application nosotros 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 tin build all sorts of things with Flask. I realized that Flask helps brand the lawmaking behind the website easier to read. I have made the following applications during this summertime of 2018 and I hope to make more.
Personal Projects
- A Twilio SMS App
- My Personal Website
During my internship
- Part of a projection where I learned most Docker and Containers
Here is the list of resources that helped me create this tutorial:
- "App Engine — Build Scalable Web & Mobile Backends in Whatever 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 Environs 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, world wide web.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 y'all have whatever suggestions or questions, feel free to get out a annotate.
Acquire to lawmaking for free. freeCodeCamp's open up source curriculum has helped more than 40,000 people get jobs as developers. Become started
Source: https://www.freecodecamp.org/news/how-to-build-a-web-application-using-flask-and-deploy-it-to-the-cloud-3551c985e492/
Posted by: richardsonscance.blogspot.com
0 Response to "How To Create A Delivery Service App"
Post a Comment