Flask开发

python编码:

#!flask/bin/python
#cmd /k python "$(FULL_CURRENT_PATH)" & ECHO. & PAUSE & EXIT
#pip install flask-httpauth jsonify pyOpenSSL
from flask import Flask, jsonify, abort, make_response, request
from flask.ext.httpauth import HTTPBasicAuth

auth = HTTPBasicAuth()

@auth.get_password
def get_password(username):
    if username == 'ok':
        return 'python'
    return None

@auth.error_handler
def unauthorized():
    return make_response(jsonify({'error': 'Unauthorized access'}), 401)


app = Flask(__name__)

#app.run('localhost', debug=True, port=8100, ssl_context=('server.crt', 'server.key')) 
#app.run('localhost', debug=True, port=8100, ssl_context='adhoc')


@app.route('/index')
def index():
    return "Hello, World!"
    
@app.route('/')
def root():
    return "Hello, World!"
    
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
    }
]

@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)

#http://localhost:5000/todo/api/v1.0/tasks
@app.route('/todo/api/v1.0/tasks', methods=['GET'])
@auth.login_required
def get_tasks():
    return jsonify({'tasks': tasks})
    
@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['GET'])
@auth.login_required
def get_task(task_id):
    task = filter(lambda t: t['id'] == task_id, tasks)
    if len(task) == 0:
        abort(404)
    return jsonify({'task': task[0]})
    
    
#curl -i -H "Content-Type: application/json" -X POST -d '{"title":"Read a book"}'  http://localhost:5000/todo/api/v1.0/tasks
@app.route('/todo/api/v1.0/tasks', methods=['POST'])
def create_task():
    if not request.json or not 'title' in request.json:
        abort(400)
    task = {
        'id': tasks[-1]['id'] + 1,
        'title': request.json['title'],
        'description': request.json.get('description', ""),
        'done': False
    }
    tasks.append(task)
    return jsonify({'task': task}), 201
    
if __name__ == '__main__':
    app.run('localhost', debug=True, port=5000)#, ssl_context='adhoc')

 

参考:

使用python的Flask实现一个RESTful API服务器端[翻译]

http://www.cnblogs.com/vovlie/p/4178077.html

原URL:https://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask

python Flask 使用https 安全协议

http://blog.youkuaiyun.com/shenzhan168/article/details/47783651

转载于:https://my.oschina.net/sanpeterguo/blog/872350

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值