Python學(xué)習(xí)筆記——0003 用Flask寫(xiě)簡(jiǎn)易API(別版)

Tag:PyCharm,Flask,flask_sqlalchemy,Flask-Restful

[TOC]

筆者使用PyCharm來(lái)進(jìn)行開(kāi)發(fā)操作。

另一篇使用的是Flask-Restless中的APIManager,本篇使用Flask-Restful中的API來(lái)實(shí)現(xiàn)。

一、在PyCharm中新建Flask項(xiàng)目

image

新建項(xiàng)目時(shí),將會(huì)聯(lián)網(wǎng)(外網(wǎng))下載并安裝flask、jinja2等。如果有錯(cuò)誤提示,請(qǐng)自行解決網(wǎng)絡(luò)問(wèn)題。

二、在PyCharm中的終端,下載所需的包

因?yàn)樾陆?xiàng)目的時(shí)候使用了Virtualenv,所以安裝相關(guān)依賴(lài),只需要在終端中,正常安裝就可以了。此時(shí)pip3安裝的包,都不是全局的,而只在當(dāng)前虛擬環(huán)境中起作用。

pip3 install flask_sqlalchemy
pip3 install flask_restful
pip3 install flask-cors
pip3 install flask-restless
pip3 install flask-httpauth
pip3 install passlib

==此處和另一篇有不同。==

本例中,使用flask_sqlalchemyFlask-Restful

pip3 install flask_sqlalchemy
pip3 install flask_restful

關(guān)于virtualenv的相關(guān)信息,可以參考:virtualenv介紹及基本使用

image

三、導(dǎo)入包

在主文件上方,導(dǎo)入相關(guān)的包。

==此處和另一篇有不同。==

import os
from flask import Flask

from flask_sqlalchemy import SQLAlchemy
from flask_restful import Api,Resource
image

四、初始配置

# 創(chuàng)建Flask應(yīng)用
app = Flask(__name__)


# 獲取項(xiàng)目的基地址
basedir = os.path.abspath(os.path.dirname(__file__))


# 格式為mysql://{用戶(hù)名}:{密碼}@{host}:{端口}/{數(shù)據(jù)庫(kù)名}
app.config['SQLALCHEMY_DATABASE_URI']='mysql://root:@172.17.0.17:3307/flaskdb'

# 或者使用SQLite項(xiàng)目文件下的SQLite數(shù)據(jù)庫(kù)。
# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'SQL/testSQL.db')

#這個(gè)提示你設(shè)為true
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']='true'

# 創(chuàng)建Flask-SQLAlchemy對(duì)象
db = SQLAlchemy(app)

這里使用SQLAlchemy來(lái)連接一個(gè)172.17.0.17上3307端口,用戶(hù)名是root,密碼為空,數(shù)據(jù)庫(kù)名是flaskdb的MariaDB數(shù)據(jù)庫(kù)。

根據(jù)官方教程, Flask中常見(jiàn)Config用法有以下幾種。

  1. 直接賦值。
  2. 通過(guò)config的update方法一次更新多個(gè)屬性值。
  3. 部分配置值可以通過(guò)屬性賦值。
  4. 通過(guò)文件讀取初始化config信息。

關(guān)于config的部分,可以參考:讀Flask源代碼學(xué)習(xí)Python--config原理,這里不多加贅述。

四、創(chuàng)建數(shù)據(jù)模型

創(chuàng)建Flask-SQLAlchemy模型(亦有成為bean的),但是要遵守下列兩點(diǎn)(合理)限制:
1.必須有一個(gè)主鍵類(lèi)型是sqlalchemy.Integer或sqlalchemy.Unicode;
2.必須有init方法,用來(lái)初始化數(shù)據(jù)(flask_sqlalchemy.SQLAlchemy.Model已經(jīng)提供)。

==此處和另一篇有不同。==

