【问题标题】:Generic Resource approach in python compared to PHP与 PHP 相比,python 中的通用资源方法
【发布时间】:2018-09-11 15:40:53
【问题描述】:

我是 python 新手,作为我的第一次体验,我正在使用 flask-RESTful 开发一个 REST API。

突然间,我想创建一个超类来处理最常用的 http 动词的基础知识,但我认为它比 PHP 更难。

所以目标是拥有一个实现以下功能的资源类:get()、post()、put() 和 delete()。

在 PHP 中它看起来像:

trait RESTActions
{
  public function get($id)
    {
        $m = self::MODEL;
        $model = $m::find($id);
        if (is_null($model)) {
            return $this->respond(Response::HTTP_NOT_FOUND);
        }
        return $this->respond(Response::HTTP_OK, $model);
    }
  }

class ProfessionsController extends Controller
{

  const MODEL = "App\Profession";

  use RESTActions;

}

class Profession extends Model
{

    public static $rules = [
        // Validation rules
    ];
    protected $fillable = [];
    protected $dates = [];

    // Relationships

}

此获取将适用于实现“使用 RESTActions;”的每个控制器

在 python 中,我认为这听起来像:

from flask_restful import Resource

class Resource(Resource):
    model = None

    def get(self, name):
        obj = model.get(name)
        if obj:
            return obj.json()
        return {'message': 'Not found'}, 404




from resources.resource import Resource
from models.store import StoreModel

class Store(Resource):
    model = StoreModel

    def get(self):
        super().get(name)



from db import db

class StoreModel(db.Model):
__tablename__ = 'stores'

id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))

items = db.relationship('ItemModel', lazy='dynamic')


def __init__(self, name):
    self.name = name
    self.items = None

@classmethod
def get(cls, name):
    return cls.query.filter_by(name=name).first()

有了这个我希望访问 Store.get(name) -> Resource.get(self, name) -> StoreModel.get(cls, name)

但它不是这样运行的

我可以访问 Resource.get(),但模型没有有效的类引用来调用 StoreModel.get()

我需要一种方法来引用必须在子类中给出的“ClassModel”,它允许我调用“ClassModel”方法,并且该引用可能是 StoreModel、ItemModel、AnythingModel,因为子类分别是 Store、Item、Anything .

【问题讨论】:

    标签: python flask-restful


    【解决方案1】:

    找到问题了。

    有一个地方我调用 StoreModule 而不是 StoreModel 好用!!!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-28
      • 2021-05-29
      • 2019-09-12
      • 2010-10-29
      • 1970-01-01
      • 2016-08-20
      • 1970-01-01
      相关资源
      最近更新 更多