Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

new versions of datamodel and asyncdb #337

Merged
merged 3 commits into from
Feb 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 65 additions & 4 deletions examples/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class Country(Model):
country: str

class Airport(Model):
iata: str = Column(primary_key=True, required=True, label='IATA Code')
iata: str = Column(primary_key=True, required=True, label='IATA Code', default='AEP')
airport: str = Column(required=True, label="Airport Name")
airport_type: AirportType = Column(
required=True,
Expand All @@ -38,17 +38,23 @@ class Airport(Model):
default=AirportType.CITY
)
city: str
country: str
country: str # = Column(foreign_key=Country.country)
created_by: int
created_at: datetime = Column(default=datetime.now(), repr=False)

def __post_init__(self):
return super().__post_init__()

def geography(self):
return self.city, self.country

class Meta:
name: str = 'airports'
schema = 'public'
strict = True


app = Application()
app = Application(enable_jinja2=True)
session = AuthHandler()
session.setup(app)

Expand All @@ -62,6 +68,60 @@ class AirportHandler(ModelView):
pk: Union[str, list] = ['iata']
dsn: str = dsn

async def _pre_get(self, *args, **kwargs):
print(' REQUEST ', self.request)
app = self.request.app
session = self.request.get('session')
print('SESSION ', session)
print('APP ', app)
db = app['database']
async with await db.acquire() as conn:
query = "SELECT * FROM public.airports"
result, _ = await conn.query(query)
print(result)
template = app['template']
auth = app['auth']
return True

async def _get_data(self, queryparams, args):
data = await super()._get_data(queryparams, args)
async with await self.handler(request=self.request) as conn:
# Country.Meta.connection = conn
# country = await Country.get(country=data.country)
# print(country)
query = f"SELECT * FROM public.airports WHERE iata = '{queryparams.get('iata')}'"
result, _ = await conn.queryrow(query)
if result:
print(result)
print('DATA > ', data)
print('QS ', queryparams)
return data

async def _put_response(self, result, status = 200, fields = None):
return await super()._put_response(result, status, fields)

async def _get_callback(self, response: web.Response, result, *args, **kwargs):
await asyncio.sleep(3)
print('GET CALLBACK', result)
return response

async def _post_callback(self, response: web.Response, result, *args, **kwargs):
print('POST CALLBACK', result)
return response

async def _put_callback(self, response: web.Response, result, *args, **kwargs):
print('PUT CALLBACK', result)
return response

async def _patch_callback(self, response: web.Response, result, *args, **kwargs):
print('PATCH CALLBACK', result)
return response



def required_by_put(self, *args, **kwargs):
return True

async def _set_created_by(self, value, column, **kwargs):
return await self.get_userid(session=self._session)

Expand Down Expand Up @@ -133,7 +193,7 @@ async def start_example(db):
},
]
await Airport.create(data)
await db.release(conn)
# await db.release(conn)


async def end_example(db):
Expand Down Expand Up @@ -166,6 +226,7 @@ async def end_example(db):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
pool = AsyncPool("pg", params=params, loop=loop, **kwargs)
app['database'] = pool
loop.run_until_complete(
start_example(pool)
)
Expand Down
2 changes: 1 addition & 1 deletion navigator/navigator.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from aiohttp.abc import AbstractView
from aiohttp.web_exceptions import HTTPError
import sockjs
from datamodel.parsers.json import json_encoder

try:
from navconfig import config
Expand Down Expand Up @@ -43,7 +44,6 @@

# websocket resources
from .resources import WebSocketHandler
from .libs.json import json_encoder
from .types import WebApp


Expand Down
6 changes: 3 additions & 3 deletions navigator/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
HTTPNoContent,
)
from aiohttp_sse import sse_response, EventSourceResponse
from .libs.json import json_encoder
from datamodel.parsers.json import json_encoder


__all__ = (
Expand All @@ -38,9 +38,9 @@ def Response(
if headers:
response["headers"] = headers
if content and isinstance(content, str) or text is not None:
response["text"] = content if content else text
response["text"] = content or text
else:
response["body"] = content if content else body
response["body"] = content or body
return web.Response(**response)


Expand Down
2 changes: 1 addition & 1 deletion navigator/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
__description__ = (
"Navigator Web Framework based on aiohttp, " "with batteries included."
)
__version__ = "2.12.12"
__version__ = "2.12.13"
__copyright__ = "Copyright (c) 2020-2024 Jesus Lara"
__author__ = "Jesus Lara"
__author_email__ = "[email protected]"
Expand Down
5 changes: 4 additions & 1 deletion navigator/views/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -514,7 +514,10 @@ async def _get_meta_info(self, meta: str, fields: list):
for _, field in self.model.get_columns().items():
key = field.name
_type = field.db_type()
_t = JSON_TYPES[field.type]
try:
_t = JSON_TYPES[field.type]
except KeyError:
_t = str(field.db_type())
default = None
if field.default is not None:
default = f"{field.default!r}"
Expand Down
1 change: 1 addition & 0 deletions navigator/views/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
# Monkey-patching
DEFAULT_JSON_ENCODER = json_encoder
DEFAULT_JSON_DECODER = json_decoder

# monkey-patch the JSON encoder
aiohttp.typedefs.DEFAULT_JSON_ENCODER = json_encoder
aiohttp.typedefs.DEFAULT_JSON_DECODER = json_decoder
Expand Down
Loading