`
rainy646556896
  • 浏览: 20506 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

Designing a RESTful API with Python and Flask

 
阅读更多

文档: http://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask

快速入门: http://www.pythondoc.com/flask/quickstart.html
 
1. 安装python2.x
2. 安装esay_install
3. 安装Flask:
   1> 打开控制台:,输入easy_install virtualenv, 安装virtualenv
   2> 配置虚拟环境: virtualenv myvir,相应路径下会多一个文件夹myvir
   3> 在myvir目录的Scripts下,输入activate.bat进入虚拟环境,然后输入esay_install Flask
   4> 控制台输入python hello.py
   5> 浏览器输入http://127.0.0.1:500访问对应的api
 
示例,hello.py文件:
from flask import Flask  
app=Flask(__name__)  
@app.route('/')  
def hello_world():  
    return "Hello World"  
if __name__ == '__main__':  
    app.run() 
 
示例,bookItems.py:
from flask import Flask, jsonify
from flask import abort
app = Flask(__name__)  

bookItems = [
    {
		"id": "1000",
		"name": "groovy",
		"price": "30",
		"author": "Jack"
	},
	{
		"id": "1001",
		"name": "java",
		"price": "32",
		"author": "Jimmy"
	},
	{
		"id": "1002",
		"name": "c#",
		"price": "32",
		"author": "Jimmy"
	},
	{
		"id": "1003",
		"name": "html",
		"price": "32",
		"author": "Jimmy"
	},
	{
		"id": "1004",
		"name": "english",
		"price": "32",
		"author": "Jimmy"
	},
	{
		"id": "1005",
		"name": "sport",
		"price": "32",
		"author": "Jimmy"
	}
]


@app.route('/api/v1/books', methods=['GET'])
def get_bookItems():
    return jsonify({'books': bookItems})

@app.route('/api/v1/books/<book_id>', methods=['GET'])
def get_book(book_id):
    book = [book for book in bookItems if book['id'] == book_id]
    if len(book) == 0:
        abort(404)
    return jsonify({'book': book[0]})

if __name__ == '__main__':  
    app.run(debug = True) 
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics