Comments (2)
Since my project is very important for other countries to deploy this time zone, we need to unify the time zone
For example, the project in Singapore is mainly based on Singapore time, for example, in the United States, it is mainly based on US time
Here is my workaround
main.py
from datetime import datetime
from typing import List
from zoneinfo import ZoneInfo
import uvicorn
from fastapi import FastAPI, HTTPException
from motor.motor_asyncio import AsyncIOMotorClient
from odmantic import AIOEngine, Model, ObjectId, Field, EmbeddedModel
client = AsyncIOMotorClient(
f'mongodb://127.0.0.1',
)
def model_to_tz(d, tz='Asia/Shanghai'):
"""多维/嵌套字典数据无限遍历"""
data = d.dict() if isinstance(d, Model) else d
if isinstance(data, dict):
for i in range(len(data)):
temp_key = list(data.keys())[i]
temp_value = data[temp_key]
if isinstance(temp_value, datetime):
offset = temp_value.astimezone(ZoneInfo(tz)).utcoffset()
n = temp_value + offset
data.update({temp_key: n})
model_to_tz(temp_value) # 自我调用实现无限遍历
return data
def list_model_to_tz(ds, tz='Asia/Shanghai'):
res = []
for d in ds:
res.append(model_to_tz(d, tz))
return res
class Detail(EmbeddedModel):
d_at: datetime = Field(default_factory=datetime.utcnow)
class Body(EmbeddedModel):
detail: Detail = Field(default={})
b_at: datetime = Field(default_factory=datetime.utcnow)
class Tree(Model):
name: str
body: Body = Field(default={})
c_at: datetime = Field(default_factory=datetime.utcnow)
u_at: datetime = Field(default=None)
app = FastAPI()
engine = AIOEngine(client)
@app.put("/trees/", response_model=Tree)
async def create(tree: Tree):
await engine.save(tree)
return tree
@app.put("/trees/update", response_model=Tree)
async def update(tree: Tree):
t = await engine.find_one(Tree, Tree.id == tree.id)
if tree is None:
raise HTTPException(404)
t.u_at = datetime.utcnow()
await engine.save(t)
return t
@app.get("/trees/", response_model=List[Tree])
async def get_trees():
trees = await engine.find(Tree)
return list_model_to_tz(trees)
@app.get("/trees/count", response_model=int)
async def count_trees():
count = await engine.count(Tree)
return count
@app.get("/trees/{id}", response_model=Tree)
async def get_tree_by_id(id: ObjectId):
tree = await engine.find_one(Tree, Tree.id == id)
if tree is None:
raise HTTPException(404)
return tree
if __name__ == '__main__':
uvicorn.run(
app,
host="0.0.0.0",
port=3600,
log_level="info"
)
effect
from odmantic.
This project is very effective, is it dead?
from odmantic.
Related Issues (20)
- regex is removed in pydantic 2.x this causes the Field class to throw an exception if its used. HOT 1
- Support for Optional types as X | None HOT 1
- Embedded models have to be defined before any normal models that reference them HOT 4
- Question: how to mock/write propper unittests HOT 2
- when a model has many optional field, it will raise unwanted validation type error HOT 4
- Odmantic Does Not Add Pydantic Computed Fields to MongoDB HOT 2
- Aggregation support via the find method HOT 1
- Datetime not updating and not updating frequently
- Injected Context for Model Class not picked up
- Unexpected @field_validator behaviour
- ODMantic is incompatible with pydantic version 2.7.0 HOT 4
- Custom fields serialisation & deserialisation HOT 1
- Motor uses ThreadPoolExecutor, it drastically decreases a performance HOT 4
- `key_name` doesn't work when field is `id` HOT 2
- The "Custom field types" doc talks about a __bson__ method with an example that doesn't include it
- Field support exclud
- __bson__ serialization does not work when Optional / Union used with Custom Types
- Can't save a model with a field of type pydantic.AnyUrl
- Optional Embedded model and key_name not working HOT 5
- Using Model.model_construct breaks attr setters
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from odmantic.