本文共 13555 字,大约阅读时间需要 45 分钟。
by Tristan Ganry
由Tristan Ganry
If you want to build web apps in a very short amount of time using Python, then is a fantastic option.
如果您想使用Python在很短的时间内构建Web应用程序,那么是一个不错的选择。
Flask is a small and powerful web framework (also known as “”). 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 .
最终产品可以在查看。
To create a weather app, we will need to request an API key from . 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 instead.
要创建天气应用,我们需要从请求API密钥。 免费版本每分钟最多允许60个呼叫,这对于此应用程序来说已经绰绰有余。 开放天气图条件图标不是很漂亮。 我们将改用的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 , HTML, and CSS
第3步:使用 ,HTML和CSS为应用创建2个页面(主页面和结果页面)
Step 4: Deploying and testing on your local laptop
步骤4:在本地笔记本电脑上进行部署和测试
Step 5: Deploying on Google Cloud.
步骤5:在Google Cloud上进行部署。
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.
使用虚拟环境,您可以为每个项目创建一个本地环境。 您可以选择要使用的库,而不会影响您的笔记本电脑环境。 当您在笔记本电脑上编写更多项目时,每个项目将需要不同的库。 对于每个项目,使用不同的虚拟环境,您的系统与项目之间或项目之间不会有冲突。
#Optionalpip install virtualenvwrapper-winpip install virtualenv
#Mandatorymkdir WeatherAppcd WeatherAppvirtualenv venv
call venv\Scripts\activate.bat
Flask==0.12.3click==6.7gunicorn==19.7.1itsdangerous==0.24Jinja2==2.9.6MarkupSafe==1.0pytz==2017.2requests==2.13.0Werkzeug==0.12.1
pip install -r requirements.txt
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.
您已照顾好当地环境。 现在,您可以专注于开发应用程序。 此步骤是确保正确的文件夹和文件结构到位。 下一步将处理后端代码。
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创建一个函数,该函数可根据所选城市检索天气数据。 该函数填充结果页面。
#!/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)
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
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 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.
这是我第一次使用模板库填充HTML文件。 令我惊讶的是,带来动态图像或使用功能(例如舍入天气)是如此容易。 绝对是一个出色的模板引擎。
Weather in a City
{% for d in data %} {% set my_string = "static/img/" + d['weather'][0]['icon']+ ".svg" %}
Weather
{ { d['name'] }}, { { d['sys']['country'] }}
{ { d['main']['temp']|round|int}} °C
{% endfor %}
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;}
Link with the images on :
与上的图像链接:
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.
在此阶段,您已经设置了环境,结构,后端和前端。 剩下的唯一事情就是启动您的应用程序并在您的本地主机上享受它。
python main.py
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
按照安装SDK
Connect to your Google Cloud Account (use if you haven’t already)
连接到您的Google Cloud帐户(如果尚未使用,请使用 )
runtime: python27api_version: 1threadsafe: true
handlers:- url: /static static_dir: static- url: /.* script: main.app libraries: - name: ssl version: latest
from google.appengine.ext import vendor
# Add any libraries installed in the "lib" folder.vendor.add('lib')
pip install -t lib -r requirements.txt
gcloud auth application-default logingcloud config set project <PROJECT_ID>gcloud initgcloud app deploy app.yaml
Enjoy your live web app for free. Mine is .
免费享受您的实时网络应用程序。 我的 。
The full code is available on . Thank you for reading my post. It was my first web app using Flask and first Tutorial on . 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.
完整的代码可以在 。 感谢您阅读我的帖子。 这是我的第一个使用Flask的Web应用程序以及上的第一个Tutorial。 如果您觉得这篇文章有帮助,请给我一些鼓掌? 它具有Python和R的数据科学背景,比我想象的要容易得多。
Feel free to contact if you want to make a simple or more complex Flask App.
如果您想制作一个简单或更复杂的Flask应用,请随时与联系。
翻译自:
转载地址:http://icewd.baihongyu.com/