领取🎁 Q群号: 943192807(纯技术交流和资源共享)以自助拿走。
①行业咨询、专业解答
②Python开发环境安装教程
③400集自学视频
④软件开发常用词汇
⑤最新学习路线图
⑥3000多本Python电子书
第 26 天 - 网络 Python
26.1网页版 Python
Python 是一种通用编程语言,可用于许多地方。在本节中,我们将了解如何在 Web 上使用 Python。Python 网页框架作品很多。Django 和 Flask 是最受欢迎的。今天,我们将看到如何使用 Flask 进行 Web 开发。
26.2Flask
Flask 是一个用 Python 编写的 Web 开发框架。Flask 使用 Jinja2 模板引擎。Flask 也可以与其他现代前端库一起使用,例如 React。
如果您还没有安装 virtualenv 包,请先安装它。虚拟环境将允许将项目依赖项与本地机器依赖项隔离开来。
文件夹结构
完成所有步骤后,您的项目文件结构应如下所示:
├── 配置文件
├── app.py
├──环境
│ ├── bin
├──需求.txt
├── 静态
│ └── css
│ └── main.css
└── 模板
├── about.html
├── home.html
├── layout.html
├── post.html
└── 结果.html
26.3设置你的项目目录
按照以下步骤开始使用 Flask。
步骤 1:使用以下命令安装 virtualenv。
pip 安装 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模块。
26.4创建路由
回家路线。
#让我们
从 flask 导入 flask import Flask
import os #导入操作系统模块
app = Flask ( __name__ )
@app.route('/') # 这个装饰器创建 home 路由
def home ():
return '<h1>Welcome</h1>'
@app.route('/about')
def about ():
return '<h1>About us</h1>'
如果 __name__ == '__main__' :
#部署,我们使用ENVIRON
#使之成为生产和开发工作
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。
让我们添加额外的路线。创建关于路由
#让我们
从 flask 导入 flask import Flask
import os #导入操作系统模块
app = Flask ( __name__ )
@app.route('/') # 这个装饰器创建 home 路由
def home ():
return '<h1>Welcome</h1>'
@app.route('/about')
def about ():
return '<h1>About us</h1>'
如果 __name__ == '__main__' :
#部署,我们使用ENVIRON
#使之成为生产和开发工作
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函数。
26.5创建模板
在模板文件夹中创建 HTML 文件。
主页.html
<!DOCTYPE html >
< html lang =" en " >
< head >
< meta charset =" UTF-8 " />
<元 名称="viewport" content =" width=device-width, initial-scale=1.0 " / >
< title >首页</ title >
</ head >
< body >
< h1 >Welcome Home</ h1 >
</ body >
</ html >
关于.html
<!DOCTYPE html >
< html lang =" en " >
< head >
< meta charset =" UTF-8 " />
<元 名称="viewport" content =" width=device-width, initial-scale=1.0 " / >
< title >关于</ title >
</ head >
< body >
< h1 >关于我们</ h1 >
</ body >
</ html >
26.6Python脚本
app.py
# 让我们
从 flask 导入 flask import Flask , render_template
import os # 导入操作系统模块
app = Flask ( __name__ )
@app.route('/') # 这个装饰器创建 home 路由
def home ():
return render_template ( 'home.html' )
@app.route('/about')
def about():
返回 render_template('about.html')
如果 __name__ == '__main__' :
#部署,我们使用ENVIRON
#使之成为生产和开发工作
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)
如您所见,要转到不同的页面或导航,我们需要导航。让我们为每个页面添加一个链接,或者让我们创建一个用于每个页面的布局。
26.7导航
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
现在,我们可以使用上面的链接在页面之间导航。让我们创建处理表单数据的附加页面。你可以叫它任何名字,我喜欢叫它 post.html。
我们可以使用 Jinja2 模板引擎将数据注入到 HTML 文件中。
# 让我们
从 flask 导入 flask import Flask , render_template , request , redirect , url_for
import os # 导入操作系统模块
app = Flask ( __name__ )
@app.route ( '/' ) # 这个装饰器创建 home 路由
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 )
如果 __name__ == '__main__' :
#部署
#使之成为生产和开发工作
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 " />
<元 名称="视口" content =" width=device-width, initial-scale=1.0 " / >
< title >首页</ 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 " />
<元 名称="视口" content =" width=device-width, initial-scale=1.0 " / >
< title >关于我们</ 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>
26.8创建布局
在模板文件中,有很多重复的代码,我们可以写一个布局,我们可以删除重复。让我们在模板文件夹中创建 layout.html。创建布局后,我们将导入到每个文件中。
提供静态文件
在您的项目目录中创建一个静态文件夹。在静态文件夹中创建 CSS 或样式文件夹并创建一个 CSS 样式表。我们使用url_for模块来提供静态文件。
布局.html
<!DOCTYPE html >
< html lang =" en " >
< head >
< meta charset =" UTF-8 " />
<元 名称="视口" 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 ="样式表"
/>
< link
rel ="样式表"
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>
此应用程序清理文本并分析单词、字符和
文本中出现频率最高的词。通过单击文本分析器检查它
菜单。您需要以下技术来构建此 Web 应用程序:
</ 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 >关于{{name}} </ h1 >
< p >
这是 30 天的 Python 编程挑战。如果你一直在编码
到目前为止,你太棒了。祝贺你的工作做得好!
</ p >
</ div >
{% endblock %}
后.html
{% extends 'layout.html' %} {% block content %}
< div class =" container " >
< h1 >文本分析器</ h1 >
< form action =" https://thirtydaysofpython-v1.herokuapp.com/post" method="POST">
< DIV >
< textarea的 行=” 25 “名称=”内容“的自动对焦> </ textarea的>
</ div >
<div >
< input type =" submit " class =" btn " value ="处理文本"/>
</ div >
</ form >
</ div >
{% 结束块 %}
请求方法,有不同的请求方法(GET、POST、PUT、DELETE)是常见的请求方法,它们允许我们进行 CRUD(创建、读取、更新、删除)操作。
在帖子中,我们将根据请求的类型使用 GET 和 POST 方法替代,请查看下面代码中的外观。请求方法是处理请求方法和访问表单数据的函数。应用程序
# 让我们
从 flask 导入 flask import Flask , render_template , request , redirect , url_for
import os # 导入操作系统模块
app = Flask ( __name__ )
# 停止缓存静态文件
app . 配置[ 'SEND_FILE_MAX_AGE_DEFAULT' ] = 0
@app.route ( '/' ) # 这个装饰器创建 home 路由
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():
返回 render_template('result.html')
@app.route ( '/post' , methods = [ 'GET' , 'POST' ])
def post ():
name = 'Text Analyzer'
if request。method == 'GET' :
如果request,则返回 render_template ( 'post.html' , name = name , title = name )
if request.method =='POST':
content = request.form['content']
print(content)
return redirect(url_for('result'))
如果 __name__ == '__main__' :
# 部署
#使之成为生产和开发工作
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文件,复制并使用它。让我们继续进行部署。
26.9部署
创建 Heroku 帐户
Heroku 为前端和全栈应用程序提供免费部署服务。在heroku上创建一个帐户并为您的机器安装 heroku CLI。安装heroku后写下以下命令
登录 Heroku
asabeneh@Asabeneh: ~ $ heroku 登录
heroku:按任意键打开浏览器登录或 q 退出:
让我们通过单击键盘上的任意键来查看结果。当您按键盘上的任意键时,它将打开 heroku 登录页面并单击登录页面。然后你将本地机器连接到远程 heroku 服务器。如果你连接到远程服务器,你会看到这个。
asabeneh@Asabeneh: ~ $ heroku 登录
heroku:按任意键打开浏览器登录或 q 退出:
打开浏览器到 https://cli-auth.heroku.com/auth/browser/be12987c-583a-4458-a2c2-ba2ce7f41610
登录...进行
已记录在为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 环境/静态/
app.py requirements.txt 模板/
(env) asabeneh@Asabeneh: ~ /Desktop/python_for_web$
Procfile 将具有在我们的 Heroku 上的示例中在 Web 服务器中运行应用程序的命令。
网络:python app.py
将项目推送到heroku
现在,它已准备好部署。在 heroku 上部署应用程序的步骤
- 混帐初始化
- git 添加。
- git commit -m “提交消息”
- heroku 创建“应用程序名称作为一个词”
- git push heroku master
- heroku open(启动部署的应用程序)
这个步骤后,你会得到这样一个应用程序
第 27 天 - Python 与 MongoDB
Python 是一种后端技术,它可以连接不同的数据库应用程序。它可以连接到 SQL 和 noSQL 数据库。在本节中,我们将 Python 与 MongoDB 数据库(noSQL 数据库)连接起来。
27.1MongoDB
MongoDB 是一个 NoSQL 数据库。MongoDB 将数据存储在类似 JSON 的文档中,这使 MongoDB 非常灵活和可扩展。让我们看看 SQL 和 NoSQL 数据库的不同术语。下表将区分 SQL 与 NoSQL 数据库。
SQL 与 NoSQL
在本节中,我们将重点介绍 NoSQL 数据库 MongoDB。让我们通过单击登录按钮在mongoDB上注册,然后单击下一页上的注册。
填写字段并单击继续
选择免费计划
选择最接近的空闲区域并为您的集群指定任何名称。
现在,创建了一个免费的沙箱
所有本地主机访问
添加用户和密码
创建一个 mongoDB uri 链接
选择 Python 3.6 或以上驱动
27.2获取连接字符串(MongoDB URI)
复制连接字符串链接,你会得到这样的东西
mongodb+srv://asabeneh: <密码> @30daysofpython-twxkr.mongodb.net/test ? retryWrites=true & w=majority
不要担心 url,它是将您的应用程序与 mongoDB 连接的一种方式。让我们用您用来添加用户的密码替换密码占位符。
例子:
mongodb+srv://asabeneh:123123123@30daysofpython-twxkr.mongodb.net/test ? retryWrites=true & w=majority
现在,我替换了所有内容,密码为 123123,数据库名称为三十天_python。这只是一个例子,你的密码必须比这强一点。
Python 需要一个 mongoDB 驱动程序来访问 mongoDB 数据库。我们将使用pymongo和dnspython将我们的应用程序与 mongoDB base 连接起来。在您的项目目录中安装 pymongo 和 dnspython。
pip 安装 pymongo dnspython
必须安装“dnspython”模块才能使用 mongodb+srv:// URI。dnspython 是 Python 的 DNS 工具包。它支持几乎所有的记录类型。
27.3将 Flask 应用程序连接到 MongoDB 集群
# 导入flask
from flask import Flask , render_template
import os # 导入操作系统模块
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority'
client = py . MongoClient(MONGODB_URI)
print(client.list_database_names())
print(client.list_database_names())
#部署,我们使用ENVIRON
#使之成为生产和开发工作
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)
当我们运行上面的代码时,我们得到了默认的 mongoDB 数据库。
['admin', 'local']
27.3创建数据库和集合
让我们创建一个数据库,如果 mongoDB 中的数据库和集合不存在,则会创建它。让我们创建一个数据库名称三十天_of_python和学生集合。创建数据库
db = client.name_of_databse #我们可以像这样或第二种方式创建数据库
db = client[ ' name_of_database ' ]
# 导入flask
from flask import Flask , render_template
import os # 导入操作系统模块
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority'
client = py . MongoClient ( MONGODB_URI )
# 创建数据库
db = client . 30_days_of_python
# 创建学生集合并插入文档
db.students.insert_one ({ '姓名':'Asabeneh' ,'国家':'芬兰','城市':'赫尔辛基','时代':250 })
print(client.list_database_names())
app = Flask(__name__)
if __name__ == '__main__':
#部署,我们使用ENVIRON
#使之成为生产和开发工作
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)
创建数据库后,我们还创建了一个学生集合,并使用insert_one()方法插入文档。现在,数据库三十天_of_python和学生集合已创建,文档已插入。检查您的 mongoDB 集群,您将看到数据库和集合。在集合内部,会有一个文档。
[ ['thirty_days_of_python', 'admin', 'local'] ]
如果你在 mongoDB 集群上看到这个,说明你已经成功创建了一个数据库和一个集合。
如果您在图中看到,该文档已经创建了一个长 id 作为主键。每次我们创建一个文档 mongoDB 都会为它创建一个唯一的 id。
27.4将许多文档插入到集合中
该insert_one() 方法一次插入一个项目,如果我们想在任何一次我们使用插入许多文档insert_many()方法或循环。我们可以使用 for 循环一次插入多个文档。
# 导入flask
from flask import Flask , render_template
import os # 导入操作系统模块
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority'
client = py . MongoClient ( MONGODB_URI )
学生 = [
{ 'name' : 'David' , 'country' : 'UK' , 'city' : 'London' , 'age' : 34 },
{ 'name' : 'John' , 'country' : '瑞典' , 'city' : 'Stockholm' , 'age' : 28 },
{ 'name' : 'Sami' , 'country' : 'Finland' , 'city' : 'Helsinki' , 'age' : 25 },
]
for student in students:
db.students.insert_one(student)
app = Flask(__name__)
if __name__ == '__main__':
#部署,我们使用ENVIRON
#使之成为生产和开发工作
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)
27.5MongoDB 查找
该find()方法和findOne()方法是在MongoDB中的数据库集合中找到数据常用的方法。它类似于 MySQL 数据库中的 SELECT 语句。让我们使用find_one()方法来获取数据库集合中的文档。
1.*find_one({"_id": ObjectId(“id”}):如果没有提供id,则获取第一次出现
# 导入flask
from flask import Flask , render_template
import os # 导入操作系统模块
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority'
client = py . MongoClient ( MONGODB_URI )
db = client [ 'thirty_days_of_python' ] # 访问数据库
student = db.students.find_one()
print(student)
app = Flask(__name__)
if __name__ == '__main__':
# 部署,我们使用ENVIRON
#使之成为生产和开发工作
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)
{ ' _id ':物件(' 5df68a21f106fe2d315bbc8b '),'名':' Asabeneh ','国':'赫尔辛基','城市':'赫尔辛基','年龄':250}
上面的查询返回第一个条目,但我们可以使用特定的 _id 定位特定的文档。举个例子,用David的id来获取David对象。’_id’:ObjectId(‘5df68a23f106fe2d315bbc8c’)
# 让我们
从 flask import Flask导入flask , render_template
import os #
从 bson导入操作系统模块。objectid import ObjectId # id 对象
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority'
client = pymongo . MongoClient ( MONGODB_URI )
db = client [ 'thirty_days_of_python' ] # 访问数据库
student = db.students.find_one({'_id':ObjectId('5df68a23f106fe2d315bbc8c')})
print(student)
app = Flask(__name__)
if __name__ == '__main__':
#部署,我们使用ENVIRON
#使之成为生产和开发工作
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)
{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34}
我们已经通过上面的例子看到了如何使用find_one()。让我们移动一个到find()
2.find():如果我们不传递查询对象,则返回集合中的所有出现。该对象是 pymongo.cursor 对象。
# 让我们
从 flask 导入 flask import Flask , render_template
import os # 导入操作系统模块
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority'
客户端 = pymongo。MongoClient(MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
students = db.students.find()
for student in students:
print(student)
app = Flask(__name__)
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)
{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250}
{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34}
{'_id': ObjectId('5df68a23f106fe2d315bbc8d'), 'name': 'John', 'country': 'Sweden', 'city': 'Stockholm', 'age': 28}
{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25}
我们可以通过在find({}, {}) 中传递第二个对象来指定要返回的字段。0 表示不包含,1 表示包含但我们不能混合 0 和 1,除了 _id。
# 让我们
从 flask 导入 flask import Flask , render_template
import os # 导入操作系统模块
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority'
客户端 = pymongo。MongoClient(MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
students = db.students.find({}, {"_id":0, "name": 1, "country":1}) # 0 means not include and 1 means include
for student in students:
print(student)
app = Flask(__name__)
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)
{'name': 'Asabeneh', 'country': 'Finland'}
{'name': 'David', 'country': 'UK'}
{'name': 'John', 'country': 'Sweden'}
{'name': 'Sami', 'country': 'Finland'}
27.6用查询查找
在 mongoDB 中找到一个查询对象。我们可以传递一个查询对象,我们可以过滤我们想要过滤掉的文档。
# let's import the flask
from flask import Flask, render_template
import os # importing operating system module
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority'
client = pymongo.MongoClient(MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
query = {
"country":"Finland"
}
students = db.students.find(query)
for student in students:
print(student)
app = Flask(__name__)
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)
# 导入操作系统模块
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority'
客户端 = pymongo。MongoClient ( MONGODB_URI )
db = client [ 'thirty_days_of_python' ] # 访问数据库
query = {
"country":"Finland"
}
students = db.students.find(query)
for student in students:
print(student)
app = Flask(__name__)
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)
{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250}
{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25}
使用修饰符查询
# 让我们
从 Flask 导入Flask import Flask , render_template
import os # 导入操作系统模块
import pymongo
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority'
客户端 = pymongo。MongoClient ( MONGODB_URI )
db = client['thirty_days_of_python'] # accessing the database
query = {
"city":"Helsinki"
}
students = db.students.find(query)
for student in students:
print(student)
app = Flask(__name__)
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)
{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250}
{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25}
27.7使用修饰符查找查询
# 让我们
从 Flask 导入 Flask import Flask , render_template
import os # 导入操作系统模块
import pymongo
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority'
客户端 = pymongo。MongoClient ( MONGODB_URI )
db = client['thirty_days_of_python'] # accessing the database
query = {
"country":"Finland",
"city":"Helsinki"
}
students = db.students.find(query)
for student in students:
print(student)
app = Flask(__name__)
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)
{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250}
{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25}
使用修饰符查询
# 让我们
从 Flask 导入 Flask import Flask , render_template
import os # 导入操作系统模块
import pymongo
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority'
客户端 = pymongo。MongoClient(MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
query = {"age":{"$gt":30}}
students = db.students.find(query)
for student in students:
print(student)
app = Flask(__name__)
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)
{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250}
{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34}
# 让我们
从 Flask 导入 Flask import Flask , render_template
import os # 导入操作系统模块
import pymongo
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority'
客户端 = pymongo。MongoClient(MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
query = {"age":{"$gt":30}}
students = db.students.find(query)
for student in students:
print(student)
{'_id': ObjectId('5df68a23f106fe2d315bbc8d'), 'name': 'John', 'country': 'Sweden', 'city': 'Stockholm', 'age': 28}
{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25}
27.8限制文件
我们可以使用limit()方法限制返回的文档数量。
# 让我们
从 Flask 导入 Flask import Flask , render_template
import os # 导入操作系统模块
import pymongo
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority'
client = pymongo.MongoClient(MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
db.students.find().limit(3)
27.9排序查找
默认情况下,排序按升序排列。我们可以通过添加 -1 参数将排序更改为降序。
# 让我们
从 Flask 导入 Flask import Flask , render_template
import os # 导入操作系统模块
import pymongo
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority'
客户端 = pymongo。MongoClient(MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
students = db.students.find().sort('name')
for student in students:
print(student)
students = db.students.find().sort('name',-1)
for student in students:
print(student)
students = db.students.find().sort('age')
for student in students:
print(student)
students = db.students.find().sort('age',-1)
for student in students:
print(student)
app = Flask(__name__)
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)
升序
{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250}
{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34}
{'_id': ObjectId('5df68a23f106fe2d315bbc8d'), 'name': 'John', 'country': 'Sweden', 'city': 'Stockholm', 'age': 28}
{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25}
降序排列
{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25}
{'_id': ObjectId('5df68a23f106fe2d315bbc8d'), 'name': 'John', 'country': 'Sweden', 'city': 'Stockholm', 'age': 28}
{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34}
{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250}
27.10使用查询更新
我们将使用update_one()方法来更新一项。它需要两个对象,一个是查询,第二个是新对象。第一个人 Asabeneh 的年龄非常令人难以置信。让我们更新 Asabeneh 的年龄。
# 让我们
从 Flask 导入 Flask import Flask , render_template
import os # 导入操作系统模块
import pymongo
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority'
客户端 = pymongo。MongoClient ( MONGODB_URI )
db = client [ 'thirty_days_of_python' ] # 访问数据库
query = {'age':250}
new_value = {'$set':{'age':38}}
db.students.update_one(query, new_value)
# lets check the result if the age is modified
for student in db.students.find():
print(student)
app = Flask(__name__)
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)
{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 38}
{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34}
{'_id': ObjectId('5df68a23f106fe2d315bbc8d'), 'name': 'John', 'country': 'Sweden', 'city': 'Stockholm', 'age': 28}
{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25}
当我们想一次更新许多文档时,我们使用upate_many()方法。
27.11删除文档
delete_one()方法删除一个文档。所述delete_one()需要一个查询对象参数。它只删除第一次出现。让我们从集合中删除一个约翰。
# 让我们
从 Flask 导入Flask import Flask , render_template
import os # 导入操作系统模块
import pymongo
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority'
client = pymongo.MongoClient(MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
query = {'name':'John'}
db.students.delete_one(query)
for student in db.students.find():
print(student)
# lets check the result if the age is modified
for student in db.students.find():
print(student)
app = Flask(__name__)
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)
{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 38}
{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34}
{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25}
如您所见,John 已从集合中删除。
当我们要删除很多文档时,我们使用delete_many()方法,它需要一个查询对象。如果我们将一个空的查询对象传递给delete_many({}),它将删除集合中的所有文档。
27.12删除一个集合
使用drop()方法,我们可以从数据库中删除一个集合。
# 让我们
从 Flask 导入 Flask import Flask , render_template
import os # 导入操作系统模块
import pymongo
MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority'
client = pymongo.MongoClient(MONGODB_URI)
db = client [ 'thirty_days_of_python' ] # 访问数据库
db.students.drop()
现在,我们已经从数据库中删除了学生集合。
第 28 天 - API
28.1应用程序编程接口(API)
API 代表应用程序编程接口。我们将在本节中介绍的 API 类型将是 Web API。Web API 是定义的接口,企业与使用其资产的应用程序之间通过该接口发生交互,这也是一种服务级别协议 (SLA),用于指定功能提供者并为其 API 用户公开服务路径或 URL。
在 Web 开发的上下文中,API 被定义为一组规范,例如超文本传输协议 (HTTP) 请求消息,以及响应消息结构的定义,通常采用 XML 或 JavaScript 对象表示法 (JSON ) 格式。
Web API 已经从基于简单对象访问协议 (SOAP) 的 Web 服务和面向服务的架构 (SOA) 转向更直接的表示状态传输 (REST) 样式的 Web 资源。
社交媒体服务、网络 API 允许网络社区在社区和不同平台之间共享内容和数据。
使用 API,在一个地方动态创建的内容可以发布并更新到网络上的多个位置。
例如,Twitter 的 REST API 允许开发人员访问核心 Twitter 数据,搜索 API 为开发人员提供与 Twitter 搜索和趋势数据交互的方法。
许多应用程序提供 API 端点。API 的一些示例,例如国家API、猫品种 API。
在本节中,我们将介绍一个 RESTful API,它使用 HTTP 请求方法来获取、PUT、POST 和 DELETE 数据。
28.2构建API
RESTful API 是一种应用程序接口 (API),它使用 HTTP 请求来获取、PUT、POST 和 DELETE 数据。在前面的章节中,我们学习了 python、flask 和 mongoDB。我们将利用我们获得的知识使用 Python Flask 和 mongoDB 数据库开发 RESTful API。每个具有 CRUD(创建、读取、更新、删除)操作的应用程序都有一个 API 来创建数据、获取数据、更新数据或从数据库中删除数据。
要构建 API,最好了解 HTTP 协议和 HTTP 请求和响应周期。
28.3HTTP(超文本传输协议)
HTTP 是客户端和服务器之间建立的通信协议。在这种情况下,客户端是浏览器,而服务器是您访问数据的地方。HTTP 是一种网络协议,用于传送资源,这些资源可以是万维网上的文件,无论是 HTML 文件、图像文件、查询结果、脚本还是其他文件类型。
浏览器是 HTTP 客户端,因为它将请求发送到 HTTP 服务器(Web 服务器),然后该服务器将响应发送回客户端。
28.4HTTP的结构
HTTP 使用客户端-服务器模型。HTTP 客户端打开连接并向 HTTP 服务器发送请求消息,HTTP 服务器返回响应消息,即请求的资源。当请求响应周期完成时,服务器关闭连接。
请求和响应消息的格式相似。两种消息都有
- 初始行,
- 零个或多个标题行,
- 一个空行(即 CRLF 本身),以及
- 可选的消息体(例如文件、查询数据或查询输出)。
让我们通过浏览此站点来查看请求和响应消息的示例:https : //thirtydaysofpython-v1-final.herokuapp.com/。此站点已部署在 Heroku 免费 dyno 上,由于请求量大,在几个月内可能无法运行。支持这项工作使服务器一直运行。
28.5初始请求行(状态行)
初始请求行与响应不同。请求行由三个部分组成,以空格分隔:
- 方法名称(GET、POST、HEAD)
- 请求资源的路径,
- 正在使用的 HTTP 版本。例如 GET / HTTP/1.1
GET 是最常见的 HTTP,有助于获取或读取资源,POST 是创建资源的常见请求方法。
28.6初始响应线(状态线)
初始响应行,称为状态行,也由空格分隔的三个部分组成:
- HTTP版本
- 给出请求结果的响应状态代码,以及描述状态代码的原因。状态行的示例是: HTTP/1.0 200 OK 或 HTTP/1.0 404 Not Found 注意:
最常见的状态代码是: 200 OK:请求成功,结果资源(例如文件或脚本输出)在消息正文中返回。500 服务器错误 可以在此处找到 HTTP 状态代码的完整列表。也可以在这里找到。
28.7标题字段
正如您在上面的屏幕截图中看到的,标题行提供有关请求或响应的信息,或者有关消息正文中发送的对象的信息。
GET / HTTP/1.1
Host: thirtydaysofpython-v1-final.herokuapp.com
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36
Sec-Fetch-User: ?1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: navigate
Referer: https://thirtydaysofpython-v1-final.herokuapp.com/post
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en;q=0.9,fi-FI;q=0.8,fi;q=0.7,en-CA;q=0.6,en-US;q=0.5,fr;q=0.4
28.8消息体
HTTP 消息可能在标题行之后发送了一个数据主体。在响应中,这是将请求的资源返回给客户端的地方(消息正文的最常见用途),或者如果出现错误,则可能是解释性文本。在请求中,这是将用户输入的数据或上传的文件发送到服务器的地方。
如果 HTTP 消息包含正文,则消息中通常会有描述正文的标题行。特别是,
Content-Type: 标头给出了正文中数据的 MIME 类型(text/html、application/json、text/plain、text/css、image/gif)。Content-Length: 标头给出了正文中的字节数。
28.9请求方法
GET、POST、PUT 和 DELETE 是我们将要实现 API 或 CRUD 操作应用程序的 HTTP 请求方法。
- GET:GET 方法用于使用给定的 URI 从给定的服务器检索和获取信息。使用 GET 的请求应该只检索数据,对数据没有其他影响。
- POST:POST 请求用于创建数据并将数据发送到服务器,例如使用 HTML 表单创建新帖子、文件上传等。
- PUT:用上传的内容替换目标资源的所有当前表示,我们使用它来修改或更新数据。
- DELETE:删除数据
第 29 天 - 构建 API
在本节中,我们将介绍一个 RESTful API,它使用 HTTP 请求方法来获取、PUT、POST 和 DELETE 数据。
RESTful API 是一种应用程序接口 (API),它使用 HTTP 请求来获取、PUT、POST 和 DELETE 数据。在前面的章节中,我们学习了 python、flask 和 mongoDB。我们将利用我们获得的知识使用 python flask 和 mongoDB 开发 RESTful API。每个具有 CRUD(创建、读取、更新、删除)操作的应用程序都有一个 API 来创建数据、获取数据、更新数据或从数据库中删除数据。
浏览器只能处理 get 请求。因此,我们必须有一个工具可以帮助我们处理所有请求方法(GET、POST、PUT、DELETE)。
API示例
- 国家 API:https : //restcountries.eu/rest/v2/all
- 猫品种 API:https : //api.thecatapi.com/v1/breeds
Postman是一个非常流行的 API 开发工具。所以,如果你喜欢做这个部分,你需要下载 postman。Postman 的另一种选择是Insomnia。
29.1API的结构
API 端点是一个 URL,可以帮助检索、创建、更新或删除资源。结构如下所示: 示例:https : //api.twitter.com/1.1/lists/members.json 返回指定列表的成员。仅当经过身份验证的用户拥有指定列表时,才会显示私人列表成员。公司名称的名称后跟版本,然后是 API 的用途。方法:HTTP 方法和 URL
API 使用以下 HTTP 方法进行对象操作:
GET Used for object retrieval
POST Used for object creation and object actions
PUT Used for object update
DELETE Used for object deletion
让我们构建一个 API 来收集有关 30DaysOfPython 学生的信息。我们将收集姓名、国家、城市、出生日期、技能和简历。
为了实现这个 API,我们将使用:
- 邮差
- Python
- Flask
- MongoDB
29.2使用 get 检索数据
在这一步中,让我们使用虚拟数据并将其作为 json 返回。要将其作为 json 返回,将使用 json 模块和 Response 模块。
让我们导入Flask
from flask import Flask, Response
import json
app = Flask(__name__)
@app.route('/api/v1.0/students', methods = ['GET'])
def students ():
student_list = [
{
'name':'Asabeneh',
'country':'Finland',
'city':'Helsinki',
'skills':['HTML', 'CSS','JavaScript','Python']
},
{
'name':'David',
'country':'UK',
'city':'London',
'skills':['Python','MongoDB']
},
{
'name':'John',
'country':'Sweden',
'city':'Stockholm',
'skills':['Java','C#']
}
]
return Response(json.dumps(student_list), mimetype='application/json')
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)
当您在浏览器上请求http://localhost:5000/api/v1.0/students url 时,您将得到以下信息:
当您在浏览器上请求http://localhost:5000/api/v1.0/students url 时,您将得到以下信息:
让我们将 Flask 应用程序与 MongoDB 连接并从 mongoDB 数据库中获取数据,而不是显示虚拟数据。
from flask import Flask, Response
import json
import pymongo
app = Flask(__name__)
#
MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority'
client = pymongo.MongoClient(MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
@app.route('/api/v1.0/students', methods = ['GET'])
def students ():
return Response(json.dumps(student), mimetype='application/json')
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)
通过连接Flask,我们可以从三十天_of_python 数据库中获取学生收集数据。
```python
[
{
"_id": {
"$oid": "5df68a21f106fe2d315bbc8b"
},
"name": "Asabeneh",
"country": "Finland",
"city": "Helsinki",
"age": 38
},
{
"_id": {
"$oid": "5df68a23f106fe2d315bbc8c"
},
"name": "David",
"country": "UK",
"city": "London",
"age": 34
},
{
"_id": {
"$oid": "5df68a23f106fe2d315bbc8e"
},
"name": "Sami",
"country": "Finland",
"city": "Helsinki",
"age": 25
}
]
29.3通过 id 获取文档
我们可以使用 id 访问 signle 文档,让我们使用他的 id 访问 Asabeneh。 http://localhost:5000/api/v1.0/students/5df68a21f106fe2d315bbc8b
# 让我们导入Flask
from flask import Flask, Response
import json
from bson.objectid import ObjectId
import json
from bson.json_util import dumps
import pymongo
app = Flask(__name__)
#
MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority'
client = pymongo.MongoClient(MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
@app.route('/api/v1.0/students', methods = ['GET'])
def students ():
return Response(json.dumps(student), mimetype='application/json')
@app.route('/api/v1.0/students/<id>', methods = ['GET'])
def single_student (id):
student = db.students.find({'_id':ObjectId(id)})
return Response(dumps(student), mimetype='application/json')
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)
[
{
"_id": {
"$oid": "5df68a21f106fe2d315bbc8b"
},
"name": "Asabeneh",
"country": "Finland",
"city": "Helsinki",
"age": 38
}
]
29.4使用 POST 创建数据
我们使用POST请求方式来创建数据
# 让我们导入Flask
from flask import Flask, Response
import json
from bson.objectid import ObjectId
import json
from bson.json_util import dumps
import pymongo
from datetime import datetime
app = Flask(__name__)
#
MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority'
client = pymongo.MongoClient(MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
@app.route('/api/v1.0/students', methods = ['GET'])
def students ():
return Response(json.dumps(student), mimetype='application/json')
@app.route('/api/v1.0/students/<id>', methods = ['GET'])
def single_student (id):
student = db.students.find({'_id':ObjectId(id)})
return Response(dumps(student), mimetype='application/json')
@app.route('/api/v1.0/students', methods = ['POST'])
def create_student ():
name = request.form['name']
country = request.form['country']
city = request.form['city']
skills = request.form['skills'].split(', ')
bio = request.form['bio']
birthyear = request.form['birthyear']
created_at = datetime.now()
student = {
'name': name,
'country': country,
'city': city,
'birthyear': birthyear,
'skills': skills,
'bio': bio,
'created_at': created_at
}
db.students.insert_one(student)
return ;
def update_student (id):
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)
29.4使用 PUT 更新
# 让我们导入Flask
from flask import Flask, Response
import json
from bson.objectid import ObjectId
import json
from bson.json_util import dumps
import pymongo
from datetime import datetime
app = Flask(__name__)
#
MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority'
client = pymongo.MongoClient(MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
@app.route('/api/v1.0/students', methods = ['GET'])
def students ():
return Response(json.dumps(student), mimetype='application/json')
@app.route('/api/v1.0/students/<id>', methods = ['GET'])
def single_student (id):
student = db.students.find({'_id':ObjectId(id)})
return Response(dumps(student), mimetype='application/json')
@app.route('/api/v1.0/students', methods = ['POST'])
def create_student ():
name = request.form['name']
country = request.form['country']
city = request.form['city']
skills = request.form['skills'].split(', ')
bio = request.form['bio']
birthyear = request.form['birthyear']
created_at = datetime.now()
student = {
'name': name,
'country': country,
'city': city,
'birthyear': birthyear,
'skills': skills,
'bio': bio,
'created_at': created_at
}
db.students.insert_one(student)
return
@app.route('/api/v1.0/students/<id>', methods = ['PUT']) # this decorator create the home route
def update_student (id):
query = {"_id":ObjectId(id)}
name = request.form['name']
country = request.form['country']
city = request.form['city']
skills = request.form['skills'].split(', ')
bio = request.form['bio']
birthyear = request.form['birthyear']
created_at = datetime.now()
student = {
'name': name,
'country': country,
'city': city,
'birthyear': birthyear,
'skills': skills,
'bio': bio,
'created_at': created_at
}
db.students.update_one(query, student)
# return Response(dumps({"result":"a new student has been created"}), mimetype='application/json')
return
def update_student (id):
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)
29.5使用 Delete 删除文档
# 让我们导入Flask
from flask import Flask, Response
import json
from bson.objectid import ObjectId
import json
from bson.json_util import dumps
import pymongo
from datetime import datetime
app = Flask(__name__)
#
MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority'
client = pymongo.MongoClient(MONGODB_URI)
db = client['thirty_days_of_python'] # accessing the database
@app.route('/api/v1.0/students', methods = ['GET'])
def students ():
return Response(json.dumps(student), mimetype='application/json')
@app.route('/api/v1.0/students/<id>', methods = ['GET'])
def single_student (id):
student = db.students.find({'_id':ObjectId(id)})
return Response(dumps(student), mimetype='application/json')
@app.route('/api/v1.0/students', methods = ['POST'])
def create_student ():
name = request.form['name']
country = request.form['country']
city = request.form['city']
skills = request.form['skills'].split(', ')
bio = request.form['bio']
birthyear = request.form['birthyear']
created_at = datetime.now()
student = {
'name': name,
'country': country,
'city': city,
'birthyear': birthyear,
'skills': skills,
'bio': bio,
'created_at': created_at
}
db.students.insert_one(student)
return
@app.route('/api/v1.0/students/<id>', methods = ['PUT']) # this decorator create the home route
def update_student (id):
query = {"_id":ObjectId(id)}
name = request.form['name']
country = request.form['country']
city = request.form['city']
skills = request.form['skills'].split(', ')
bio = request.form['bio']
birthyear = request.form['birthyear']
created_at = datetime.now()
student = {
'name': name,
'country': country,
'city': city,
'birthyear': birthyear,
'skills': skills,
'bio': bio,
'created_at': created_at
}
db.students.update_one(query, student)
# return Response(dumps({"result":"a new student has been created"}), mimetype='application/json')
return
@app.route('/api/v1.0/students/<id>', methods = ['PUT']) # this decorator create the home route
def update_student (id):
query = {"_id":ObjectId(id)}
name = request.form['name']
country = request.form['country']
city = request.form['city']
skills = request.form['skills'].split(', ')
bio = request.form['bio']
birthyear = request.form['birthyear']
created_at = datetime.now()
student = {
'name': name,
'country': country,
'city': city,
'birthyear': birthyear,
'skills': skills,
'bio': bio,
'created_at': created_at
}
db.students.update_one(query, student)
# return Response(dumps({"result":"a new student has been created"}), mimetype='application/json')
return ;
@app.route('/api/v1.0/students/<id>', methods = ['DELETE'])
def delete_student (id):
db.students.delete_one({"_id":ObjectId(id)})
return
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)
第 30 天-结论
🎉 恭喜! 🎉
在准备这份材料的过程中,我从中学到了很多东西,也激励我去做更多的事情。那么对于你们应该也从中学到些东西吧,能陪我坚持到最后这一天你 ,真的很优秀,恭喜你达到这个水平。挑战30天学习Python编程,有了这些基础,现在你可以去学习数据分析、机器学习或 Web 开发与爬虫,一起加油!