File tree 3 files changed +22
-1
lines changed
3 files changed +22
-1
lines changed Original file line number Diff line number Diff line change @@ -33,6 +33,12 @@ def _get_collection(self, model):
33
33
col = self .COLLECTIONS [model ]
34
34
return self ._db [col ]
35
35
36
+ async def create_indexes (self ):
37
+ """Create indexes for models"""
38
+ for model in self .COLLECTIONS :
39
+ col = self ._get_collection (model )
40
+ model .create_indexes (col )
41
+
36
42
async def find_all (self , model ):
37
43
"""Find all objects of a given model"""
38
44
col = self ._get_collection (model )
Original file line number Diff line number Diff line change @@ -35,6 +35,12 @@ async def pubsub_startup():
35
35
pubsub = await PubSub .create ()
36
36
37
37
38
+ @app .on_event ('startup' )
39
+ async def create_indexes ():
40
+ """Startup event handler to create database indexes"""
41
+ await db .create_indexes ()
42
+
43
+
38
44
async def get_current_user (
39
45
security_scopes : SecurityScopes ,
40
46
token : str = Depends (auth .oauth2_scheme )):
Original file line number Diff line number Diff line change @@ -86,8 +86,12 @@ class DatabaseModel(ModelId):
86
86
def update (self ):
87
87
"""Method to update model"""
88
88
89
+ @classmethod
90
+ def create_indexes (cls , collection ):
91
+ """Method to create indexes"""
92
+
89
93
90
- class User (ModelId ):
94
+ class User (DatabaseModel ):
91
95
"""API user model"""
92
96
username : str
93
97
hashed_password : str = Field (description = 'Hash of the plaintext password' )
@@ -100,6 +104,11 @@ class User(ModelId):
100
104
description = 'True if superuser otherwise False'
101
105
)
102
106
107
+ @classmethod
108
+ def create_indexes (cls , collection ):
109
+ """Create an index to bind unique constraint to username"""
110
+ collection .create_index ("username" , unique = True )
111
+
103
112
104
113
class KernelVersion (BaseModel ):
105
114
"""Linux kernel version model"""
You can’t perform that action at this time.
0 commit comments