前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Flask_RESTful之API接口编写实践记录

Flask_RESTful之API接口编写实践记录

作者头像
全栈工程师修炼指南
发布2022-09-29 19:46:14
3740
发布2022-09-29 19:46:14
举报
文章被收录于专栏:全栈工程师修炼之路

[TOC]

代码语言:javascript
复制
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from flask import Blueprint
from flask import make_response,render_template,jsonify
from flask_restful import Api,Resource

# 蓝图名称以及使用API实例化
index_blue=Blueprint('index',__name__)
api=Api(index_blue)

# 视图类资源定义
class Index(Resource):
  def get(self):
    # App\templates\index.html
    return  make_response(render_template('index.html',title="WeiyiGeek-Flask-RESTful之API接口编写实践记录",boby="这个是一个API专用URL什么都没有,想范返回数据请POST请求获取接口json数据"),200)
  def post(self):
    resp = make_response(render_template('index.json'),200)
    resp.he
    return resp
  def put(self):
    return make_response(jsonify({"code":2022, "status": "err","message":"Not found!"}),200)

class Robots(Resource):
  def get(self):
    # App\templates\robots.txt
    resp = make_response(render_template('robots.txt'),200)
    resp.headers={'context-type':'text/plain', 'Custom-Head': 'True'}
    return resp
  def post(self):
    return {"msg": "robots.txt requires get request."}, 200, {"Content-Type":"application/json"}

# 路由绑定
# 视图 Index , 路由URL为/index, 路由别名endpoint为index
api.add_resource(Index,"/",endpoint='index')
# 视图 Robots , 路由URL为/robots.txt, 路由别名endpoint为robots
api.add_resource(Robots,"/robots.txt",endpoint='robots')

执行结果如下图所示:

WeiyiGeek.flask_restful-简单示例
WeiyiGeek.flask_restful-简单示例

WeiyiGeek.flask_restful-简单示例

温馨提示: 如果指定资源类没有定义支持的请求方法, 则会在请求后显示”405 METHOD NOT ALLOWED”信息。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-04-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档