Flash develops restful api

Keywords: Python Session Database

The standard restful api http request methods are as follows:,

Get: get list

Get < int: ID >: get a single data record

post: add data

put: modify data

Delete: delete data

Related view processing code

from flask import jsonify,request
from app.api import api
from app.models.article import Article
##Page to get all lists
@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

##Get details
@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":"Add success"})
    pass




##Modifying data
@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": "Modified success"})

##Delete data
@api.route('/article/<int:id>/',methods=['DELETE'])
def delete_info(id):
    try:
        model = Article.delete_by_id(id)
        return jsonify({"message": "Delete successful"})
    except Exception as e:
        return jsonify({"messge":str(e)})

 

Relevant codes in 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
##Article category
class Article(BaseModel):

    __tablename__ ='article' ##Table name corresponding to database
    desction=Column(String(256))
    title=Column(String(64),nullable=True)
    author=Column(String(64),default='Unknown author')
    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 the user specifies the corresponding relationship of entity model. Category here refers to the class name written in the entity, which is case sensitive
    category=relationship('Category')
    ##Category in category.id refers to the variable name and ID column name received by category in the previous sentence
    ##ForeignKey means foreign key
    categroy_id=Column(Integer,ForeignKey('category.id'))


    def __init__(self):
        self.addtime=datetime.now()
    ##Add data
    def add(self,article):
        try:
            db.session.add(article)
            db.session.commit()
        except Exception as e:

            db.session.rollback()
            print(e)
            raise e

    ##Modifying data    
    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

    
    ##Delete data
    @classmethod
    def delete_by_id(_cls,id):
        db.session.query(Article).filter(Article.id==id).delete()
        db.session.commit()

# take list Turn to dict,convenient jsonify serialize def to_json(self): dict = self.__dict__ if "_sa_instance_state" in dict: del dict["_sa_instance_state"] return dict

 

App init initialization related code:

from app.api import api
##Specify api access prefix
app.register_blueprint(api, url_prefix='/api/v1/')

It should be noted that the url is case sensitive and /, and may prompt 404 if it is not spelled completely

Run the browser and input http://127.0.0.1:5000/api/v1/article/ to access

Here, the interface testing tool recommends using postman to test

Posted by Jas on Fri, 01 Nov 2019 19:11:44 -0700