flask_restful 学习笔记

简介: 笔记
from flask import Flask,make_response,jsonify,request,url_for,g
from flask_restful import reqparse, abort, Api, Resource
from flask_httpauth import  HTTPBasicAuth
from flask_sqlalchemy import  SQLAlchemy
from werkzeug.security import check_password_hash,generate_password_hash
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
app = Flask(__name__)
api = Api(app)
auth=HTTPBasicAuth()
db=SQLAlchemy(app)
class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key = True)
    username = db.Column(db.String(32), index = True)
    password_hash = db.Column(db.String(128))
    def set_password(self, password):
        self.password = generate_password_hash(password)
    def check_password(self, password):
        return check_password_hash(self.password, password=password)
    @auth.verify_password
    def verify_password(username_or_token, password):#这里是接口基于令牌或者用户名和密码的验证
        user = User.verify_auth_token(username_or_token)
        if not user:
            user = User.query.filter_by(username=username_or_token).first()
            if not user or not user.verify_password(password):
                return False
        g.user = user
        return True
    def generate_auth_token(self,expiration=600):
        s=Serializer('2344asdfasdf',expires_in=expiration)
        return  s.dumps({'id':self.id})
    @staticmethod
    def verify_auth_token(token):
        s = Serializer('2344asdfasdf')
        try:
            data = s.loads(token)
        except :
            return None
        user = User.query.get(data['id'])
        return user
def abort_if_todo_doesnt_exist(todo_id):
    if todo_id not in TODOS:
        abort(404, message="Todo {} doesn't exist".format(todo_id))
parser = reqparse.RequestParser()
parser.add_argument('task', type=str)
@auth.login_required
@app.route('/todo/api/v1.0/tasks', methods=['GET'])
@auth.login_required
def get_tasks():
    return jsonify({'tasks': '111'})
TODOS = {
    'todo1': {'task': 'build an API'},
    'todo2': {'task': '?????'},
    'todo3': {'task': 'profit!'},
}
class Todo(Resource):
    decorators = [auth.login_required]
    def get(self, todo_id):
        abort_if_todo_doesnt_exist(todo_id)
        return TODOS[todo_id]
    def delete(self, todo_id):
        abort_if_todo_doesnt_exist(todo_id)
        del TODOS[todo_id]
        return '', 204
    def put(self, todo_id):
        args = parser.parse_args()
        task = {'task': args['task']}
        TODOS[todo_id] = task
        return task, 201
class TodoList(Resource):
    decorators = [auth.login_required]
    def get(self):
        return TODOS
    def post(self):
        args = parser.parse_args()
        todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
        todo_id = 'todo%i' % todo_id
        TODOS[todo_id] = {'task': args['task']}
        return TODOS[todo_id], 201
api.add_resource(TodoList, '/todos')
api.add_resource(Todo, '/todos/<todo_id>')
@auth.get_password
def get_password(username):
    if username == 'miguel':
        return 'python'
    return None
@auth.error_handler
def unauthorized():
    return make_response(jsonify({'error': 'Unauthorized access'}), 403)
@app.route('/api/users', methods = ['POST'])
def new_user():
    username = request.json.get('username')
    password = request.json.get('password')
    if username is None or password is None:
        abort(400) # missing arguments
    if User.query.filter_by(username = username).first() is not None:
        abort(400) # existing user
    user = User(username = username)
    user.hash_password(password)
    db.session.add(user)
    db.session.commit()
    return jsonify({ 'username': user.username }), 201, {'Location': url_for('get_user', id = user.id, _external = True)}
@app.route('/api/resource')
@auth.login_required
def get_resource():
    return jsonify({ 'data': 'Hello, %s!' % g.user.username })
if __name__ == '__main__':
    app.run(debug=True)
相关文章
|
20天前
|
JSON API 数据格式
构建RESTful APIs:使用Python和Flask
构建RESTful APIs:使用Python和Flask
27 1
|
4月前
|
API Python
Flask-RESTful基础示例
Flask-RESTful基础示例
|
5月前
|
JSON API 数据格式
如何使用Flask开发RESTful API
RESTful API(Representational State Transferful Application Programming Interface)是一种基于 REST 架构风格设计的 Web 服务接口,用于实现资源的增删改查(CRUD)操作。它通过使用 HTTP 协议的不同方法(如 GET、POST、PUT、DELETE)和 URL 路径来对资源进行操作,并使用不同的状态码和数据格式进行响应。
60 1
|
6月前
|
JSON 安全 API
Flask-Login与Flask-RESTful:扩展你的应用功能
【4月更文挑战第16天】本文介绍了两个实用的Flask扩展——Flask-Login和Flask-RESTful。Flask-Login提供用户认证和会话管理,简化了登录、注销和保护路由的逻辑。而Flask-RESTful则助力构建RESTful API,支持多种HTTP方法和请求解析。通过这两个扩展,开发者能轻松增强Flask应用的功能性,实现安全的用户认证和高效的API交互。
|
API Python
Python编程:flask_restful模块提供api接口
Python编程:flask_restful模块提供api接口
141 0
|
API 网络架构 Python
Flask RESTful 简明教程(1)--Flask RESTful概述
本文目录 1. 简介 2. 学习内容 3. 小结
1032 0
|
Python
Flask RESTful 简明教程(2)--安装
本文目录 1. 基础环境安装 2. 安装Flask RESTful 3. 小结
472 0
|
前端开发 API 网络架构
基于Django实现 RESTful API 之RestFramework框架1
一、首先什么是RESTful REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称,中文翻译为“表征状态转移” REST从资源的角度类审视整个网络,它将分布在网络中某个节点的资...
1838 0