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.
44 lines
1.4 KiB
44 lines
1.4 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
|
||
|
|
||
|
def __init__(self, app: Flask):
|
||
|
self.app = app
|
||
|
|
||
|
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))
|
||
|
|
||
|
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))
|