提交 bf573ae3 编写于 作者: W wizardforcel

2019-11-19 11:45:09

上级 d45ee5d4
......@@ -13,7 +13,7 @@
可重用的语句组,有助于结构化代码并提高了可读性。
**3.类**
这些类用于<u>创建具有功能和变量的对象</u>。 字符串是对象的示例:字符串书具有功能 book.replace()和 book.lowercase()。 这种样式通常称为面向对象编程。
这些类用于创建具有功能和变量的对象。 字符串是对象的示例:字符串书具有功能 book.replace()和 book.lowercase()。 这种样式通常称为面向对象编程。
让我们一起潜水吧!
......
......@@ -8,7 +8,7 @@
![python-debugging-pudb](img/be30d3c5aa2158a9864d173116eb6291.jpg)
Python Debug with PuDB
使用 PuDB 进行 Python 调试
使用 PuDB 终端显示了图形界面。
......@@ -46,13 +46,13 @@ $ pudb3 program.py
![pudb-debug](img/224bd2a6a881437fdda6c2509430673e.jpg)
debug with python
python 调试
您可以使用 **b** 键设置断点。 要继续执行直到下一个断点,请按 **c** 键。
![python-breakpoint](img/b4dc9a1dbd2f3dbfa9b8223a63b62c12.jpg)
Breakpoint in Python program
Python 程序中的断点
## PDB-Python 调试器
......
......@@ -4,39 +4,39 @@
在本教程中,您将学习如何在 Python 中使用 SQLite [数据库](https://pythonspot.com/python-database/)管理系统。 您将学习如何使用 SQLite,SQL 查询,RDBMS 以及更多有趣的东西!
**Related course:** [Master SQL Databases with Python](https://gumroad.com/l/JImAU)
## Pyton 数据库
![Python Database ](img/4c7e8cbef62872a3c49fc4085527514d.jpg)
Python Database.
Data is retrieved from a database system using the SQL language. Data is everywhere and software applications use that. Data is either in memory, files or databases.
Python数据库。
Python has bindings for many database systems including [MySQL](https://pythonspot.com/mysql-with-python), [Postregsql](https://pythonspot.com/python-database-postgresql/), Oracle, Microsoft SQL Server and Maria DB.
使用 SQL 语言从数据库系统检索数据。 数据无处不在,软件应用程序使用它。 数据位于内存,文件或数据库中。
One of these database management systems (DBMS) is called SQLite. SQLite was created in the year 2000 and is one of the many management systems in the database zoo.
Python 具有许多数据库系统的绑定,包括 [MySQL](https://pythonspot.com/mysql-with-python), [Postregsql](https://pythonspot.com/python-database-postgresql/), Oracle, Microsoft SQL Server 和 Maria DB。
SQL is a special-purpose programming language designed for managing data held in a [databases](https://pythonspot.com/python-database/). The language has been around since 1986 and is worth learning. The [is an old funny video about SQL](https://www.youtube.com/watch?v=5ycx9hFGHog)
这些数据库管理系统(DBMS)之一称为 SQLite。 SQLite 创建于 2000 年,是数据库动物园中众多管理系统之一。
SQL 是专用于管理[数据库](https://pythonspot.com/python-database/)中保存的数据的专用编程语言。该语言自 1986 年以来一直存在,值得学习。[这是关于 SQL 的古老有趣的视频](https://www.youtube.com/watch?v=5ycx9hFGHog)
## SQLite
![SQLite](img/b49bf74e6651a4fea2a00aefd48f3b71.jpg)
SQLite, a relational database management system. SQLite is the most widely deployed SQL database engine in the world. The source code for SQLite is in the public domain.
SQLite,一个关系数据库管理系统。SQLite 是世界上部署最广泛的 SQL 数据库引擎。SQLite 的源代码位于公共领域。
It is a self-contained, serverless, zero-configuration, transactional SQL database engine. The SQLite project is sponsored by Bloomberg and Mozilla.
它是一个自包含,无服务器,零配置的事务型 SQL 数据库引擎。SQLite 项目由彭博社和 Mozilla 赞助。
## 安装 SQLite:
Use this command to install SQLite:
使用此命令安装 SQLite:
```py
$ sudo apt-get install sqlite
```
Verify if it is correctly installed. Copy this program and save it as test1.py
验证是否正确安装。 复制此程序并将其另存为`test1.py`
```py
#!/usr/bin/python
......@@ -62,41 +62,41 @@ finally:    
```
Execute with:
执行:
```py
$ python test1.py
```
It should output:
它应该输出:
```py
SQLite version: 3.8.2
```
## What did the script above do?
## 上面的脚本做了什么?
The script connected to a new database called test.db with this line:
该脚本使用以下代码行连接到名为`test.db`的新数据库:
```py
con = lite.connect('test.db')
```
It then queries the database management system with the command
然后,它使用以下命令查询数据库管理系统
```py
SELECT SQLITE_VERSION()
```
which in turn returned its version number. That line is known as an SQL query.
依次返回其版本号。 该行称为 SQL 查询。
## SQL 创建和插入
The script below will store data into a new database called user.db
下面的脚本会将数据存储到名为`user.db`的新数据库中
```py
#!/usr/bin/python
......@@ -117,14 +117,14 @@ with con:
```
SQLite is a database management system that uses tables. These tables can have relations with other tables: it’s called relational database management system or RDBMS. The table defines the structure of the data and can hold the data. A database can hold many different tables. The table gets created using the command:
SQLite 是使用表的数据库管理系统。 这些表可以与其他表建立关系:称为关系数据库管理系统或 RDBMS。 该表定义了数据的结构并可以保存数据。 数据库可以容纳许多不同的表。 使用以下命令创建表:
```py
cur.execute("CREATE TABLE Users(Id INT, Name TEXT)")
```
We add records into the table with these commands:
我们使用以下命令将记录添加到表中:
```py
cur.execute("INSERT INTO Users VALUES(2,'Sonya')")
......@@ -132,15 +132,15 @@ cur.execute("INSERT INTO Users VALUES(3,'Greg')")
```
The first value is the ID. The second value is the name. Once we run the script the data gets inserted into the database table Users:
第一个值是ID。 第二个值是名称。 一旦运行脚本,数据便被插入到数据库表`Users`中:
![SQL Table](img/6331a77064535de9dc0a93e8b103f00d.jpg)
SQL Table
SQL
## SQLite 查询数据
We can explore the database using two methods: the command line and a graphical interface.
我们可以使用两种方法浏览数据库:命令行和图形界面。
_ 从控制台:_ 要使用命令行进行浏览,请键入以下命令:
......@@ -184,7 +184,7 @@ sqliteman
## SQL 数据库查询语言
SQL has many commands to interact with the [database](https://pythonspot.com/python-database/). You can try the commands below from the command line or from the GUI:
SQL 有许多命令可以与[数据库](https://pythonspot.com/python-database/)进行交互。 您可以从命令行或 GUI 尝试以下命令:
```py
sqlite3 user.db
......
......@@ -29,7 +29,7 @@ yum install mysql-python
_ 在 Mac 上:_
按照 stackoverflow 的安装说明[](https://stackoverflow.com/questions/1448429/how-to-install-mysqldb-python-data-access-library-to-mysql-on-mac-os-x#1448476)
<u>必须先运行 MySQL 服务器,然后再进行下一步。</u>
必须先运行 MySQL 服务器,然后再进行下一步。
## 步骤 2:设置数据库
......
......@@ -8,7 +8,7 @@
![ORM Object Relational Mapping](img/9146e41d31ff53b16fd2fbb13d3f823e.jpg)
ORM Object Relational Mapping. We communicate with the database using the ORM and only use Python objects and classes.
ORM 对象关系映射。 我们使用 ORM 与数据库进行通信,并且仅使用 Python 对象和类。
## 创建一个类来填充 ORM
......@@ -16,7 +16,7 @@ ORM Object Relational Mapping. We communicate with the database using the ORM an
![class](img/56afbfa748895a916cb9a83cb407e791.jpg)
Class definition
类定义
请注意,我们没有定义任何方法,仅定义了类的变量。 这是因为我们会将此类映射到数据库,因此不需要任何方法。
......@@ -121,7 +121,7 @@ ORM 会将 Python 对象映射到关系数据库。 这意味着您无需与应
![Data in database table.](img/deb55c16c07fa22d5f0e10f36f49e448.jpg)
Data in database table.
数据表中的数据。
## 查询数据
......
......@@ -15,7 +15,7 @@ Web 应用程序通常是使用框架创建的。 框架使开发可扩展,可
* 会话管理
* 防范常见攻击
A framework may offer some or all of these features.
框架可以提供部分或全部这些功能。
例如,Flask Web 应用程序框架不支持数据库,您将需要一个单独的模块来使用数据库。 Django Web 应用程序框架默认支持数据库。
......@@ -23,25 +23,27 @@ A framework may offer some or all of these features.
## 为什么要使用 Web 框架?
As you are doing web development, you want to avoid spending time on programming things that have already been solved. On the other hand, if you are an experienced web developer a web framework may not offer everything you need.
在进行 Web 开发时,您要避免花费时间在已经解决的事情上进行编程。 另一方面,如果您是经验丰富的 Web 开发人员,则 Web 框架可能无法提供您所需的一切。
## 存在哪些 Python Web 框架?
Django and Flask are the most popular web frameworks. However, you may want to evaluate the frameworks. An overview:
Django 和 Flask 是最受欢迎的Web框架。 但是,您可能需要评估框架。 概述:
* [Django](https://www.djangoproject.com/)
* [Flask](http://flask.pocoo.org/)
* [](http://bottlepy.org/docs/dev/index.html)
* [金字塔](http://www.pylonsproject.org/projects/pyramid/about)
* [松饼](https://github.com/klen/muffin)
* [Bottle](http://bottlepy.org/docs/dev/index.html)
* [Pyramid](http://www.pylonsproject.org/projects/pyramid/about)
* [Muffin](https://github.com/klen/muffin)
* [CherryPy](http://www.cherrypy.org/)
* [web2py](http://www.web2py.com/)
* [猎鹰](http://falconframework.org/)
* [Falcon](http://falconframework.org/)
* [Turbo2Gears](http://turbogears.org/)
The most popular python web application framework is **Django**, followed by **Flask**.
最受欢迎的 python Web 应用程序框架是 Django,其次是 Flask。
[<picture><source srcset="/wp-content/uploads/2015/08/python-web-development.jpg.webp" type="image/webp"> <source srcset="/wp-content/uploads/2015/08/python-web-development.jpg" type="image/jpeg"> ![python web development](img/5a539b08d07773dbba46f659b5d1743c.jpg) </picture>](/wp-content/uploads/2015/08/python-web-development.jpg) 在 Github 上提及框架的项目数量。
![python web development](img/5a539b08d07773dbba46f659b5d1743c.jpg)
在 Github 上提及框架的项目数量。
## Django
......@@ -62,15 +64,15 @@ The most popular python web application framework is **Django**, followed by **F
* 国际化
* 安全
If you want to know more about Django, [read here.](https://pythonspot.com/django-tutorial-building-a-note-taking-app/)Did you know the websites of [NASA](https://www.nasa.gov/), [Bitbucket](https://bitbucket.org/) and [Pinterest](https://www.pinterest.com/) were made with Django?
如果您想进一步了解 Django,[阅读这里](https://pythonspot.com/django-tutorial-building-a-note-taking-app/)。你知道 [NASA](https://www.nasa.gov/)[Bitbucket](https://bitbucket.org/)[Pinterest](https://www.pinterest.com/) 的网站是用 Django 制作的嘛?
## Flask
![flask-logo](img/2a47be594c5c80724c14a822dd96b251.jpg)
[Flask](http://flask.pocoo.org/) is a Python micro framework which is modular by design. The framework is intended to build web apps. Flask does not have a specific database system or ORM system. If you want to use a database, you’ll have to use extensions. Flask is often combined with SQLAlchemy for database use.
[Flask](http://flask.pocoo.org/) 是一个通过设计模块化的 Python 微框架。 该框架旨在构建 Web 应用程序。 Flask 没有特定的数据库系统或 ORM 系统。 如果要使用数据库,则必须使用扩展。 Flask 通常与 SQLAlchemy 结合使用以用于数据库。
Flask is very easy to get running, a minimal app would be:
Flask 非常易于运行,一个最小的应用程序是:
```py
from flask import Flask
......@@ -85,9 +87,9 @@ if __name__ == '__main__':
```
The framework supports URL routing, template (using Jinja2), session management and has some out of the box security.
该框架支持 URL 路由,模板(使用 Jinja2),会话管理,并具有一些现成的安全性。
**Features**:
**特性**
* URL 路由和视图
......@@ -97,13 +99,13 @@ The framework supports URL routing, template (using Jinja2), session management
* 记录中
If you want to know more about Flask[, read here.](https://pythonspot.com/python-flask-tutorials/)
Did you know Flask started as an April Fools joke?
如果您想进一步了解 Flask,[阅读这里](https://pythonspot.com/python-flask-tutorials/)。您知道 Flask 最初是愚人节的笑话吗?
## Python 托管
To run your app on the web, you will need hosting. Unless you want to do hosting yourself, you need a party to host.
Hosting servers:
要在网络上运行您的应用,您需要托管。 除非您想自己托管,否则需要一个第三方来托管。
托管服务器:
* [PythonAnywhere.com](https://www.pythonanywhere.com/?affiliate_id=00535ced)
......
......@@ -6,10 +6,10 @@
我们将使用称为 [Flask](https://pythonspot.com/python-flask-tutorials/) 的微型框架。 它的核心很小,但是可以通过许多插件扩展,例如 SQLAlchemy,Babel,CouchDB,MongoDB 等。
一些 Flask 示例应用为:
一些 Flask 示例应用为:
* [flaskr](http://flask.pocoo.org/docs/0.10/tutorial/introduction/) -微博
* [minitwit](https://github.com/mitsuhiko/flask/tree/master/examples/minitwit/) -一个推特克隆
* [minitwit](https://github.com/mitsuhiko/flask/tree/master/examples/minitwit/) -- 一个推特克隆
* [flask 网站](https://github.com/mitsuhiko/flask-website)-静态页面+邮件列表文件
## 安装 Flask
......@@ -23,7 +23,7 @@ pip install Flask
## Flask Hello World 应用程序
Create a file called hello.py
创建一个名为`hello.py`的文件
```py
......@@ -49,4 +49,4 @@ $ python hello.py
在您的网络浏览器中打开 [http:// localhost:5000 /](http://localhost:5000/) ,然后会出现“ Hello World!”。
[下载 Flask 示例](https://pythonspot.com/download-flask-examples/)
\ No newline at end of file
[下载 Flask 示例](https://pythonspot.com/download-flask-examples/)
\ No newline at end of file
......@@ -16,7 +16,7 @@ Jinja2 模板只是一个文本文件,不需要特定的扩展名,例如.htm
| <raw><…#><endraw></endraw></raw> | 注释未包含在模板输出中 |
| <raw>#…##<endraw></endraw></raw> | 行语句 |
In the example above we have two statements and one expression.  We have not included any comments.
在上面的示例中,我们有两个语句和一个表达式。 我们还没有包含任何注释。
## 基本模板和子模板
......@@ -74,4 +74,4 @@ python app.py
Flask Jinja template engine
[下载烧瓶示例](https://pythonspot.com/download-flask-examples/)
\ No newline at end of file
[下载 Flask 示例](https://pythonspot.com/download-flask-examples/)
\ No newline at end of file
......@@ -4,7 +4,7 @@
![python-flask-webap](img/a9c26e973da367c3f6e0289252c0c55a.jpg)
Python app created with Flask
使用 Flask 创建的 Python 应用
在本教程中,您将学习如何使用 Python 构建网络应用。 我们将使用称为 Flask 的微型框架。
......@@ -31,7 +31,7 @@ Python app created with Flask
## 创建 URL 路由
URL Routing makes URLs in your Web app easy to remember. We will now create some URL routes:
URL 路由使 Web 应用程序中的 URL 易于记住。 现在,我们将创建一些 URL 路由:
```py
/hello
......@@ -91,15 +91,15 @@ python-flask-webapp
## Flask 页面模板
We will separate code and User Interface using a technique called Templates. We make the directory called /templates/ and create the template:
我们将使用称为模板的技术将代码和用户界面分开。 我们创建名为`/templates/`的目录并创建模板:
```py
<h1>Hello { {name}}</h1>
<h1>Hello {{name}}</h1>
```
The Python Flask app with have a new URL route. We have changed the default port to 80, the default HTTP port:
Python Flask 应用具有新的 URL 路由。 我们将默认端口更改为 80,即默认 HTTP 端口:
```py
from flask import Flask, flash, redirect, render_template, request, session, abort
......@@ -124,24 +124,24 @@ You can then open : [http://127.0.0.1/hello/Jackson/](http://127.0.0.1/hello/Jac
## 给模板添加样式
Do you want some better looking template? We modify the file:
您是否需要一些外观更好的模板? 我们修改文件:
```py
&#123;% extends "layout.html" %&#125;
&#123;% block body %&#125;
{% extends "layout.html" %};
{% block body %};
<div class="block1">
<h1>Hello { {name}}!</h1>
<h1>Hello {{name}}!</h1>
<h2>Here is an interesting quote for you:</h2>
"The limits of my language are the limits of my mind. All I know is what I have words for."
<img src="http://www.naturalprogramming.cimg/smilingpython.gif">
</div>
&#123;% endblock %&#125;
{% endblock %};
```
We then create layout.html which defines the look of the page. (You may want to split the stylesheet and layout.html file). Copy this as layout.html
然后,我们创建`layout.html`来定义页面的外观。 (您可能想要拆分样式表和`layout.html`文件)。将此复制为`layout.html`
```py
......@@ -158,12 +158,11 @@ h1{<br />
color: #8ac640;<br />
font-size: 2.5em;<br />
}</p>
</style>&#123;% block body %&#125;&#123;% endblock %&#125;
</style>{% block body %};{% endblock %};
```
Restart the App and open the url. [http://127.0.0.1/hello/Jackson/](http://127.0.0.1/hello/Jackson/)
You can pick any name other than Jackson.
重新启动应用程序并打开 URL:[http://127.0.0.1/hello/Jackson/](http://127.0.0.1/hello/Jackson/),您可以选择杰克逊以外的任何其他名字。
![python-webapp-flask](img/596080c3f68a2e0f8ba4ca54f064272d.jpg)
......@@ -171,7 +170,7 @@ python webapp flask
## 传递变量
Lets display random quotes instead of always the same quote. We will need to pass both the _name variable_ and the _quote variable_. To pass multiple variables to the function, we simply do this:
让我们显示随机引文,而不是总是相同的引文。我们将需要同时传递`name`变量和`quote`变量。要将多个变量传递给函数,我们只需执行以下操作:
```py
return render_template(
......@@ -179,24 +178,24 @@ Lets display random quotes instead of always the same quote. We will need to pas
```
Our new _test.html template_ will look like this:
我们新的`test.html`模板如下所示:
```py
&#123;% extends "layout.html" %&#125;
&#123;% block body %&#125;
{% extends "layout.html" %};
{% block body %};
<div class="block1">
<h1>Hello { {name}}!</h1>
<h1>Hello {{name}}!</h1>
<h2>Here is an interesting quote for you:</h2>
{ {quote}}
{{quote}}
<img src="http://www.naturalprogramming.cimg/smilingpython.gif">
</div>
&#123;% endblock %&#125;
{% endblock %};
```
We will need to pick a random quote. To do so, we use this code:
我们将需要选择一个随机引文。 为此,我们使用以下代码:
```py
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 ",
......@@ -210,7 +209,7 @@ quote = quotes[randomNumber]
```
The first thing you see is we have defined an array of multiples quotes. These can be accessed as quote[0], quote[1], quote[2] and so on. The function **randint()** returns a random number between 0 and the total number of quotes, one is subtracted because we start counting from zero. Finally we set the quote variable to the quote the computer has chosen. Copy the code below to app.py:
您看到的第一件事是我们定义了一个包含多个引文的数组。 这些可以作为`quote[0]``quote[1]``quote[2]`等访问。函数`randint()`返回一个介于 0 和引文总数之间的随机数,因为我们从零开始计数,所以减去了一个。最后,我们将`quote`变量设置为计算机选择的引文。将以下代码复制到`app.py`
```py
from flask import Flask, flash, redirect, render_template, request, session, abort
......@@ -244,14 +243,14 @@ if __name__ == "__main__":
```
When you restart the application it will return one of these quotes at random.
重新启动应用程序时,它将随机返回这些引文之一。
![python-flask-webap](img/a9c26e973da367c3f6e0289252c0c55a.jpg)
python flask webap
[下载应用程序以及更多烧瓶示例](https://pythonspot.com/en/download-flask-examples/)
[下载应用程序以及更多 Flask 示例](https://pythonspot.com/en/download-flask-examples/)
## 接下来是什么?
您可以将您的站点链接到数据库系统,例如 MySQL,MariaDb 或 SQLite。 您可以在中找到 [SQLite 教程。 享受创建您的应用程序的乐趣!](https://pythonspot.com/en/python-database-programming-sqlite-tutorial/)
\ No newline at end of file
您可以将您的站点链接到数据库系统,例如 MySQL,MariaDb 或 SQLite。 您可以在中找到 [SQLite 教程](https://pythonspot.com/en/python-database-programming-sqlite-tutorial/)。 享受创建您的应用程序的乐趣!
\ No newline at end of file
......@@ -4,13 +4,13 @@
![flask-logo](img/18374e2fa266165025a38238c3cdc35f.jpg)
The Flask Logo
Flask 图标
在本教程中,您将学习如何使用 [Flask](https://pythonspot.com/en/python-flask-tutorials/) 和 Python 构建登录 Web 应用程序。
### 建立一个 Flask 登录页面
Create this Python file and save it as app.py:
创建此 Python 文件并将其另存为`app.py`
```py
from flask import Flask
......@@ -53,20 +53,20 @@ app.run(debug=True,host='0.0.0.0', port=4000)
我们创建目录/ templates /。 使用以下代码创建文件/templates/login.html:
```py
&#123;% block body %&#125;
&#123;% if session['logged_in'] %&#125;
{% block body %};
{% if session['logged_in'] %};
You're logged in already!
&#123;% else %&#125;
{% else %};
<form action="/login" method="POST">
<input type="username" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="submit" value="Log in">
</form>
&#123;% endif %&#125;
&#123;% endblock %&#125;
&#123;% endraw %&#125;
{% endif %};
{% endblock %};
{% endraw %};
```
......@@ -79,13 +79,14 @@ $ python hello.py
在您的网络浏览器中打开 [http:// localhost:4000 /](http://localhost:5000/) ,然后会出现登录屏幕。 登录凭据显示在 _do_admin_login()_ 函数中。
<caption id=”attachment_49” align=”alignnone” width=”620”]![Pythonspot.com Login Screen Python](img/00af7aae4e992d7feccf73ba2c75cb8f.jpg)
![Pythonspot.com Login Screen Python](img/00af7aae4e992d7feccf73ba2c75cb8f.jpg)
Pythonspot.com Login Screen Python
Pythonspot.com 登录界面
### 使它看起来很棒
While functional, the login screen looks like an early 90s User Interface (UI). We picked a random login template from [codepen.io](https://codepen.io). We create the directory /static/ with the file style.css.
功能正常时,登录屏幕看起来像 90 年代初期的用户界面(UI)。 我们从 [codepen.io](https://codepen.io) 中选择了一个随机登录模板。 我们使用文件`style.css`创建目录`/static/`
```py
* {
......@@ -169,11 +170,11 @@ margin-top: 12px;
```
Modify the login.html template as:
`login.html`模板修改为:
```py
<link rel="stylesheet" href="/static/style.css" type="text/css">
&#123;% block body %&#125;
{% block body %};
<form action="/login" method="POST">
<div class="login">
......@@ -194,21 +195,21 @@ Modify the login.html template as:
</div>
</div>
</form>
&#123;% endblock %&#125;
{% endblock %};
```
Once you restart the application this screen should appear:
重新启动应用程序后,将出现以下屏幕:
<caption id=”attachment_267” align=”alignnone” width=”823”]![Python login screen Flask](img/fb0c1e80aa99b4e5cdf8e4159b31d784.jpg)
![Python login screen Flask](img/fb0c1e80aa99b4e5cdf8e4159b31d784.jpg)
Python login screen [**Flask**](https://pythonspot.com/en/python-flask-tutorials/)
Python Flask 登录界面
很棒,不是吗? :-)
### 那么注销呢?
As you may have seen, there is no logout button or functionality. Creating that is very easy. The solution proposed below is only one of the many solutions. We create a new route /logout which directs to the function logout(). This function clears the session variable and returns to the login screen.
如您所见,没有注销按钮或功能。 创建起来非常容易。 下面提出的解决方案只是众多解决方案之一。 我们创建一个新的路由`/logout`,它直接指向函数`logout()`。 此函数清除会话变量并返回登录屏幕。
```py
@app.route("/logout")
......@@ -255,7 +256,7 @@ app.run(debug=True,host='0.0.0.0', port=4000)
### 连接数据库
If you want a multi-user login system, you should add a database layer to the application. Flask does not have out of the box database support. You have to use a third party library if you want database support. In this tutorial we will use SqlAlchemy. If you do not have that installed type:
如果要使用多用户登录系统,则应在应用程序中添加一个数据库层。Flask 没有现成的数据库支持。 如果要数据库支持,则必须使用第三方库。 在本教程中,我们将使用 SqlAlchemy。 如果您没有安装,请执行以下操作:
```py
$ sudo pip install Flask-SqlAlchemy
......@@ -414,9 +415,9 @@ app.run(debug=True,host='0.0.0.0', port=4000)
### 那么安全性呢?
We have demonstrated a simple login app above. However, it is your job to properly secure it. There are many guys out there that are going to try to break into your app.
我们在上面演示了一个简单的登录应用程序。 但是,正确保护它是您的工作。 有很多人会尝试闯入您的应用程序。
[下载烧瓶示例](https://pythonspot.com/en/download-flask-examples/)
[下载 Flask 示例](https://pythonspot.com/en/download-flask-examples/)
_ 最佳做法:_
......
......@@ -8,7 +8,7 @@
> OAuth 是一种使用令牌来代表资源所有者访问资源的协议。 考虑使用户能够对网站的某些部分发出代客密钥。 许多网站,例如 Google,Facebook 和 Twitter,都使用 OAuth 来认证第三方客户端,以便访问某些用户资源。
Don’t worry if that sounds vague, we’ll take you through the steps.
如果听起来含糊,请放心,我们将逐步指导您。
## 使用 Google 的登录验证
......@@ -114,8 +114,8 @@ python app.py
![google_oauth_login_python](img/da268e0c364d3bc6fcbf891258c7d557.jpg)
Login to your Flask app with Google
使用 Google 登录到您的 Flask 应用
最后,您可以验证是否在新路由上设置了访问令牌。
[
[下载烧瓶示例](https://pythonspot.com/en/download-flask-examples/)
\ No newline at end of file
[下载 Flask 示例](https://pythonspot.com/en/download-flask-examples/)
\ No newline at end of file
......@@ -8,7 +8,7 @@
> OAuth 是一种使用令牌来代表资源所有者访问资源的协议。 考虑使用户能够对网站的某些部分发出代客密钥。 许多网站,例如 Google,Facebook 和 Twitter,都使用 OAuth 来认证第三方客户端,以便访问某些用户资源。
Don’t worry if that sounds vague, we’ll take you through the steps.
如果听起来含糊,请放心,我们将逐步指导您。
## 代码
......@@ -104,18 +104,18 @@ app.run()
使用文件 index.html 创建目录/ templates /
```py
&#123;% block body %&#125;
{% block body %};
<h2>Flask Login App</h2>
&#123;% if session['screen_name'] %&#125;
Hello &#123; &#123; session['screen_name'] &#125;&#125;!
&#123;% else %&#125;
{% if session['screen_name'] %};
Hello {{ session['screen_name'] };};!
{% else %};
Sign in with twitter.
<a href="&#123; &#123; url_for('login') &#125;&#125;"><img src="&#123; &#123;
url_for('static', filename='sign-in.png') &#125;&#125; alt="sign in"></a>
&#123;% endif %&#125;
&#123;% endblock %&#125;
<a href="{{ url_for('login') };};"><img src="{{
url_for('static', filename='sign-in.png') };}; alt="sign in"></a>
{% endif %};
{% endblock %};
```
......@@ -134,10 +134,14 @@ python app.py
![Flask Login Twitter](img/26f8399bf1c15d18bf11bd65253f1c25.jpg)
Flask Login Twitter Screen ![Flask OAuth Twitter](img/4771c932e36a9c118f5967ffccc36b4e.jpg)
Flask Twitter 登录界面
Flask OAuth Twitter ![twitter_oauth](img/bdac172cb293a59affa870d6d1998358.jpg)
![Flask OAuth Twitter](img/4771c932e36a9c118f5967ffccc36b4e.jpg)
Flask OAuth Twitter
![twitter_oauth](img/bdac172cb293a59affa870d6d1998358.jpg)
twitter_oauth
[下载烧瓶示例](https://pythonspot.com/download-flask-examples/)
\ No newline at end of file
[下载 Flask 示例](https://pythonspot.com/download-flask-examples/)
\ No newline at end of file
......@@ -6,7 +6,7 @@
## 获取 JSON 数据
To display awesome charts we first need some data. There are two common ways to get data in web apps: data from servers using an API (usually JSON) and data from databases. I use the Fixer.io JSON API to get some financial data, but any JSON API should do. If you are unfamiliar with [JSON, see this article.](https://pythonspot.com/json-encoding-and-decoding-with-python/)
要显示很棒的图表,我们首先需要一些数据。有两种常见的方法可以在 Web 应用程序中获取数据:使用 API(通常为 JSON)的服务器中的数据和数据库中的数据。 我使用 Fixer.io JSON API 来获取一些财务数据,但是任何 JSON API 都可以。 如果您不熟悉 JSON,[请参阅此文章](https://pythonspot.com/json-encoding-and-decoding-with-python/)
我们编写此脚本来获取汇率:
......@@ -33,7 +33,7 @@ print rates
## 使用 Flask 的 Google Charts API
With the [Google Charts API](https://developers.google.com/chart/interactive/docs/gallery) you can display live data on your site. There are a lot of great charts there that are easy to add to your Flask app. We simply give the data that we got from the server through JSON and parsed, to the Google Charts API.
使用 [Google Charts API](https://developers.google.com/chart/interactive/docs/gallery),您可以在网站上显示实时数据。有很多很棒的图表可以轻松添加到 Flask 应用中。我们只需将通过 JSON 从服务器获取并解析的数据提供给 Google Charts API。
为目录创建带有目录/ templates /的 flask 应用程序。 这是 Flask 的主要代码:
......@@ -116,8 +116,8 @@ app.run()
结果:
<caption id=”attachment_770” align=”alignnone” width=”855”]![Flask App](img/f10feda9b4de908651d49d99ae3924e4.jpg)
![Flask App](img/f10feda9b4de908651d49d99ae3924e4.jpg)
Flask App
[下载烧瓶示例](https://pythonspot.com/download-flask-examples/)
\ No newline at end of file
[下载 Flask 示例](https://pythonspot.com/download-flask-examples/)
\ No newline at end of file
......@@ -4,7 +4,7 @@
![Flask wtforms](img/e1ecb442d3cf63667cc8d8f265ea6fb7.jpg)
Flask web form
Flask web 表单
在本教程中,您将学习如何使用 Flask 进行表单验证。 表单在所有 Web 应用程序中都扮演着重要角色。
......@@ -12,7 +12,7 @@ Flask web form
## CSS 与 Flask
We use bootstrap to style the form.Bootstrap is a popular HTML, CSS, and JS framework for developing responsive, mobile first projects on the web. It makes front-end web development faster and easier. The output will be:
我们使用 Bootstrap 来设置表单的样式。Bootstrap 是流行的 HTML,CSS 和 JS 框架,用于在 Web 上开发响应式,移动优先项目。 它使前端 Web 开发更快,更轻松。 输出将是:
![Flask wtforms](img/fcfe05a322371b16b27393f14b96f8b2.jpg)
......@@ -66,7 +66,7 @@ if __name__ == "__main__":
<div class="container">
<h2>Flask Web Form</h2>
<form action="" method="post" role="form">
{ { form.csrf }}
{{ form.csrf }}
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="What's your name?"></div>
......@@ -77,12 +77,12 @@ if __name__ == "__main__":
{% for message in messages %}
{% if "Error" not in message[1]: %}
<div class="alert alert-info">
<strong>Success! </strong> { { message[1] }}</div>
<strong>Success! </strong> {{ message[1] }}</div>
{% endif %}
{% if "Error" in message[1]: %}
<div class="alert alert-warning">
{ { message[1] }}</div>
{{ message[1] }}</div>
{% endif %}
{% endfor %}
{% endif %}
......@@ -94,7 +94,7 @@ if __name__ == "__main__":
## Flask 注册表
We use the same principle to create a registration form asking for name, email and password. We update the Form class:
我们使用相同的原理来创建注册表,要求输入姓名,电子邮件和密码。 我们更新`Form`类:
```py
class ReusableForm(Form):
......@@ -169,7 +169,7 @@ if __name__ == "__main__":
<div class="container">
<h2>Flask Web Form</h2>
<form action="" method="post" role="form">
{ { form.csrf }}
{{ form.csrf }}
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="What's your name?">
......@@ -188,12 +188,12 @@ if __name__ == "__main__":
{% for message in messages %}
{% if "Error" not in message[1]: %}
<div class="alert alert-info">
<strong>Success! </strong> { { message[1] }}</div>
<strong>Success! </strong> {{ message[1] }}</div>
{% endif %}
{% if "Error" in message[1]: %}
<div class="alert alert-warning">
{ { message[1] }}</div>
{{ message[1] }}</div>
{% endif %}
{% endfor %}
{% endif %}
......@@ -207,8 +207,8 @@ if __name__ == "__main__":
![flask form bootstrap](img/f7ac284ac78f49d58761139b6641f9fb.jpg)
flask form bootstrap
flask 表单 bootstrap
[下载烧瓶示例](/download-flask-examples/)
[下载 Flask 示例](/download-flask-examples/)
WTForms 可以验证电子邮件,密码,数字等等。 有关验证器的列表,请参见: [http://wtforms.readthedocs.org/en/latest/validators.html](https://wtforms.readthedocs.org/en/latest/validators.html)
\ No newline at end of file
WTForms 可以验证电子邮件,密码,数字等等。 有关验证器的列表,请参见:[http://wtforms.readthedocs.org/en/latest/validators.html](https://wtforms.readthedocs.org/en/latest/validators.html)
\ No newline at end of file
......@@ -41,7 +41,7 @@ def render_static(page_name):
```
&lt; / string:page_name &gt;
`/<string:page_name>/`
创建目录/ templates /并添加文件 hello.html:
......@@ -65,4 +65,4 @@ $ python app.py
例如,可以使用 [http://127.0.0.1:5000/hello](http://127.0.0.1:5000/hello) 访问静态文件 hello.html。 您可以将任何 css 文件存储在/ static /目录中。
[下载烧瓶示例](https://pythonspot.com/download-flask-examples/)
\ No newline at end of file
[下载 Flask 示例](https://pythonspot.com/download-flask-examples/)
\ No newline at end of file
......@@ -71,4 +71,4 @@ python manage.py runserver
![cookiecutter](img/bbadfcdfb92f4eda0d40720b8d0e771e.jpg)
cookiecutter output theme
\ No newline at end of file
cookiecutter 输出主题
\ No newline at end of file
......@@ -4,13 +4,12 @@
![Flask piechart](img/42212723a1a77a8a66fecd11fd3d5165.jpg)
[**Flask**](/python-flask-tutorials) webapp with pie chart In this article you will learn how to create great looking charts using [Chart.js](http://www.chartjs.org) and [**Flask**](/python-flask-tutorials).
带有饼图的 Flask webapp
Chart.js is a javascript library to create simple and clean charts. All of them are HTML5 based, responsive, modular, interactive and there are in total 6 charts.
在本文中,您将学习如何使用 [Chart.js](http://www.chartjs.org)[Flask](/ python-flask-tutorials)。
## Related course
Chart.js 是一个 JavaScript 库,用于创建简单干净的图表。它们都是基于 HTML5 的,响应式的,模块化的,交互式的,共有 6 个图表。
[Python Flask: Make Web Apps with Python](https://gum.co/IMzBy)
```py
<meta charset="utf-8"> <title>Chart.js </title> <!-- import plugin script --> <script src="static/Chart.min.js"></script>
......@@ -48,7 +47,7 @@ Chart.js is a javascript library to create simple and clean charts. All of them
```
Create the directory /static/ and add the file [Chart.min.js](https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js) to it. You can get it either from the Chart.js website or use the link. Finally go into the home directory and create app.py with this contents:
创建目录`/static/`并将文件[`Chart.min.js`](https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js)添加到其中。您可以从 Chart.js 网站获得它,也可以使用链接。 最后进入主目录并使用以下内容创建`app.py`
```py
from flask import Flask
......@@ -68,23 +67,26 @@ app.run(host='0.0.0.0', port=5001)
```
Finally run:
最后运行:
```py
python app.py
```
Open [http://127.0.0.1:5001/](http://127.0.0.1:5001/) and you will see the array values[] plotted with the data in labels[].
We simply pass these two arrays to render_template(). This means that most of the magic occurs in the template. Chart.js is a client-side javascript library which is why our app.py is very minimal.
打开 [http://127.0.0.1:5001/](http://127.0.0.1:5001/),您会看到数组`values[]`与数据中的`labels[]`一起绘制。
Result: ![Flask barchart](img/be653e10825576897782b24bebe362dd.jpg)
我们只需将这两个数组传递给`render_template()`即可。这意味着大多数魔术都发生在模板中。 Chart.js 是一个客户端 javascript 库,因此我们的`app.py`非常少。
Flask barchart
结果:
![Flask barchart](img/be653e10825576897782b24bebe362dd.jpg)
Flask 条形图
### 使用 Chart.js 和 Flask 创建折线图
To create a line chart, we can simply modify the chart.html template. Change it to:
要创建折线图,我们只需修改`chart.html`模板即可。 更改为:
```py
<meta charset="utf-8">
......@@ -147,7 +149,7 @@ To create a line chart, we can simply modify the chart.html template. Change it
### 创建饼图
To create a pie chart, we must modify the application code slightly. We need 3 arrays: values, labels and colors. Colors are defined in hexadecimal, as usual in HTML. To iterate them in one loop, we zip them.
要创建饼图,我们必须稍加修改应用程序代码。 我们需要 3 个数组:值,标签和颜色。 与 HTML 一样,颜色以十六进制定义。 要在一个循环中对其进行迭代,请压缩它们。
```py
from flask import Flask
......@@ -190,6 +192,8 @@ app.run(host='0.0.0.0', port=5001)
结果:
[&lt;picture&gt;&lt;source srcset="/wp-content/uploads/2015/07/flask-piechart.png.webp" type="image/webp"&gt; &lt;source srcset="/wp-content/uploads/2015/07/flask-piechart.png" type="image/jpeg"&gt; ![Flask piechart](img/54280984e9f8f3b22316893807c1a52e.jpg) &lt;/picture&gt;](https://pythonspot.com/wp-content/uploads/2015/07/flask-piechart.png) 烧瓶饼图
![Flask piechart](img/54280984e9f8f3b22316893807c1a52e.jpg)
Flask 饼图
[下载烧瓶示例](https://pythonspot.com/download-flask-examples/)
\ No newline at end of file
[下载 Flask 示例](https://pythonspot.com/download-flask-examples/)
\ No newline at end of file
......@@ -125,7 +125,7 @@ print json.dumps(d, ensure_ascii=False)
## 漂亮的打印
If you want to display JSON data you can use the json.dumps() function.
如果要显示 JSON 数据,可以使用`json.dumps()`函数。
```py
import json
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册