{% raw %}

Python 和 Flask Web 应用程序(入门教程)

原文: https://pythonspot.com/flask-web-app-with-python/

51.md - 图1

使用 Flask 创建的 Python 应用

在本教程中,您将学习如何使用 Python 构建网络应用。 我们将使用称为 Flask 的微型框架。

为什么是 Flask?

  • 易于使用。

  • 内置开发服务器和调试器

  • 集成单元测试支持

  • RESTful 请求分派

  • 使用 Jinja2 模板

  • 支持安全 cookie(客户端会话)

  • 100%符合 WSGI 1.0

  • 基于 Unicode

  • 大量记录

创建 URL 路由

URL 路由使 Web 应用程序中的 URL 易于记住。 现在,我们将创建一些 URL 路由:

  1. /hello
  2. /members/
  3. /members/name/

复制下面的代码,并将其另存为app.py

  1. from flask import Flask
  2. app = Flask(__name__)
  3. @app.route("/")
  4. def index():
  5. return "Index!"
  6. @app.route("/hello")
  7. def hello():
  8. return "Hello World!"
  9. @app.route("/members")
  10. def members():
  11. return "Members"
  12. @app.route("/members/<string:name>/")
  13. def getMember(name):
  14. return name</string:name>
  15. if __name__ == "__main__":
  16. app.run()

使用以下命令重新启动应用程序:

  1. $ python hello.py
  2. * Running on http://localhost:5000/

在浏览器中尝试网址:

51.md - 图2

python-flask-webapp

Flask 页面模板

我们将使用称为模板的技术将代码和用户界面分开。 我们创建名为/templates/的目录并创建模板:

  1. <h1>Hello {{name}}</h1>

Python Flask 应用具有新的 URL 路由。 我们将默认端口更改为 80,即默认 HTTP 端口:

  1. from flask import Flask, flash, redirect, render_template, request, session, abort
  2. app = Flask(__name__)
  3. @app.route("/")
  4. def index():
  5. return "Flask App!"
  6. @app.route("/hello/<string:name>/")
  7. def hello(name):
  8. return render_template(
  9. 'test.html',name=name)</string:name>
  10. if __name__ == "__main__":
  11. app.run(host='0.0.0.0', port=80)

You can then open : http://127.0.0.1/hello/Jackson/

给模板添加样式

您是否需要一些外观更好的模板? 我们修改文件:

  1. {% extends "layout.html" %};
  2. {% block body %};
  3. <div class="block1">
  4. <h1>Hello {{name}}!</h1>
  5. <h2>Here is an interesting quote for you:</h2>
  6. "The limits of my language are the limits of my mind. All I know is what I have words for."
  7. <img src="http://www.naturalprogramming.cimg/smilingpython.gif">
  8. </div>
  9. {% endblock %};

然后,我们创建layout.html来定义页面的外观。 (您可能想要拆分样式表和layout.html文件)。将此复制为layout.html

  1. <title>Website</title>
  2. <style>
  3. @import url(http://fonts.googleapis.com/css?family=Amatic+SC:700);</p>
  4. <p>body{<br />
  5. text-align: center;<br />
  6. }<br />
  7. h1{<br />
  8. font-family: 'Amatic SC', cursive;<br />
  9. font-weight: normal;<br />
  10. color: #8ac640;<br />
  11. font-size: 2.5em;<br />
  12. }</p>
  13. </style>{% block body %};{% endblock %};

重新启动应用程序并打开 URL:http://127.0.0.1/hello/Jackson/,您可以选择杰克逊以外的任何其他名字。

51.md - 图3

python webapp flask

传递变量

让我们显示随机引文,而不是总是相同的引文。我们将需要同时传递name变量和quote变量。要将多个变量传递给函数,我们只需执行以下操作:

  1. return render_template(
  2. 'test.html',**locals())

我们新的test.html模板如下所示:

  1. {% extends "layout.html" %};
  2. {% block body %};
  3. <div class="block1">
  4. <h1>Hello {{name}}!</h1>
  5. <h2>Here is an interesting quote for you:</h2>
  6. {{quote}}
  7. <img src="http://www.naturalprogramming.cimg/smilingpython.gif">
  8. </div>
  9. {% endblock %};

我们将需要选择一个随机引文。 为此,我们使用以下代码:

  1. quotes = [ "'If people do not believe that mathematics is simple, it is only because they do not realize how complicated life is.' -- John Louis von Neumann ",
  2. "'Computer science is no more about computers than astronomy is about telescopes' -- Edsger Dijkstra ",
  3. "'To understand recursion you must first understand recursion..' -- Unknown",
  4. "'You look at things that are and ask, why? I dream of things that never were and ask, why not?' -- Unknown",
  5. "'Mathematics is the key and door to the sciences.' -- Galileo Galilei",
  6. "'Not everyone will understand your journey. Thats fine. Its not their journey to make sense of. Its yours.' -- Unknown" ]
  7. randomNumber = randint(0,len(quotes)-1)
  8. quote = quotes[randomNumber]

您看到的第一件事是我们定义了一个包含多个引文的数组。 这些可以作为quote[0]quote[1]quote[2]等访问。函数randint()返回一个介于 0 和引文总数之间的随机数,因为我们从零开始计数,所以减去了一个。最后,我们将quote变量设置为计算机选择的引文。将以下代码复制到app.py

  1. from flask import Flask, flash, redirect, render_template, request, session, abort
  2. from random import randint
  3. app = Flask(__name__)
  4. @app.route("/")
  5. def index():
  6. return "Flask App!"
  7. #@app.route("/hello/<string:name>")
  8. @app.route("/hello/<string:name>/")
  9. def hello(name):
  10. # return name
  11. quotes = [ "'If people do not believe that mathematics is simple, it is only because they do not realize how complicated life is.' -- John Louis von Neumann ",
  12. "'Computer science is no more about computers than astronomy is about telescopes' -- Edsger Dijkstra ",
  13. "'To understand recursion you must first understand recursion..' -- Unknown",
  14. "'You look at things that are and ask, why? I dream of things that never were and ask, why not?' -- Unknown",
  15. "'Mathematics is the key and door to the sciences.' -- Galileo Galilei",
  16. "'Not everyone will understand your journey. Thats fine. Its not their journey to make sense of. Its yours.' -- Unknown" ]
  17. randomNumber = randint(0,len(quotes)-1)
  18. quote = quotes[randomNumber] </string:name></string:name>
  19. return render_template(
  20. 'test.html',**locals())
  21. if __name__ == "__main__":
  22. app.run(host='0.0.0.0', port=80)

重新启动应用程序时,它将随机返回这些引文之一。

51.md - 图4

python flask webap

下载应用程序以及更多 Flask 示例

接下来是什么?

您可以将您的站点链接到数据库系统,例如 MySQL,MariaDb 或 SQLite。 您可以在中找到 SQLite 教程。 享受创建您的应用程序的乐趣!

{% endraw %}