一、說(shuō)明
????????我將把這個(gè)系列分成 3 或 4 篇文章。在本系列的最后,您將了解使用flask構(gòu)建 restful API 是多么容易。在本文中,我們將設(shè)置環(huán)境并創(chuàng)建將顯示“Hello World”的終結(jié)點(diǎn)。
????????我假設(shè)你的電腦上安裝了python 2.7和pip。我已經(jīng)在python 2.7上測(cè)試了本文中介紹的代碼,盡管在python 3.4或更高版本上可能沒問(wèn)題。
二、 安裝flask
a. Installing flask
????????Flask是python的微框架。微框架中的“微”意味著Flask旨在保持核心簡(jiǎn)單但可擴(kuò)展(http://flask.pocoo.org/docs/0.12/foreword/#what-does-micro-mean)。您可以使用以下命令安裝flask:
$ pip install Flask
b.準(zhǔn)備您的 IDE
????????實(shí)際上,您可以使用所有類型的文本編輯器來(lái)構(gòu)建python應(yīng)用程序,但是如果您使用IDE,則會(huì)容易得多。就我個(gè)人而言,我更喜歡使用jetbrains(PyCharm: the Python IDE for Professional Developers by JetBrains)的Pycharm。
c. 在flask中創(chuàng)造“你好世界”
????????首先,您需要?jiǎng)?chuàng)建項(xiàng)目文件夾,在本教程中,我將它命名為“flask_tutorial”。如果您使用的是 pycharm,您可以通過(guò)從菜單中選擇文件和新項(xiàng)目來(lái)創(chuàng)建項(xiàng)目文件夾。
之后,您可以設(shè)置項(xiàng)目位置和解釋器。無(wú)論如何,您的計(jì)算機(jī)都可以有一些python解釋器。
設(shè)置項(xiàng)目后,在pycharm上右鍵單擊您的項(xiàng)目文件夾,然后選擇新建-> Python文件并將其命名為“app.py”。
在 app.py 上寫下下面的代碼。
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == '__main__':
app.run(debug=True)
????????從終端運(yùn)行它。您可以使用命令行或從pycharm單擊位于左下角的終端選項(xiàng)卡并在下面編寫代碼。
$ python app.py
打開瀏覽器并訪問(wèn)本地主機(jī):5000。瞧,現(xiàn)在您有了第一個(gè)燒瓶應(yīng)用:)
????????好的,現(xiàn)在讓我們看一下代碼。
from flask import Flask
????????此行要求應(yīng)用程序從燒瓶包導(dǎo)入燒瓶模塊。用于創(chuàng)建 Web 應(yīng)用程序?qū)嵗臒俊?/span>
app = Flask(__name__)
????????此行創(chuàng)建 Web 應(yīng)用程序的實(shí)例。__name__是 python 中的一個(gè)特殊變量,如果模塊(python 文件)作為主程序執(zhí)行,它將等于“__main__”。
@app.route("/")
????????此行定義路由。例如,如果我們像上面一樣將路由設(shè)置為“/”,如果我們?cè)L問(wèn) localhost:5000/,代碼將被執(zhí)行。您可以將路由設(shè)置為“/hello”,如果我們?cè)L問(wèn)localhost:5000 / hello,將顯示我們的“hello world”。
def hello():
return "Hello World!"
????????這條線定義了如果我們?cè)L問(wèn)路由時(shí)將執(zhí)行的函數(shù)。
if __name__ == '__main__':
app.run(debug=True)
????????此行表示如果我們從 app.py 運(yùn)行,您的燒瓶應(yīng)用將運(yùn)行。另請(qǐng)注意,我們將參數(shù)設(shè)置為 。這將在網(wǎng)頁(yè)上打印出可能的 Python 錯(cuò)誤,幫助我們跟蹤錯(cuò)誤。debug?
true
????????好的,這就是第 1 部分的全部?jī)?nèi)容,接下來(lái)我們將嘗試使用 flask 在 SQLLite 上進(jìn)行 CRUD 操作。
三、使用flask和SQLite構(gòu)建簡(jiǎn)單的restful api
????????在本文中,我將向您展示如何使用flask和SQLite構(gòu)建簡(jiǎn)單的restful api,這些api具有從數(shù)據(jù)庫(kù)中創(chuàng)建,讀取,更新和刪除數(shù)據(jù)的功能。
3.1??安裝 flask-sqlalchemy and flask-marshmallow
????????SQLAlchemy 是 python SQL 工具包和 ORM,可為開發(fā)人員提供 SQL 的全部功能和靈活性。其中 flask-sqlalchemy 是 flask 擴(kuò)展,它添加了對(duì) SQLAlchemy 的支持到 flask 應(yīng)用程序 (Flask-SQLAlchemy — Flask-SQLAlchemy Documentation (2.x))。??????
????????另一方面,flask-marshmallow 是 Fl??ask 擴(kuò)展,用于將 Flask 與 Marshmallow(對(duì)象序列化/反序列化庫(kù))集成。在本文中,我們使用flask-marshmallow 來(lái)渲染json 響應(yīng)。
您可以使用 pip 輕松安裝 flask-sqlalchemy 和 flask-marshmallow,使用以下命令:
$ pip install flask_sqlalchemy
$ pip install flask_marshmallow
$ pip install marshmallow-sqlalchemy
3.2.準(zhǔn)備代碼
????????在名為 crud.py 的文件夾上創(chuàng)建新的flask_tutorial python文件。在 crud.py 中記下以下代碼。
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'crud.sqlite')
db = SQLAlchemy(app)
ma = Marshmallow(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
class UserSchema(ma.Schema):
class Meta:
# Fields to expose
fields = ('username', 'email')
user_schema = UserSchema()
users_schema = UserSchema(many=True)
# endpoint to create new user
@app.route("/user", methods=["POST"])
def add_user():
username = request.json['username']
email = request.json['email']
new_user = User(username, email)
db.session.add(new_user)
db.session.commit()
return jsonify(new_user)
# endpoint to show all users
@app.route("/user", methods=["GET"])
def get_user():
all_users = User.query.all()
result = users_schema.dump(all_users)
return jsonify(result.data)
# endpoint to get user detail by id
@app.route("/user/<id>", methods=["GET"])
def user_detail(id):
user = User.query.get(id)
return user_schema.jsonify(user)
# endpoint to update user
@app.route("/user/<id>", methods=["PUT"])
def user_update(id):
user = User.query.get(id)
username = request.json['username']
email = request.json['email']
user.email = email
user.username = username
db.session.commit()
return user_schema.jsonify(user)
# endpoint to delete user
@app.route("/user/<id>", methods=["DELETE"])
def user_delete(id):
user = User.query.get(id)
db.session.delete(user)
db.session.commit()
return user_schema.jsonify(user)
if __name__ == '__main__':
app.run(debug=True)
????????對(duì)于短代碼,上面的代碼將具有 5 個(gè)端點(diǎn),具有創(chuàng)建新記錄、從數(shù)據(jù)庫(kù)中獲取所有記錄、按 id 獲取記錄詳細(xì)信息、更新所選記錄和刪除所選記錄的功能。同樣在此代碼中,我們?yōu)閿?shù)據(jù)庫(kù)定義模型。
????????讓我們逐部分看一下代碼
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
????????在這一部分,我們導(dǎo)入應(yīng)用程序所需的所有模塊。我們導(dǎo)入 Flask 來(lái)創(chuàng)建 Web 應(yīng)用程序的實(shí)例,請(qǐng)求獲取請(qǐng)求數(shù)據(jù),jsonify 將 JSON 輸出轉(zhuǎn)換為具有應(yīng)用程序/json?mimetype 的對(duì)象,從 flask_sqlalchemy 到 訪問(wèn)數(shù)據(jù)庫(kù)的 SQAlchemy,以及從flask_marshmallow到序列化對(duì)象的 Marshmallow。Response
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'crud.sqlite')
????????這部分創(chuàng)建我們的 Web 應(yīng)用程序的實(shí)例并設(shè)置我們的 SQLite uri 的路徑。
db = SQLAlchemy(app)
ma = Marshmallow(app)
????????在這一部分,我們將SQLAlchemy和棉花糖綁定到我們的燒瓶應(yīng)用程序中。
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
????????導(dǎo)入 SQLAlchemy 并將其綁定到我們的燒瓶應(yīng)用程序后,我們可以聲明我們的模型。在這里,我們聲明名為 User 的模型,并用它的屬性定義它的字段。
class UserSchema(ma.Schema):
class Meta:
# Fields to expose
fields = ('username', 'email')
user_schema = UserSchema()
users_schema = UserSchema(many=True)
????????這部分定義了端點(diǎn)的響應(yīng)結(jié)構(gòu)。我們希望所有終結(jié)點(diǎn)都具有 JSON 響應(yīng)。在這里,我們定義我們的 JSON 響應(yīng)將有兩個(gè)鍵(用戶名和電子郵件)。此外,我們將user_schema定義為UserSchema的實(shí)例,user_schemas定義為UserSchema列表的實(shí)例。
# endpoint to create new user
@app.route("/user", methods=["POST"])
def add_user():
username = request.json['username']
email = request.json['email']
new_user = User(username, email)
db.session.add(new_user)
db.session.commit()
return jsonify(new_user)
????????在這一部分,我們定義端點(diǎn)以創(chuàng)建新用戶。首先,我們將路由設(shè)置為“/user”,并將HTTP方法設(shè)置為POST。設(shè)置路由和方法后,我們定義在訪問(wèn)此端點(diǎn)時(shí)將執(zhí)行的函數(shù)。在此函數(shù)中,我們首先從請(qǐng)求數(shù)據(jù)中獲取用戶名和電子郵件。之后,我們使用請(qǐng)求數(shù)據(jù)中的數(shù)據(jù)創(chuàng)建新用戶。最后,我們將新用戶添加到數(shù)據(jù)庫(kù)中,并以JSON形式顯示新用戶作為響應(yīng)。
# endpoint to show all users
@app.route("/user", methods=["GET"])
def get_user():
all_users = User.query.all()
result = users_schema.dump(all_users)
return jsonify(result.data)
????????在這一部分中,我們定義端點(diǎn)以獲取所有用戶的列表,并將結(jié)果顯示為JSON響應(yīng)。
# endpoint to get user detail by id
@app.route("/user/<id>", methods=["GET"])
def user_detail(id):
user = User.query.get(id)
return user_schema.jsonify(user)
????????就像這部分的前一部分一樣,我們定義了端點(diǎn)來(lái)獲取用戶數(shù)據(jù),但不是在這里獲取所有用戶,我們只是根據(jù) id 從一個(gè)用戶那里獲取數(shù)據(jù)。如果仔細(xì)查看路由,可以看到此終結(jié)點(diǎn)的路由上有不同的模式。像“<id>”這樣的父親是參數(shù),所以你可以用你想要的一切來(lái)改變它。這個(gè)參數(shù)應(yīng)該放在函數(shù)參數(shù)上(在本例中為?def?user_detail(id)),這樣我們就可以在函數(shù)中獲取這個(gè)參數(shù)值。
# endpoint to update user
@app.route("/user/<id>", methods=["PUT"])
def user_update(id):
user = User.query.get(id)
username = request.json['username']
email = request.json['email']
user.email = email
user.username = username
db.session.commit()
return user_schema.jsonify(user)
????????在這一部分中,我們定義端點(diǎn)以更新用戶。首先,我們調(diào)用與參數(shù)上的給定 id 相關(guān)的用戶。然后,我們使用請(qǐng)求數(shù)據(jù)中的值更新此用戶的用戶名和電子郵件值。
# endpoint to delete user
@app.route("/user/<id>", methods=["DELETE"])
def user_delete(id):
user = User.query.get(id)
db.session.delete(user)
db.session.commit()
return user_schema.jsonify(user)
????????最后,我們定義要?jiǎng)h除用戶的端點(diǎn)。首先,我們調(diào)用與參數(shù)上的給定 id 相關(guān)的用戶。然后我們刪除它。
四、 生成 SQLite 數(shù)據(jù)庫(kù)
????????在上一步中,您已經(jīng)編寫了代碼來(lái)處理SQLite的CRUD操作,但是如果您運(yùn)行此python文件并嘗試訪問(wèn)端點(diǎn)(您可以嘗試訪問(wèn)localhost:5000 /user),您將收到類似于以下內(nèi)容的錯(cuò)誤消息
操作錯(cuò)誤: (sqlite3.操作錯(cuò)誤) 沒有這樣的表: 用戶 [SQL: u'SELECT user.id AS user_id, user.username AS user_username, user.email AS user_email \nFROM user']
????????出現(xiàn)此錯(cuò)誤消息的原因是您嘗試從 SQLite 獲取數(shù)據(jù),但您還沒有 SQLite 數(shù)據(jù)庫(kù)。因此,在此步驟中,我們將在運(yùn)行應(yīng)用程序之前先生成SQLite數(shù)據(jù)庫(kù)。您可以使用以下步驟在 crud.py 中基于您的模型生成 SQLite 數(shù)據(jù)庫(kù)。
- 進(jìn)入 Python 交互式外殼
首先,您需要在終端中使用以下命令進(jìn)入python交互式shell:
$ 蟒蛇
2. 導(dǎo)入數(shù)據(jù)庫(kù)對(duì)象并生成SQLite數(shù)據(jù)庫(kù)
在 python 交互式 shell 中使用以下代碼
從原油導(dǎo)入數(shù)據(jù)庫(kù)
>>> db.create_all()>>>
crud.sqlite將在您的flask_tutorial文件夾中生成。
五、?運(yùn)行flask應(yīng)用
????????現(xiàn)在,在生成 sqlite 數(shù)據(jù)庫(kù)后,我們就可以運(yùn)行我們的燒瓶應(yīng)用程序了。從終端運(yùn)行以下命令以運(yùn)行應(yīng)用程序。
$ python crud.py
????????我們已經(jīng)準(zhǔn)備好嘗試我們的燒瓶應(yīng)用。要在我們的燒瓶應(yīng)用程序中嘗試端點(diǎn),我們可以使用 API 開發(fā)工具,例如 curl 或 postman。就我個(gè)人而言,我喜歡 api 開發(fā)的郵遞員(Postman)。在本文中,我將使用郵遞員來(lái)訪問(wèn)端點(diǎn)。
- 創(chuàng)建新用戶
2. 獲取所有用戶
3. 通過(guò) id 獲取用戶
4. 更新用戶
5. 刪除用戶
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-640660.html
六、后記
????????這就是本文的全部?jī)?nèi)容。接下來(lái),我計(jì)劃使用 pytest 編寫小型測(cè)試。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-640660.html
到了這里,關(guān)于使用 Python 和 Flask 構(gòu)建簡(jiǎn)單的 Restful API 第 1 部分的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!