您的位置:首页 > 其它

用flask开发个人博客(39)—— 在flask中定义Rest API

2017-01-19 17:26 204 查看

一、什么是Rest API

        Rest 是将业务逻辑从后端转移到前端的一种Web架构,它使用URL来定位Web中的资源,将资源的URL和其他一些信息封装成JSON或者XML格式,在客户端和服务端之间进行传递。它支持http协议中GET、POST、PUT、DELETE等一般方法,作为服务端,就是根据客户端的请求方法,调用实现定义好的API,通过这种方式,服务端不再关心业务逻辑,只需要指定不同功能的API供客户端调用即可。

二、flask中对Rest API的支持

        flask中对Rest API的支持其实很简单,不用我们做特别的操作,只要将试图函数的返回类型改成JSON格式即可。我们知道http协议中有内容协商机制,别如当请求谷歌的主页时,对于同一个url,如果请求的content-language等相关请求头是英文则会显示英文页面,如果是中文就会显示中文界面。类似,http请求中有一个Accept的字段,可以选择接受html响应还是JSON格式的响应,对于flask的Rest API来说,就是处理Accept为JSON的http请求,并将资源按照JSON格式返回给浏览器即可。

下面的示例代码,我们将利用Rest API创建一篇博客文章并读取该文章。

2.1 Post模型的修改

        我们需要在Post模型中增加两个函数,分别将Post对象转换成JSON格式的资源以及解析解析JSON字符串:

classPost(db.Model):
__tablename__='posts'
id=db.Column(db.Integer,primary_key=True)
body=db.Column(db.Text)
timestamp=db.Column(db.DateTime,index=True,default=datetime.utcnow)
html_body=db.Column(db.Text)

def to_json(self):
json_post={
'url':url_for('main.get_post',id=self.id,_external=True),
'body':self.body,
'html_body':self.html_body
}
Return json_post

@staticmethod
def from_json(json_post):
body=json_post.get('body')
return Post(body=body)
        我们定义了to_json成员函数,将Post相关信息转换成了JSON格式的资源字符串,这里面url表示获取这一Post对象的地址,是该Post对象的唯一标示。而我们只转换了body和html_body两个字段,因为构建JSON时不需要将模型的全部字段进行转换。

        from_json被定义成了一个静态函数,它的参数json_post是一个json格式的字符串,将来会由http请求传给我们。

2.2 增加REST API的路由映射

        REST API的路由映射方法,其实和普通的路由和视图函数映射方法大同小异,都是使用蓝本对象的route()函数。但是需要注意的是Rest API的路由后面必须加上‘/’,而且视图函数要返回JSON格式的响应,对于后者我们只需要调用jsonfy()这个python中提供的现成的将dictionary转换成JSON格式的函数即可。

        首先增加新增文章的API:

@main.route('/posts/',methods=[‘POST’])
def new_post():
post=Post.from_json(request.json)
db.session.add(post)
db.session.commit()
return jsonify(post.to_json())
        这里面我们从request的json字段中可以获取http请求的json数据,然后利用Post定义的from_json()函数解析出博客的body,并构建Post对象存入数据库,并返回该Post对象构建的JSON字符串。

        接下来,编写通过GET方法获取文章的API,分别获取所有的文章和按照id获取文章:

@main.route('/posts/',methods=['GET'])
def get_posts():
post=Post.query.all()
return jsonify({'posts':[post.to_json() for post in posts]})

@main.route('/posts/<int:id>',methods=['GET'])
def get_post(id):
post=Post.query.get_or_404(id)
returnjsonify(post.to_json())
        完成了上面的步骤之后,我们调用httpie对创建的API进行测试。

三、使用httpie测试REST API

3.1 安装httpie

pip install httpie

3.2 使用httpie测试REST API

插入一篇新文章:

hyman@hyman-VirtualBox:~/Github/flaskTs$http --json POST \
>http://127.0.0.1:5000/posts/ \
>"body=Iam a post"
HTTP/1.0 200 OK
Content-Length:109
Content-Type:application/json
Date: Thu, 19Jan 2017 08:57:51 GMT
Server:Werkzeug/0.11.15 Python/2.7.12

{
"body": "I am a post",
"html_body": "<p>I ama post</p>",
"url":"http://127.0.0.1:5000/posts/1"
}

获取所有的文章:

hyman@hyman-VirtualBox:~/Github/flaskTs$http --json GET \
>http://127.0.0.1:5000/posts/
HTTP/1.0 200 OK
Content-Length:281
Content-Type:application/json
Date: Thu, 19Jan 2017 09:09:51 GMT
Server:Werkzeug/0.11.15 Python/2.7.12

{
"posts": [
{
"body": "I am apost",
"html_body":"<p>I am a post</p>",
"url":"http://127.0.0.1:5000/posts/1"
},
{
"body": "I am a post",
"html_body":"<p>I am a post</p>",
"url":"http://127.0.0.1:5000/posts/2"
}
]
}
按照id获取一篇文章:

hyman@hyman-VirtualBox:~/Github/flaskTs$http --json GET \
>http://127.0.0.1:5000/posts/1
HTTP/1.0 200 OK
Content-Length:109
Content-Type:application/json
Date: Thu, 19Jan 2017 09:10:55 GMT
Server:Werkzeug/0.11.15 Python/2.7.12

{
"body": "I am a post",
"html_body": "<p>I ama post</p>",
"url":"http://127.0.0.1:5000/posts/1"
}

Github位置:
https://github.com/HymanLiuTS/flaskTs
克隆本项目:
Git clone Git@github.com:HymanLiuTS/flaskTs.Git
获取本文源代码:
Git checkout
FL39

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: