Python3, the API interface for website building, let the front-end page display data!

Xiao Diaosi : Brother Xiaoyu, what did you do this week? I haven't updated the blog post in a week.
Xiaoyu : Well, time really flies. This week, I am busy with a big event!
Xiao Diaosi is curious: Dig grass~~ Brother Yu, take a step to talk, what can make you so busy? ?
Xiaoyu : This... Don't want to bribe me with a barbecue...
Xiao Diaosi : Let's hurry up, Brother Yu, two meals, eat and take, okay?
Xiaoyu : Hmm... Okay , let's reveal a little bit, it has something to do with silver ...
Xiao Diaosi : What, be more specific? ?
Xiaoyu : Haha, your phrase " be more specific " reminds me of an interviewer once, maybe because of limited ability, or... During the interview, I just wrote the code + annotation directly on the paper Now, goose, the interviewer said, be more specific...
Xiao Diaosi : Don’t interrupt, 3 barbecues, no more...
Xiaoyu : Well, yes, let ’s reveal a little bit about my busy schedule this week. There will be a special blog post to share the content. It is said to be very good. If you have all the skills , plus your own actual project experience , you will be able to play normally . If you encounter a very nice interviewer , P7's offer will be inseparable. Bar
Xiao Diaosi : Why add, "I met a very nice interviewer"?
Xiaoyu : Because of the concept, sometimes, no matter how strong your ability and skills are, the company is great, but you don’t agree with the interviewer , so you have to say bye~~

>>> 后期,小鱼也会针对遇到的各种面试官大佬,写一篇文章,很有趣的~  一句成语**大千世界,无奇不有**来体现!

Every time I was strayed by the small dick ribbon, I got back
to business, and then the last article "Python3, website construction and construction of Flask project, let you start the web service!
Start our task today: write an api interface to display data on the front-end page .

1. Install third-party modules

1.1 flask_restplus installation

cmd window, direct pip installation

pip install flask_restplus

1.2 werkzeug installation

cmd window, direct pip installation

pip install werkzeug == 0.16.0

Here to talk about, why install the old version, because the new version (1.0.1) is not compatible with flask,
this report will appear:

ImportError: cannot import name 'cached_property' from 'werkzeug'

2. Write api interface

2.1 Create api

This code is written in __init__.py under the apis folder

init.py

# -*- coding: utf-8 -*-
"""
@ auth : carl_DJ
@ time : 2020-9-09
"""

from flask_restplus import Api
from PaperWeb.Services import app

#创建api

api = Api(
    app,
    version='0.1.0',
    title='papers api ',
    description='论文分享网站',
    # authorizations={}  #认证
    ui = True

)

#导入papers 所有的内容,以便方便执行
from PaperWeb.Services.apis.papers import  *

2.2 Create papers

This file is mainly to write the processing logic
papers.py to create the api

# -*- coding:utf-8 -*-
"""
@ auth : carl_DJ
@ time : 2020-9-09
"""

#编写api逻辑

from flask_restplus import Resource
from PaperWeb.Services.apis import api
from flask import request
from PaperWeb.Services.models.papers import PaperModel


class PapaerParsers(object):
    #定义一个静态方法
    #静态方法的作用:不需要实例化类,就可以直接调用对应的方法
    @staticmethod
    def getpaperlist():
        #解析器
        parser =api.parser()
        #往解析器里面添加参数,required = True 表示必传项
        parser = parser.add_argument('index',type = int,help ='第几页',required = True)
        parser = parser.add_argument('count',type = int,help ='一页包含的数据',required = True)
        return  parser

#创建获取接口的列表的类
class PaperList(Resource):
    #运用装饰器,将解析器运用到get方法
    @api.expect(PapaerParsers.getpaperlist())
    def get(self):
        index = int(request.values.get('index',0))
        count = int(request.values.get('count',0))
        papers,has_next = PaperModel.get_paper(index, count)
        #字典的形式,返回给前端
        return {
    
    
            'status':200,
            'msg':'success',
            'data': papers,
            'index':index,
            'count':count,  #一页有多少个数据
            'has_next':has_next  #是否有下一页

        }


#创建搜索的类,主要对作者进行搜索

class PaperSearch(Resource):
    #获取数据
    def get(self):
    # 这部分内容,与PaperList方法内容一样,只不过是查询的对象不同,不做展开
        pass

#定义一个命名空间
ns = api.namespace('papers',description = '论文接口')

#把ns 加载到PaperList中
ns.add_resource(PaperList,'','/')
#把ns 加载到PaperSearch中
ns.add_resource(PaperSearch,'/author','/author/')

2.3 Get the contents of the papers list

We create the models folder under the Services folder, and create the PaperModel class at the same time. The purpose
is to get the data
papers.py of the database.

# -*- coding:utf-8 -*-
"""
@ auth : carl_DJ
@ time : 2020-9-09
"""

from PaperWeb.Services.libs.mysql import db

class PaperModel(object):
    #静态方法的作用:不需要实例化类,就可以直接调用对应的方法
    @staticmethod
    def get_paper(index,count):
        #获得papers列表的内容
        sql = f'''
            SELECT
                id,title,url
            FROM
                papers
            WHERE
                is_delect =0
            LIMIT{(index -1) * count},{count+1}
        
        '''
        
        result = db.query(sql)
        if not result:
            return [],0
        if len(result) ==count +1:
            result.pop()
            has_next = 1  # 是否有下一页

        else:
            has_next = 0

        return result,has_next

After writing the above code, we can directly run the main.py file
and then the perfect page is displayed~ ~
Insert picture description here
Insert picture description here

3. Summary

Up to now, except for the page style and functions, it has been almost shared.
Regarding the page style, our js really cannot be compared with the front-end bosses.
As long as the function is okay, I think it is still qualified! !
If you are still not sure about the website creation process, Xiaoyu will re-link and click in order to learn.
1. " Python3, database table design and data storage for website building!

2. " Python3, website building to build Flask project, take you to start web service! !

3. " Python3, write API interface for website building, let the front-end page display data!

Xiao Diaosi : Thank you, Brother Yu, for sharing. Then, when do you share those articles? ?
Xiaoyu : Hmm... Don't worry, it should come, it will come! !

Guess you like

Origin blog.csdn.net/wuyoudeyuer/article/details/108484390