web中最主要的兩點 資源和表述
顧名思義 資源就是互聯網上的各種資源,可以是文字 圖片。。 表述就是一種表現手段
在web的世界中,主要是三個東西來支撐上面兩點,分別是:
url http html分別用來 顯示資源位置, 傳輸資源, 顯示資源
例如
a的瀏覽器向https://www.baidu.com發送一條http請求,這個https://www.baidu.com
就是url ,利用http協議傳輸,上面的http后面的s意味著加了一個加密層,用來保護數據不被篡改。
服務器向瀏覽器返回資源后,瀏覽器解析,生成頁面。瀏覽器生成就是所謂的表述。
http層是在計算機網絡模型的最頂層 應用層,在http連接開始之前,還有很多的工作。
從最底層物理層開始 數據通過有線或者是無線的方式來給上層提供服務,數據鏈路層保證可靠點的傳輸。
然后到了ip層,計算機通過ip地址,來知道服務器在哪一個地方,從而可以獲取數據。 但是瀏覽器發送的是一個
url,這時就要通過dns 發送一個udp包來獲取ip。獲取ip后還需要加上一個相應的端口。http的端口是80,通過ip加上
端口號形成套接字,從而能夠發送數據了。
http協議的一大特性:
無狀態性
服務器不需要關心客戶端的狀態
冪等性 多次請求和一次請求的狀態是相同的。
Rest(表現層狀態轉移)六大特性
服務器 客戶端 --有明確界限
無狀態
緩存
接口統一
系統分層
按需代碼
api設計流程
羅列語義描述符 將要表達資源寫出來
畫狀態圖 表達資源之間的聯系
調整命名 命名規范
選擇媒體類型 表達方式
寫profile 文檔
code
發布
在flask中,可以很方便的設計出api
認證:
因為 REST 架構基于 HTTP 協議,所以發送密令的最佳方式是使用 HTTP 認證,基本認證
和摘要認證都可以。在 HTTP 認證中,用戶密令包含在請求的 Authorization 首部中。
使用flask-httpauth可以很簡單實現認證
auth = HTTPBasicAuth()
@auth.verify_password 確認密碼或者token
@auth.login_required 確認用戶是否通過了認證
認證方式是將用戶名和密碼通過b64編碼,加到authorization頭中
在header中可以找到這樣一條信息 Authorization:Basic ***********
使用requests 和 base64可以直接很方便的在客戶端使用
from requests import get, post
import base64
code = base64.decode(用戶名 密碼)
header = {'Authorization':code}
get('url', headers=header)
認證完成后需要資源,可以選擇使用三方庫自動生成,也可以手動生成
手動將資源在模型類下生成為json格式的:
def to_json(self):
json_post = {
'url': url_for('api.get_post', id=self.id, _external=True),
'body': self.body,
'body_html': self.body_html,
'timestamp': self.timestamp,
'author': url_for('api.get_user', id=self.author_id,
_external=True),
'comments': url_for('api.get_post_comments', id=self.id,
_external=True)
'comment_count': self.comments.count()
}
return json_post
使用flask_restless可以很方便的生成
初始化
manager = APIManager(app, flask_sqlalchemy_db=db)
from my_app import manager
需要生成的資源
manager.create_api(Product, methods=['GET', 'POST', 'DELETE'])
manager.create_api(Category, methods=['GET', 'POST', 'DELETE'])
使用:
import requests
import json
res = requests.get('http://127.0.0.1:5000/api/category')
res.json()
{u'total_pages': 0, u'objects': [], u'num_results': 0, u'page': 1}
但是使用這樣的方法有一個不好的地方,這樣顯示的是數據庫的模型,但是用戶
并不關心數據庫是怎么樣的。要面向用戶設計
有一個更好的擴展 flask-restful
from flask_restful import Api
from flask_restful import reqparse, fields, marshal_with
api = Api(app)
這里可以自定義一個自己的基類。
method_decorators能夠執行裝飾器函數,可以不用在每個方法上都寫裝飾器。
主要是加一些訪問控制裝飾器。
這是實現:
def dispatch_request(self, *args, **kwargs):
# Taken from flask
#noinspection PyUnresolvedReferences
meth = getattr(self, request.method.lower(), None)
if meth is None and request.method == 'HEAD':
meth = getattr(self, 'get', None)
assert meth is not None, 'Unimplemented method %r' % request.method
for decorator in self.method_decorators:
meth = decorator(meth)
resp = meth(*args, **kwargs)
自定義
class Resource(restful.Resource)
version = 'v1'
method_decorators = []
required_scopes = {}
自定義自己的數據格式,fields提供了不同的方法能夠將數據庫中的數據轉化為
我們規定的格式。
class APISchema():
"""describes input and output formats for resources,
and parser deals with arguments to the api.
"""
get_fields = {
'id': fields.Integer,
'created': fields.DateTime(dt_format='iso8601')
}
def __init__(self):
self.parser = reqparse.RequestParser()
def parse_args(self):
return self.parser.parse_args()
然后就可以實現自己想顯示的格式了,例如:
class User(Resource):
schema = Schema()
model = models.User
/#marshal_with裝飾器用來將輸出的數據為我們定義的格式。
@marshal_with(schema.get_fields)
def get(self, id=None):
user = self.model.get_by_id(id)
data = {
'id': user.id,
'email': user.email,
'username': user.username,
'is_admin': user.is_admin,
'profile': user.profile,
}
return data
def post(self):
self.schema.auth_user()
return {'email':g.current_user.email}
最后添加url,api就可以使用了。
api.add_resource(User, '/v1/user', '/v1/user/<int:id>')
對于一般的應用,上面說的basic認證方式就夠了,如果網站沒有使用https的話,就需要
更安全的oauth認證。
Blog www.97up.cn