引言

http或者https协议是一种被广泛运用的网络传输协议,是一种应用层协议。通过该协议传输数据,一般是POST方法,有两种常用的方式

  • 使用浏览器原生的form表单,应该是最常用的方式了,一般是用户向服务器提交数据(在此之前服务器要向浏览器渲染网页)
  • 如果是单纯的提供数据,应该使用API接口。也是后台和前后的一套规范。数据的格式建议采用json,简单规范。

参考:四种常见的POST 提交数据方式

 

flask框架开发,可以使用Flask-Restful插件编写API接口,为前台/用户提供数据服务。

安装依赖:

pip install flask-restful

 

Restful API规范

参考:http://www.ruanyifeng.com/blog/2014/05/restful_api.html

 

 

测试代码

from flask import Flask
from flask_restful import Api,Resource,reqparse,fields


#目的:使用flask_restful模块,进行API接口的编写


app = Flask(__name__)

# 用Api来绑定app
api = Api(app)

#直接返回json数据
#用户使用get请求获取API接口
class IndexView(Resource):
    def get(self):
        return {"username":"hinzer"}

api.add_resource(IndexView,'/',endpoint='index')


#通过指定字段返回数据
#使用ORM模型或者自定义的模型的时候,他会自动的获取模型中的相应的字段,生成json数据,然后再返回给客户端。
# class ProfileView(Resource):
#     resource_fields = {
#         'username': fields.String,
#         'age': fields.Integer(default=18),              #默认值 18岁~~
#         # 'school': fields.String,
#         'education': fields.String(attribute='school')  #重命名属性,对外提供 education这个属性名,程序上实际是school属性
#     }
#
#     @marshal_with(resource_fields)
#     def get(self,user_id):
#         user = User.query.get(user_id)      #查询模型 User
#         return user




if __name__ == '__main__':
    app.run()

通过ORM模型对数据库进行操作,相关了解可以查看我另一篇文章  https://blog.csdn.net/feit2417/article/details/86590669

 

浏览器测试