Python 30 天:第 26 天 -- Python for web

<< 第 25 天 || 第 27 天 >>

第 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 上部署应用程序的步骤

  1. 初始化
  2. 混帐添加。
  3. git commit -m "提交消息"
  4. heroku 创建“应用程序的名称作为一个词”
  5. git push heroku 大师
  6. heroku open(启动已部署的应用程序)

 🎉恭喜!🎉

<< 第 25 天 || 第 27 天 >>​​​​​​​

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Flask-Paginate是一个Flask扩展,它提供了一种简单的方法来实现分页功能。它基于SQLAlchemy,并且可以与任何SQLAlchemy支持的数据库一起使用。 首先,你需要安装Flask-Paginate扩展。可以通过以下命令来安装: ``` pip install Flask-Paginate ``` 然后,你需要导入Flask-Paginate扩展并创建一个分页器。以下是一个简单的示例: ```python from flask_paginate import Pagination, get_page_args @app.route('/') def index(): # 获取当前页码和每页显示的数量 page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page') # 从数据库中获取数据 data = get_data_from_database(offset=offset, per_page=per_page) # 创建分页器 pagination = Pagination(page=page, per_page=per_page, total=count_total_items_in_database(), css_framework='bootstrap4') # 渲染模板 return render_template('index.html', data=data, pagination=pagination) ``` 在上面的示例中,我们首先使用`get_page_args`函数从请求参数中获取当前页码和每页显示的数量。然后,我们从数据库中获取数据,并使用`Pagination`类创建一个分页器对象。最后,我们将数据和分页器对象传递给模板进行渲染。 在模板中,你可以使用`prev_href`,`next_href`和`links`属性来生成分页器的HTML代码。以下是一个简单的示例: ```html <div class="pagination"> <a href="{{ pagination.prev_href() }}">Previous</a> {% for page in pagination.links %} {% if page == '...' %} <span class="ellipsis">...</span> {% elif page == pagination.page %} <span class="current">{{ page }}</span> {% else %} <a href="{{ page }}">{{ page }}</a> {% endif %} {% endfor %} <a href="{{ pagination.next_href() }}">Next</a> </div> ``` 上面的代码会生成一个类似于以下HTML代码的分页器: ```html <div class="pagination"> <a href="/?page=1&per_page=10">Previous</a> <a href="/?page=1&per_page=10">1</a> <a href="/?page=2&per_page=10">2</a> <a href="/?page=3&per_page=10">3</a> <a href="/?page=4&per_page=10">4</a> <a href="/?page=5&per_page=10">5</a> <span class="ellipsis">...</span> <a href="/?page=10&per_page=10">10</a> <a href="/?page=2&per_page=10">Next</a> </div> ``` 此外,你还可以使用`prev_disabled`和`next_disabled`属性来禁用“上一页”和“下一页”链接,如果当前页码是第一页或最后一页的话。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

舍不得,放不下

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值