You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
flask-mongorester/__init__.py

47 lines
1.6 KiB

4 years ago
from urllib.parse import urljoin
from flask import Flask
from mongoengine import Document
from restapi.views import ApiView
from restapi import Methods
class MongoApi:
app: Flask = None
authentication_methods: list = []
def __init__(self, app: Flask, authentication_methods=[]):
4 years ago
self.app = app
self.authentication_methods = authentication_methods
def register_model(self, model: any, uri: str = None, name: str = None) -> None:
if not getattr(model, '_meta').get('methods'):
raise Exception("{} model methods not set".format(model.__name__))
if not uri:
uri = model.__name__.lower()
if uri[:-1] != "/":
uri = uri + "/"
if uri[0] != "/":
uri = "/" + uri
if not name:
name = model.__name__
self.app.add_url_rule(
uri,
methods=(method.method for method in getattr(model, '_meta').get('methods') if
method not in (Methods.Get, Methods.Update)),
view_func=ApiView.as_view(name, model=model, authentication_methods=self.authentication_methods))
single = []
if Methods.Update in getattr(model, '_meta').get('methods'):
single.append('PUT')
if Methods.Get in getattr(model, '_meta').get('methods'):
single.append('GET')
if single:
self.app.add_url_rule(
urljoin(uri, '<pk>/'),
methods=single,
view_func=ApiView.as_view("{}_GET_PUT".format(name), model=model,
authentication_methods=self.authentication_methods))