-
-
Save mkschulze/9c623d4e885ace6f71452dcbff8b8ab0 to your computer and use it in GitHub Desktop.
ViewModelBase
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Optional | |
import flask | |
from flask import Request | |
from app.data.users import User | |
from app.infrastructure import request_dict, cookie_auth | |
from app.services import user_service | |
class ViewModelBase: | |
def __init__(self): | |
self.request: Request = flask.request | |
self.__user: Optional[User] = None | |
self.__user_set: bool = False | |
self.request_dict = request_dict.create('') | |
self.error: Optional[str] = None | |
self.user_id: Optional[int] = cookie_auth.get_user_id_via_auth_cookie(self.request) | |
def to_dict(self): | |
data = dict(self.__dict__) | |
data['user'] = self.user | |
return data | |
@property | |
def user(self) -> Optional[User]: | |
if self.__user or self.__user_set: | |
return self.__user | |
self.__user_set = True | |
if not self.user_id: | |
return None | |
self.__user = user_service.find_user_by_id(self.user_id) | |
return self.__user |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import flask | |
from werkzeug.datastructures import MultiDict | |
class RequestDictionary(dict): | |
def __init__(self, *args, default_val=None, **kwargs): | |
self.default_val = default_val | |
super().__init__(*args, **kwargs) | |
def __getattr__(self, key): | |
return self.get(key, self.default_val) | |
def create(default_val=None, **route_args) -> RequestDictionary: | |
request = flask.request | |
# Adding this retro actively. Some folks are experiencing issues where they | |
# are getting a list rather than plain dict. I think it's from multiple | |
# entries in the multidict. This should fix it. | |
args = request.args | |
if isinstance(request.args, MultiDict): | |
args = request.args.to_dict() | |
form = request.form | |
if isinstance(request.args, MultiDict): | |
form = request.form.to_dict() | |
data = { | |
**args, # The key/value pairs in the URL query string | |
**request.headers, # Header values | |
**form, # The key/value pairs in the body, from a HTML post form | |
**route_args # And additional arguments the method access, if they want them merged. | |
} | |
return RequestDictionary(data, default_val=default_val) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment