如何使用Python的Flask和Google App Engine构建网络应用

by Tristan Ganry

由Tristan Ganry

这是一个小型教程项目,用于为初学者学习Flask,API和Google App Engine。 (This is a small tutorial project for learning Flask, APIs, and Google App Engine for beginners.)

If you want to build web apps in a very short amount of time using Python, then Flask is a fantastic option.

如果您想使用Python在很短的时间内构建Web应用程序,那么Flask是一个不错的选择。

Flask is a small and powerful web framework (also known as “microframework”). It is also very easy to learn and simple to code. Based on my personal experience, it was easy to start as a beginner.

Flask是一个小型而强大的Web框架(也称为“ 框架”)。 它也是非常容易学习和易于编写的。 根据我的个人经验,初学者很容易上手。

Before this project, my knowledge of Python was mostly limited to Data Science. Yet, I was able to build this app and create this tutorial in just a few hours.

在进行此项目之前,我对Python的了解主要限于数据科学。 但是,我仅用几个小时就可以构建此应用程序并创建本教程。

In this tutorial, I’ll show you how to build a simple weather app with some dynamic content using an API. This tutorial is a great starting point for beginners. You will learn to build dynamic content from APIs and deploying it on Google Cloud.

在本教程中,我将向您展示如何使用API​​构建具有一些动态内容的简单天气应用。 对于初学者来说,本教程是一个很好的起点。 您将学习从API构建动态内容并将其部署到Google Cloud上。

The end product can be viewed here.

最终产品可以在这里查看。

To create a weather app, we will need to request an API key from Open Weather Map. The free version allows up to 60 calls per minute, which is more than enough for this app. The Open Weather Map conditions icons are not very pretty. We will replace them with some of the 200+ weather icons from Erik Flowers instead.

要创建天气应用,我们需要从Open Weather Map中请求API密钥。 免费版本每分钟最多允许60个呼叫,这对于此应用程序来说已经绰绰有余。 开放天气图条件图标不是很漂亮。 我们将改用Erik Flowers的200多种天气图标中的某些代替。

This tutorial will also cover: (1) basic CSS design, (2) basic HTML with Jinja, and (3) deploying a Flask app on Google Cloud.

本教程还将涵盖:(1)基本CSS设计,(2)使用Jinja的基本HTML,以及(3)在Google Cloud上部署Flask应用。

The steps we’ll take are listed below:

下面列出了我们将采取的步骤:

  • Step 0: Installing Flask (this tutorial doesn’t cover Python and PIP installation)

    步骤0:安装Flask(本教程不介绍Python和PIP安装)

  • Step 1: Building the App structure

    步骤1:建立App结构

  • Step 2: Creating the Main App code with the API request

    步骤2:使用API​​请求创建Main App代码

  • Step 3: Creating the 2 pages for the App (Main and Result) with Jinja, HTML, and CSS

    第3步:使用Jinja ,HTML和CSS为应用创建2个页面(主页面和结果页面)

  • Step 4: Deploying and testing on your local laptop

    步骤4:在本地笔记本电脑上进行部署和测试

  • Step 5: Deploying on Google Cloud.

    步骤5:在Google Cloud上进行部署。

步骤0 —安装Flask和我们将在虚拟环境中使用的库。 (Step 0 — Installing Flask and the libraries we will use in a virtual environment.)

We’ll build this project using a virtual environment. But why do we need one?

我们将使用虚拟环境构建该项目。 但是为什么我们需要一个呢?

With virtual environments, you create a local environment specific for each projects. You can choose libraries you want to use without impacting your laptop environment. As you code more projects on your laptop, each project will need different libraries. With a different virtual environment for each project, you won’t have conflicts between your system and your projects or between projects.

使用虚拟环境,您可以为每个项目创建一个本地环境。 您可以选择要使用的库,而不会影响您的笔记本电脑环境。 当您在笔记本电脑上编写更多项目时,每个项目将需要不同的库。 对于每个项目,使用不同的虚拟环境,您的系统与项目之间或项目之间不会有冲突。

  • Run Command Prompt (cmd.exe) with administrator privileges. Not using admin privileges will prevent you from using pip.

    使用管理员权限运行命令提示符(cmd.exe)。 不使用管理员权限将阻止您使用pip。
  • (Optional) Install virtualenv and virtualenvwrapper-win with PIP. If you already have these system libraries, please jump to the next step.

    (可选)使用PIP安装virtualenv和virtualenvwrapper-win。 如果您已经拥有这些系统库,请跳至下一步。
#Optionalpip install virtualenvwrapper-winpip install virtualenv
  • Create your folder with the name “WeatherApp” and make a virtual environment with the name “venv” (it can take a bit of time)

    创建名称为“ WeatherApp”的文件夹,并创建名称为“ venv”的虚拟环境(这可能需要一些时间)
#Mandatorymkdir WeatherAppcd WeatherAppvirtualenv venv
  • Activate your virtual environment with “call” on Windows (same as “source” for Linux). This step changes your environment from the system to the project local environment.

    在Windows上通过“呼叫”来激活您的虚拟环境(与Linux的“源”相同)。 此步骤将您的环境从系统更改为项目本地环境。
call venv\Scripts\activate.bat
  • Create a requirements.txt file that includes Flask and the other libraries we will need in your WeatherApp folder, then save the file. The requirements file is a great tool to also keep track of the libraries you are using in your project.

    创建一个Requirements.txt文件,其中包括Flask和我们在WeatherApp文件夹中需要的其他库,然后保存该文件。 需求文件是一个很好的工具,可以跟踪您在项目中使用的库。
Flask==0.12.3click==6.7gunicorn==19.7.1itsdangerous==0.24Jinja2==2.9.6MarkupSafe==1.0pytz==2017.2requests==2.13.0Werkzeug==0.12.1
  • Install the requirements and their dependencies. You are now ready to build your WeatherApp. This is the final step to create your local environment.

    安装需求及其依赖性。 现在,您可以开始构建WeatherApp了。 这是创建本地环境的最后一步。
pip install -r requirements.txt
第1步-构建App结构 (Step 1 — Building the App structure)

You have taken care of the local environment. You can now focus on developing your application. This step is to make sure the proper folder and file structure is in place. The next step will take care of the backend code.

您已照顾好当地环境。 现在,您可以专注于开发应用程序。 此步骤是确保正确的文件夹和文件结构到位。 下一步将处理后端代码。

  • Create two Python files (main.py, weather.py) and two folders (static with a subfolder img, templates).

    创建两个Python文件(main.py,weather.py)和两个文件夹(带有子文件夹img的静态文件夹,模板)。
第2步-使用API​​请求创建主应用程序代码(后端) (Step 2 — Creating the Main App code with the API request (Backend))

With the structure set up, you can start coding the backend of your application. Flask’s “Hello world” example only uses one Python file. This tutorial uses two files to get you comfortable with importing functions to your main app.

通过设置结构,您可以开始对应用程序的后端进行编码。 Flask的“ Hello world”示例仅使用一个Python文件。 本教程使用两个文件来使您适应将功能导入到主应用程序。

The main.py is the server that routes the user to the homepage and to the result page. The weather.py file creates a function with API that retrieves the weather data based on the city selected. The function populates the resulting page.

main.py是将用户路由到首页和结果页的服务器。 weather.py文件使用API​​创建一个函数,该函数可根据所选城市检索天气数据。 该函数填充结果页面。

  • Edit main.py with the following code and save

    使用以下代码编辑main.py并保存
#!/usr/bin/env pythonfrom pprint import pprint as ppfrom flask import Flask, flash, redirect, render_template, request, url_forfrom weather import query_api
app = Flask(__name__)
@app.route('/')def index():    return render_template(        'weather.html',        data=[{'name':'Toronto'}, {'name':'Montreal'}, {'name':'Calgary'},        {'name':'Ottawa'}, {'name':'Edmonton'}, {'name':'Mississauga'},        {'name':'Winnipeg'}, {'name':'Vancouver'}, {'name':'Brampton'},         {'name':'Quebec'}])
@app.route("/result" , methods=['GET', 'POST'])def result():    data = []    error = None    select = request.form.get('comp_select')    resp = query_api(select)    pp(resp)    if resp:       data.append(resp)    if len(data) != 2:        error = 'Bad Response from Weather API'    return render_template(        'result.html',        data=data,        error=error)
if __name__=='__main__':    app.run(debug=True)
  • Request a free API key on Open Weather Map

    在开放式天气地图上请求免费的API密钥
  • Edit weather.py with the following code (updating the API_KEY) and save

    使用以下代码(更新API_KEY)编辑weather.py并保存
