学习目的
使用flask开发一些简单的接口,调用第三方接口。后续可能会加入接入数据库取数据,对第三方接口进行封装,权限问题等等。
实例
#coding:gbk
#
from flask import Flask, jsonify
from flask import abort
from flask import make_response
import os
import json
import requests
from requests.auth import HTTPBasicAuth
app = Flask(__name__)
tasks = [
{
'id': 1,
'title': u'Buy groceries',
'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
'done': False
},
{
'id': 2,
'title': u'Learn Python',
'description': u'Need to find a good Python tutorial on the web',
'done': False
},
{
'id':3,
'title':'flask project',
'description':'test the flask api',
'done':True
}
]
@app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks})
@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
task = list(filter(lambda t: t['id'] == task_id, tasks))
if len(task) == 0:
abort(404)
return jsonify({'task': task[0]})
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error':'Not found'}),404)
@app.route('/entry/tapd',methods=['GET'])
def entry_tapd():
tapd_url = 'https://api.tapd.cn/stories?workspace_id=201148522&created=>2018-11-12~2018-11-18&status=developing' #第三方接口
#tapd_url = 'http://www.itwhy.org'
r = requests.get(url=tapd_url,auth=('username','passwd'))
return r.content
if __name__ == '__main__':
app.run(debug=True)