第 26 天
用于网络的 Python
Python 是一种通用编程语言,可用于许多地方。在本节中,我们将了解如何将 Python 用于 Web。有很多 Python web 框架作品。Django 和 Flask 是最受欢迎的。今天,我们将了解如何使用 Flask 进行 Web 开发。
Flask
Flask 是一个用 Python 编写的 Web 开发框架。Flask 使用 Jinja2 模板引擎。Flask 还可以与其他现代前端库一起使用,例如 React。
如果您没有安装 virtualenv 包,请先安装它。虚拟环境将允许将项目依赖项与本地机器依赖项隔离开来。
文件夹结构
完成所有步骤后,您的项目文件结构应如下所示:
├── Procfile
├── app.py
├── env
│ ├── bin
├── requirements.txt
├── static
│ └── css
│ └── main.css
└── templates
├── about.html
├── home.html
├── layout.html
├── post.html
└── result.html
设置项目目录
按照以下步骤开始使用 Flask。
第 1 步:使用以下命令安装 virtualenv。
pip install virtualenv
第2步:
asabeneh@Asabeneh:~/Desktop$ mkdir python_for_web
asabeneh@Asabeneh:~/Desktop$ cd python_for_web/
asabeneh@Asabeneh:~/Desktop/python_for_web$ virtualenv venv
asabeneh@Asabeneh:~/Desktop/python_for_web$ source venv/bin/activate
(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ pip freeze
(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ pip install Flask
(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ pip freeze
Click==7.0
Flask==1.1.1
itsdangerous==1.1.0
Jinja2==2.10.3
MarkupSafe==1.1.1
Werkzeug==0.16.0
(env) asabeneh@Asabeneh:~/Desktop/python_for_web$
我们创建了一个名为 python_for_web 的项目主管。在项目中,我们创建了一个虚拟环境venv,它可以是任何名称,但我更喜欢称它为venv。然后我们激活了虚拟环境。我们使用 pip freeze 查看项目目录下安装的包。pip freeze 的结果是空的,因为还没有安装包。
现在,让我们在项目目录中创建 app.py 文件并编写以下代码。app.py 文件将是项目中的主要文件。下面代码有flask模块,os模块。
创建路线
回家路线
# let's import the flask
from flask import Flask
import os # importing operating system module
app = Flask(__name__)
@app.route('/') # this decorator create the home route
def home ():
return '<h1>Welcome</h1>'
@app.route('/about')
def about():
return '<h1>About us</h1>'
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)
要运行 flask 应用程序,请在主 flask 应用程序目录中写入 python app.py。
运行python app.py后检查本地主机 5000。
让我们添加额外的路线。创建关于路线
# let's import the flask
from flask import Flask
import os # importing operating system module
app = Flask(__name__)
@app.route('/') # this decorator create the home route
def home ():
return '<h1>Welcome</h1>'
@app.route('/about')
def about():
return '<h1>About us</h1>'
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)
现在,我们在上面的代码中添加了 about 路由。如果我们想渲染一个 HTML 文件而不是字符串呢?可以使用函数render_templae渲染 HTML 文件。让我们创建一个名为 templates 的文件夹,并在项目目录中创建 home.html 和 about.html。让我们也从 flask 导入render_template函数。
创建模板
在 templates 文件夹中创建 HTML 文件。
主页.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Home</title>
</head>
<body>
<h1>Welcome Home</h1>
</body>
</html>
关于.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>About</title>
</head>
<body>
<h1>About Us</h1>
</body>
</html>
Python脚本
应用程序.py
# let's import the flask
from flask import Flask, render_template
import os # importing operating system module
app = Flask(__name__)
@app.route('/') # this decorator create the home route
def home ():
return render_template('home.html')
@app.route('/about')
def about():
return render_template('about.html')
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)
如您所见,要转到不同的页面或进行导航,我们需要导航。让我们为每个页面添加一个链接,或者让我们创建一个用于每个页面的布局。
导航
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
现在,我们可以使用上面的链接在页面之间导航。让我们创建处理表单数据的附加页面。你可以给它起任何名字,我喜欢叫它 post.html。
我们可以使用 Jinja2 模板引擎将数据注入 HTML 文件。
# let's import the flask
from flask import Flask, render_template, request, redirect, url_for
import os # importing operating system module
app = Flask(__name__)
@app.route('/') # this decorator create the home route
def home ():
techs = ['HTML', 'CSS', 'Flask', 'Python']
name = '30 Days Of Python Programming'
return render_template('home.html', techs=techs, name = name, title = 'Home')
@app.route('/about')
def about():
name = '30 Days Of Python Programming'
return render_template('about.html', name = name, title = 'About Us')
@app.route('/post')
def post():
name = 'Text Analyzer'
return render_template('post.html', name = name, title = name)
if __name__ == '__main__':
# for deployment
# to make it work for both production and development
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)
让我们也看看模板:
主页.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Home</title>
</head>
<body>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
<h1>Welcome to {{name}}</h1>
<ul>
{% for tech in techs %}
<li>{{tech}}</li>
{% endfor %}
</ul>
</body>
</html>
关于.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>About Us</title>
</head>
<body>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
<h1>About Us</h1>
<h2>{{name}}</h2>
</body>
</html>
创建布局
在模板文件中,有很多重复的代码,我们可以写一个布局,我们可以去掉重复的。让我们在模板文件夹中创建 layout.html。创建布局后,我们将导入到每个文件。
提供静态文件
在您的项目目录中创建一个静态文件夹。在静态文件夹中创建 CSS 或样式文件夹并创建 CSS 样式表。我们使用url_for模块来提供静态文件。
布局.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
href="https://fonts.googleapis.com/css?family=Lato:300,400|Nunito:300,400|Raleway:300,400,500&display=swap"
rel="stylesheet"
/>
<link
rel="stylesheet"
href="{{ url_for('static', filename='css/main.css') }}"
/>
{% if title %}
<title>30 Days of Python - {{ title}}</title>
{% else %}
<title>30 Days of Python</title>
{% endif %}
</head>
<body>
<header>
<div class="menu-container">
<div>
<a class="brand-name nav-link" href="/">30DaysOfPython</a>
</div>
<ul class="nav-lists">
<li class="nav-list">
<a class="nav-link active" href="{{ url_for('home') }}">Home</a>
</li>
<li class="nav-list">
<a class="nav-link active" href="{{ url_for('about') }}">About</a>
</li>
<li class="nav-list">
<a class="nav-link active" href="{{ url_for('post') }}"
>Text Analyzer</a
>
</li>
</ul>
</div>
</header>
<main>
{% block content %} {% endblock %}
</main>
</body>
</html>
现在,让我们删除其他模板文件中的所有重复代码并导入 layout.html。href 使用带有路径函数名称的url_for函数来连接每条导航路径。
主页.html
{% extends 'layout.html' %} {% block content %}
<div class="container">
<h1>Welcome to {{name}}</h1>
<p>
This application clean texts and analyse the number of word, characters and
most frequent words in the text. Check it out by click text analyzer at the
menu. You need the following technologies to build this web application:
</p>
<ul class="tech-lists">
{% for tech in techs %}
<li class="tech">{{tech}}</li>
{% endfor %}
</ul>
</div>
{% endblock %}
关于.html
{% extends 'layout.html' %} {% block content %}
<div class="container">
<h1>About {{name}}</h1>
<p>
This is a 30 days of python programming challenge. If you have been coding
this far, you are awesome. Congratulations for the job well done!
</p>
</div>
{% endblock %}
post.html
{% extends 'layout.html' %} {% block content %}
<div class="container">
<h1>Text Analyzer</h1>
<form action="https://thirtydaysofpython-v1.herokuapp.com/post" method="POST">
<div>
<textarea rows="25" name="content" autofocus></textarea>
</div>
<div>
<input type="submit" class="btn" value="Process Text" />
</div>
</form>
</div>
{% endblock %}
请求方法,有不同的请求方法(GET,POST,PUT,DELETE)是常见的请求方法,允许我们进行CRUD(Create,Read,Update,Delete)操作。
在帖子中,路由我们将根据请求的类型使用 GET 和 POST 方法替代,检查它在下面的代码中的样子。请求方法是处理请求方法和访问表单数据的函数。应用程序.py
# let's import the flask
from flask import Flask, render_template, request, redirect, url_for
import os # importing operating system module
app = Flask(__name__)
# to stop caching static file
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
@app.route('/') # this decorator create the home route
def home ():
techs = ['HTML', 'CSS', 'Flask', 'Python']
name = '30 Days Of Python Programming'
return render_template('home.html', techs=techs, name = name, title = 'Home')
@app.route('/about')
def about():
name = '30 Days Of Python Programming'
return render_template('about.html', name = name, title = 'About Us')
@app.route('/result')
def result():
return render_template('result.html')
@app.route('/post', methods= ['GET','POST'])
def post():
name = 'Text Analyzer'
if request.method == 'GET':
return render_template('post.html', name = name, title = name)
if request.method =='POST':
content = request.form['content']
print(content)
return redirect(url_for('result'))
if __name__ == '__main__':
# for deployment
# to make it work for both production and development
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)
到目前为止,我们已经了解了如何使用模板以及如何向模板注入数据,如何进行通用布局。现在,让我们处理静态文件。在project director中创建一个名为static的文件夹,并创建一个名为css的文件夹。在 css 文件夹中创建 main.css。你的主要。css 文件将链接到 layout.html。
你不必编写css文件,复制并使用它。让我们继续部署。
部署
创建 Heroku 帐户
Heroku 为前端和全栈应用程序提供免费部署服务。在heroku上创建一个帐户并为你的机器安装 heroku CLI。安装好 heroku 后写下面的命令
登录到 Heroku
asabeneh@Asabeneh:~$ heroku login
heroku: Press any key to open up the browser to login or q to exit:
让我们通过单击键盘上的任意键来查看结果。当您按下键盘上的任意键时,它将打开 heroku 登录页面并单击登录页面。然后你将本地机器连接到远程 heroku 服务器。如果你连接到远程服务器,你会看到这个。
asabeneh@Asabeneh:~$ heroku login
heroku: Press any key to open up the browser to login or q to exit:
Opening browser to https://cli-auth.heroku.com/auth/browser/be12987c-583a-4458-a2c2-ba2ce7f41610
Logging in... done
Logged in as asabeneh@gmail.com
asabeneh@Asabeneh:~$
创建需求和 Procfile
在我们将代码推送到远程服务器之前,我们需要需求
- 要求.txt
- 简介
(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ pip freeze Click==7.0 Flask==1.1.1 itsdangerous==1.1.0 Jinja2==2.10.3 MarkupSafe==1.1.1 Werkzeug==0.16.0 (env) asabeneh@Asabeneh:~/Desktop/python_for_web$ touch requirements.txt (env) asabeneh@Asabeneh:~/Desktop/python_for_web$ pip freeze > requirements.txt (env) asabeneh@Asabeneh:~/Desktop/python_for_web$ cat requirements.txt Click==7.0 Flask==1.1.1 itsdangerous==1.1.0 Jinja2==2.10.3 MarkupSafe==1.1.1 Werkzeug==0.16.0 (env) asabeneh@Asabeneh:~/Desktop/python_for_web$ touch Procfile (env) asabeneh@Asabeneh:~/Desktop/python_for_web$ ls Procfile env/ static/ app.py requirements.txt templates/ (env) asabeneh@Asabeneh:~/Desktop/python_for_web$
在我们的 Heroku 案例中,Procfile 将具有在 Web 服务器中运行应用程序的命令。
web: python app.py
将项目推送到 heroku
现在,它已准备好部署。在 heroku 上部署应用程序的步骤
- 初始化
- 混帐添加。
- git commit -m "提交消息"
- heroku 创建“应用程序的名称作为一个词”
- git push heroku 大师
- heroku open(启动已部署的应用程序)
🎉恭喜!🎉