from datetime import datetimeimport osimport pytzimport requestsimport mathAPI_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX'API_URL = ('http://api.openweathermap.org/data/2.5/weather?q={}&mode=json&units=metric&appid={}')
def query_api(city):    try:        print(API_URL.format(city, API_KEY))        data = requests.get(API_URL.format(city, API_KEY)).json()    except Exception as exc:        print(exc)        data = None    return data
第3步-使用Jinja ,HTML和CSS创建页面(前端) (Step 3 — Creating pages with Jinja, HTML, and CSS (Frontend))

This step is about creating what the user will see.

此步骤是关于创建用户将看到的内容。

The HTML pages weather and result are the one the backend main.py will route to and give the visual structure. The CSS file will bring the final touch. There is no Javascript in this tutorial (the front end is pure HTML and CSS).

HTML页面的天气和结果是后端main.py将路由并给出视觉结构的页面。 CSS文件将带来最终效果。 本教程中没有Javascript(前端是纯HTML和CSS)。

It was my first time using the Jinja2 template library to populate the HTML file. It surprised me how easy it was to bring dynamic images or use functions (e.g. rounding weather). Definitely a fantastic template engine.

这是我第一次使用Jinja2模板库填充HTML文件。 令我惊讶的是,带来动态图像或使用功能(例如舍入天气)是如此容易。 绝对是一个出色的模板引擎。

  • Create the first HTML file in the templates folder (weather.html)

    在模板文件夹中创建第一个HTML文件(weather.html)
<!doctype html><link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
<div class="center-on-page">  <h1>Weather in a City</h1>
<form class="form-inline" method="POST" action="{{ url_for('result') }}">   <div class="select">    <select name="comp_select" class="selectpicker form-control">    {% for o in data %}     <option value="{{ o.name }}">{{ o.name }}</option>    {% endfor %}    </select>   </div>    <button type="submit" class="btn">Go</button></form>
  • Create the second HTML file in the templates folder (result.html)

    在模板文件夹中创建第二个HTML文件(result.html)
<!doctype html>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
<div class="center-on-page">
{% for d in data %} {% set my_string = "static/img/" + d['weather'][0]['icon']+ ".svg" %}    <h1>  <img src="{{ my_string }}" class="svg" fill="white" height="100" vertical-align="middle" width="100"> </h1>  <h1>Weather</h1> <h1>{{ d['name'] }}, {{ d['sys']['country'] }}</h1>    <h1>{{ d['main']['temp']|round|int}} °C</h1>{% endfor %}
  • Add a CSS file in the static folder (style.css)

    在静态文件夹(style.css)中添加CSS文件
body {  color: #161616;  font-family: 'Roboto', sans-serif;  text-align: center;  background-color: currentColor;}.center-on-page {  position: absolute;  top:50%;  left: 50%;  transform: translate(-50%,-50%);}h1 {  text-align: center;  color:#FFFFFF;}img {  vertical-align: middle; }/* Reset Select */select {  -webkit-appearance: none;  -moz-appearance: none;  -ms-appearance: none;  appearance: none;  outline: 0;  box-shadow: none;  border: 0 !important;  background: #2c3e50;  background-image: none;}/* Custom Select */.select {  position: relative;  display: block;  width: 20em;  height: 3em;  line-height: 3;  background: #2c3e50;  overflow: hidden;  border-radius: .25em;}select {  width: 100%;  height: 100%;  margin: 0;  padding: 0 0 0 .5em;  color: #fff;  cursor: pointer;}select::-ms-expand {  display: none;}/* Arrow */.select::after {  content: '\25BC';  position: absolute;  top: 0;  right: 0;  bottom: 0;  padding: 0 1em;  background: #34495e;  pointer-events: none;}/* Transition */.select:hover::after {  color: #f39c12;}.select::after {  -webkit-transition: .25s all ease;  -o-transition: .25s all ease;  transition: .25s all ease;}
button{  -webkit-appearance: none;  -moz-appearance: none;  -ms-appearance: none;  appearance: none;  outline: 0;  box-shadow: none;  border: 0 !important;  background: #2c3e50;  background-image: none;  width: 100%;  height: 40px;  margin: 0;  margin-top: 20px;  color: #fff;  cursor: pointer;  border-radius: .25em;}.button:hover{  color: #f39c12;}
  • Download the images in the img subfolder in static

    静态下载img子文件夹中的图像

Link with the images on Github:

Github上的图像链接:

第4步-本地部署和测试 (Step 4 — Deploying and testing locally)

At this stage, you have set up the environment, the structure, the backend, and the frontend. The only thing left is to launch your app and to enjoy it on your localhost.

在此阶段,您已经设置了环境,结构,后端和前端。 剩下的唯一事情就是启动您的应用程序并在您的本地主机上享受它。

  • Just launch the main.py with Python

    只需使用Python启动main.py
python main.py
  • Go to the localhost link proposed on cmd with your Web Browser (Chrome, Mozilla, etc.). You should see your new weather app live on your local laptop :)

    使用Web浏览器(Chrome,Mozilla等)转到cmd上建议的localhost链接。 您应该在本地笔记本电脑上看到新的天气应用程序:)