class Person(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  name = db.Column(db.Unicode, unique=True)
  birth_date = db.Column(db.Date)
  # 要將這個(gè)Bean手動(dòng)轉(zhuǎn)換為json
  def to_json(self):
      return {'id': self.id, 'name': self.name, 'birth_date': self.birth_date.strftime("%Y-%m-%d")}

class Computer(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  name = db.Column(db.Unicode, unique=True)
  vendor = db.Column(db.Unicode)
  purchase_time = db.Column(db.DateTime)
  owner_id = db.Column(db.Integer, db.ForeignKey('person.id'))
  def to_json(self):
      return {'id': self.id, 'name': self.name, 'vendor': self.vendor, 'purchase_time': self.purchase_time.strftime("%Y-%m-%d %H:%M:%S"), 'owner_id': self.owner_id}

flask-sqlalchemy中的SQLAlchemy可以用orm處理數(shù)據(jù)庫(kù),告別繁瑣的sql語(yǔ)句。文檔鏈接:http://flask-sqlalchemy.pocoo.org/2.3/

五、創(chuàng)建api

根據(jù)數(shù)據(jù)模型,創(chuàng)建對(duì)應(yīng)的api。

class personList(Resource):
    # get方法實(shí)現(xiàn)的內(nèi)容
    def get(self):
        person_list = []
        # 限制查詢(xún)10個(gè)
        persons = Person.query.limit(10).all()
        for n in persons:
            # 逐個(gè)轉(zhuǎn)化為json后添加進(jìn)數(shù)組
            person_list.append(n.to_json())
        # 完善一下json
        return {"stories":person_list}

class computerList(Resource):
    # get方法實(shí)現(xiàn)的內(nèi)容
    def get(self):
        computer_list = []
        # 限制查詢(xún)10個(gè)
        computers = Computer.query.limit(10).all()
        for n in computers:
            # 逐個(gè)轉(zhuǎn)化為json后添加進(jìn)數(shù)組
            computer_list.append(n.to_json())
        # 完善一下json
        return {"stories":computer_list}



# 查詢(xún)person的api
api.add_resource(personList,'/api/person')
# 查詢(xún)computer的api
api.add_resource(computerList,'/api/computer')

更多關(guān)于Flask-Restless的內(nèi)容,請(qǐng)查閱官方文檔,本文不在贅述。文檔鏈接:https://flask-restless.readthedocs.io/en/latest/index.html

六、主程序入口

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=6789)

在瀏覽器中輸入地址即ip加端口進(jìn)行訪(fǎng)問(wèn)驗(yàn)證:

http://127.0.0.1:6789/api/person
http://127.0.0.1:6789/api/computer
或者
http://172.17.0.38:6789/api/person
http://172.17.0.38:6789/api/computer

此時(shí)應(yīng)該得到一個(gè)json的response。

得到兩個(gè)json

{
  "stories": [
    {
      "id": 1,
      "name": "tt01",
      "vendor": "dd",
      "purchase_time": "2018-08-20 11:58:17",
      "owner_id": 1
    },
    {
      "id": 2,
      "name": "tt02",
      "vendor": "33",
      "purchase_time": "2018-08-20 11:58:21",
      "owner_id": 2
    },
    {
      "id": 3,
      "name": "tt03",
      "vendor": "22",
      "purchase_time": "2018-08-20 11:58:12",
      "owner_id": 1
    }
  ]
}
{
  "stories": [
    {
      "id": 1,
      "name": "wolf",
      "birth_date": "2018-08-20"
    },
    {
      "id": 2,
      "name": "tst",
      "birth_date": "2018-08-20"
    }
  ]
}

七、完整代碼

完整的flaskAPI.py代碼如下:

import os
from flask import Flask

from flask_sqlalchemy import SQLAlchemy
from flask_restful import Api, Resource


app = Flask(__name__)

'''
根據(jù)官方教程, Flask中常見(jiàn)Config用法有以下幾種。

    1.直接賦值。
    2.通過(guò)config的update方法一次更新多個(gè)屬性值。
    3.部分配置值可以通過(guò)屬性賦值。
    4.通過(guò)文件讀取初始化config信息。
'''
# 獲取項(xiàng)目的基地址
basedir = os.path.abspath(os.path.dirname(__file__))

# 格式為mysql://{用戶(hù)名}:{密碼}@{host}:{端口}/{數(shù)據(jù)庫(kù)名}
# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@172.17.0.17:3307/flaskdb'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'SQL/testSQL.db')

# 這個(gè)提示你設(shè)為true
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = 'true'

# 創(chuàng)建Flask-SQLAlchemy對(duì)象
db = SQLAlchemy(app)

api = Api(app)

# 像往常一樣創(chuàng)建Flask-SQLAlchemy模型,但是要遵守下列兩點(diǎn)(合理)限制:
#  1.必須有一個(gè)主鍵類(lèi)型是sqlalchemy.Integer或sqlalchemy.Unicode。
#  2.必須有__init__方法,用來(lái)初始化數(shù)據(jù)(flask.ext.sqlalchemy.SQLAlchemy.Model已經(jīng)提供)。


class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Unicode, unique=True)
    birth_date = db.Column(db.Date)

    # 要將這個(gè)Bean手動(dòng)轉(zhuǎn)換為json
    def to_json(self):
        return {'id': self.id, 'name': self.name, 'birth_date': self.birth_date.strftime("%Y-%m-%d")}

class Computer(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Unicode, unique=True)
    vendor = db.Column(db.Unicode)
    purchase_time = db.Column(db.DateTime)
    owner_id = db.Column(db.Integer, db.ForeignKey('person.id'))

    def to_json(self):
        return {'id': self.id, 'name': self.name, 'vendor': self.vendor,
                'purchase_time': self.purchase_time.strftime("%Y-%m-%d %H:%M:%S"), 'owner_id': self.owner_id}

class personList(Resource):
    # get方法實(shí)現(xiàn)的內(nèi)容
    def get(self):
        person_list = []
        # 限制查詢(xún)10個(gè)
        persons = Person.query.limit(10).all()
        for n in persons:
            # 逐個(gè)轉(zhuǎn)化為json后添加進(jìn)數(shù)組
            person_list.append(n.to_json())
        # 完善一下json
        return {"stories": person_list}


class computerList(Resource):
    # get方法實(shí)現(xiàn)的內(nèi)容
    def get(self):
        computer_list = []
        # 限制查詢(xún)10個(gè)
        computers = Computer.query.limit(10).all()
        for n in computers:
            # 逐個(gè)轉(zhuǎn)化為json后添加進(jìn)數(shù)組
            computer_list.append(n.to_json())
        # 完善一下json
        return {"stories": computer_list}


# 查詢(xún)person的api
api.add_resource(personList, '/api/person')
# 查詢(xún)computer的api
api.add_resource(computerList, '/api/computer')


@app.route('/')
def hello_world():
    return 'Hello WOLF!'


if __name__ == '__main__':
    db.create_all()
    app.run(host='0.0.0.0', port=6789)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容