标准的restful api http 请求方式有,
get:获取列表
get<int:id>: 获取单条数据记录
post:添加数据
put:修改数据
delete:删除数据
相关view处理代码
from flask import jsonify,request from app.api import api from app.models.article import Article ##分页获取所有列表 @api.route('/article/',methods=['GET']) def list(): try: page=request.args.get('page',1, type=int) page_size=request.args.get('page_size',10,type=int) query = Article.query.limit(page_size).offset((page-1)*page_size).all() result_list=[item.to_json() for item in query] return jsonify(result_list) except Exception as e: print(e) raise ##获取详细内容 @api.route('/article/<int:id>/',methods=['GET']) def get_detail(id): model=Article.query.get_or_404(id) return jsonify(model.to_json()) @api.route('/article/',methods=['POST']) def add_info(): data=request.get_json(force=True) model=Article() model.desction=data['desction'] model.title=data['title'] model.add(model) return jsonify({"msg":"添加成功"}) pass ##修改数据 @api.route('/article/',methods=['PUT']) def modify(): data = request.get_json(force=True) model = Article() model.id=data['id'] model.desction = data['desction'] model.title = data['title'] model.modify(model) return jsonify({"msg": "修改成功"}) ##删除数据 @api.route('/article/<int:id>/',methods=['DELETE']) def delete_info(id): try: model = Article.delete_by_id(id) return jsonify({"message": "删除成功"}) except Exception as e: return jsonify({"messge":str(e)})
mode里相关代码:
from app.models.base import BaseModel,db from datetime import datetime from sqlalchemy import Column,String,Integer,Text,DateTime,ForeignKey from sqlalchemy.orm import relationship ##文章类 class Article(BaseModel): __tablename__ ='article' ##数据库对应的表名 desction=Column(String(256)) title=Column(String(64),nullable=True) author=Column(String(64),default='未知作者') cover_img=Column(String(128)) source_link_url=Column(String(128)) content=Column(Text) view_count=Column(Integer,default=0) #sort_id=Column(Integer,default=99) ##relationship用户指定实体模型对应关系,这里的Category指的是实体里编写的类名,区分大小写 category=relationship('Category') ##category.id里的category指的是上句category接收的变量名,id列名 ##ForeignKey表示外键 categroy_id=Column(Integer,ForeignKey('category.id')) def __init__(self): self.addtime=datetime.now() ##添加数据 def add(self,article): try: db.session.add(article) db.session.commit() except Exception as e: db.session.rollback() print(e) raise e ##修改数据 def modify(self,article): try: data=Article.query.filter(Article.id==article.id).first() data.title=article.title data.desction=article.desction db.session.commit() except Exception as e: db.session.rollback() print(e) raise e ##删除数据 @classmethod def delete_by_id(_cls,id): db.session.query(Article).filter(Article.id==id).delete() db.session.commit()
# 将list转为dict,方便jsonify序列化 def to_json(self): dict = self.__dict__ if "_sa_instance_state" in dict: del dict["_sa_instance_state"] return dict
app_init初始化相关代码:
from app.api import api
##指定api访问前缀
app.register_blueprint(api, url_prefix='/api/v1/')
这里需要注意的是,url里区分大小写和/,如果不完全拼写拼写则有可能会提示404
运行浏览器输入http://127.0.0.1:5000/api/v1/article/访问
这里接口测试工具推荐使用postman来测试