第5步-在Google Cloud上进行部署 (Step 5 — Deploying on Google Cloud)

This last step is for sharing your app with the world. It’s important to note that there are plenty of providers for web apps built using Flask. Google Cloud is just one of many. This article does not cover some of the others like AWS, Azure, Heroku…

最后一步是与世界共享您的应用程序。 重要的是要注意,有很多使用Flask构建的Web应用程序的提供程序。 Google Cloud只是其中之一。 本文不涉及其他一些东西,例如AWS,Azure,Heroku ...

If the community is interested, I can provide the steps of the other cloud providers in another article and some comparison (pricing, limitations, etc.).

如果社区有兴趣,我可以在另一篇文章中提供其他云提供商的步骤以及一些比较(定价,限制等)。

To deploy your app on Google Cloud you will need to 1) Install the SDK, 2) Create a new project, 3) Create 3 local files, 4) Deploy and test online.

要在Google Cloud上部署您的应用,您需要1)安装SDK,2)创建一个新项目,3)创建3个本地文件,4)在线部署和测试。

  • Install the SDK following Google’s instructions

    按照Google的说明安装SDK

  • Connect to your Google Cloud Account (use a $300 coupon if you haven’t already)

    连接到您的Google Cloud帐户(如果尚未使用,请使用$ 300的优惠券 )

  • Create a new project and save the project id (wait a bit until the new project is provisioned)

    创建一个新项目并保存该项目的ID(稍等片刻,直到配置了新项目)
  • Create an app.yaml file in your main folder with the following code:

    使用以下代码在主文件夹中创建一个app.yaml文件:
runtime: python27api_version: 1threadsafe: true
handlers:- url: /static  static_dir: static- url: /.*  script: main.app  libraries:  - name: ssl    version: latest
  • Create an appengine_config.py file in your main folder with the following code:

    使用以下代码在主文件夹中创建一个appengine_config.py文件:
from google.appengine.ext import vendor
# Add any libraries installed in the "lib" folder.vendor.add('lib')
  • Replicate the library’s dependencies in lib folder

    在lib文件夹中复制库的依赖项
pip install -t lib -r requirements.txt
  • Deploy on Google Cloud using your save project ID (it can take 10 minutes). Use the following steps:

    使用您的保存项目ID在Google Cloud上进行部署(可能需要10分钟)。 使用以下步骤:
gcloud auth application-default logingcloud config set project &lt;PROJECT_ID>gcloud initgcloud app deploy app.yaml
  • Enjoy your live web app for free. Mine is here.

    免费享受您的实时网络应用程序。 我的在这里

The full code is available on Github. Thank you for reading my post. It was my first web app using Flask and first Tutorial on freeCodeCamp. If you found this article helpful, give me some claps ?. It was a lot easier than I thought it would, coming from a Data Science background with Python and R.

完整的代码可以在Github上找到 。 感谢您阅读我的帖子。 这是我的第一个使用Flask的Web应用程序以及freeCodeCamp上的第一个Tutorial。 如果您觉得这篇文章有帮助,请给我一些鼓掌? 它具有Python和R的数据科学背景,比我想象的要容易得多。

Feel free to contact me if you want to make a simple or more complex Flask App.

如果您想制作一个简单或更复杂的Flask应用,请随时与联系。

翻译自: https://www.freecodecamp.org/news/how-to-build-a-web-app-using-pythons-flask-and-google-app-engine-52b1bb82b221/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值