or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

bulk-operations.mdcustom-types.mddocuments.mdevents-actions.mdfields-types.mdindex.mdinitialization.mdmigrations.mdquery-operations.mdtime-series.md

initialization.mddocs/

0

# Initialization

1

2

Database and ODM initialization functionality that establishes connections, registers document models, creates indexes, and configures the Beanie ODM for use in applications.

3

4

## Capabilities

5

6

### Database Initialization

7

8

The primary function for initializing Beanie with database connections and document model registration.

9

10

```python { .api }

11

async def init_beanie(

12

database: Optional[Any] = None,

13

document_models: List[Union[Type[Document], Type[View], str, Dict]] = None,

14

connection_string: Optional[str] = None,

15

allow_index_dropping: bool = False,

16

recreate_views: bool = False,

17

skip_indexes: bool = False,

18

multiprocessing_mode: bool = False

19

) -> None:

20

"""

21

Initialize Beanie ODM with database connection and document models.

22

23

Args:

24

database: Motor database instance or database name

25

document_models: List of document classes to register

26

connection_string: MongoDB connection string (alternative to database)

27

allow_index_dropping: Allow dropping indexes during initialization

28

recreate_views: Recreate views if they already exist

29

skip_indexes: Skip index creation during initialization

30

multiprocessing_mode: Enable multiprocessing compatibility mode

31

32

Raises:

33

ConfigurationError: If configuration is invalid

34

ConnectionError: If database connection fails

35

"""

36

```

37

38

#### Usage Examples

39

40

```python

41

import asyncio

42

from beanie import Document, View, init_beanie

43

from motor.motor_asyncio import AsyncIOMotorClient

44

45

# Define document models

46

class User(Document):

47

name: str

48

email: str

49

50

class Settings:

51

collection = "users"

52

53

class Post(Document):

54

title: str

55

content: str

56

author_id: str

57

58

class Settings:

59

collection = "posts"

60

61

class UserStatsView(View):

62

user_id: str

63

post_count: int

64

65

class Settings:

66

source = Post

67

pipeline = [

68

{"$group": {"_id": "$author_id", "post_count": {"$sum": 1}}},

69

{"$project": {"user_id": "$_id", "post_count": 1, "_id": 0}}

70

]

71

72

# Method 1: Using Motor client and database

73

async def init_with_client():

74

client = AsyncIOMotorClient("mongodb://localhost:27017")

75

database = client.myapp

76

77

await init_beanie(

78

database=database,

79

document_models=[User, Post, UserStatsView]

80

)

81

82

# Method 2: Using connection string

83

async def init_with_connection_string():

84

await init_beanie(

85

connection_string="mongodb://localhost:27017/myapp",

86

document_models=[User, Post, UserStatsView]

87

)

88

89

# Method 3: With additional options

90

async def init_with_options():

91

client = AsyncIOMotorClient("mongodb://localhost:27017")

92

database = client.myapp

93

94

await init_beanie(

95

database=database,

96

document_models=[User, Post, UserStatsView],

97

allow_index_dropping=True, # Allow index modifications

98

recreate_views=True, # Recreate views if they exist

99

skip_indexes=False # Create indexes (default)

100

)

101

102

# Method 4: Using string references (for avoiding circular imports)

103

async def init_with_string_refs():

104

await init_beanie(

105

connection_string="mongodb://localhost:27017/myapp",

106

document_models=[

107

"myapp.models.User",

108

"myapp.models.Post",

109

"myapp.views.UserStatsView"

110

]

111

)

112

113

# Method 5: Mixed configuration with model dictionaries

114

async def init_with_mixed_config():

115

await init_beanie(

116

connection_string="mongodb://localhost:27017/myapp",

117

document_models=[

118

User, # Direct class reference

119

"myapp.models.Post", # String reference

120

{ # Dictionary configuration

121

"model": UserStatsView,

122

"recreate": True

123

}

124

]

125

)

126

```

127

128

#### Production Setup Examples

129

130

```python

131

import os

132

from beanie import init_beanie

133

from motor.motor_asyncio import AsyncIOMotorClient

134

135

# Environment-based configuration

136

async def init_production():

137

# Read from environment variables

138

mongodb_url = os.getenv("MONGODB_URL", "mongodb://localhost:27017")

139

database_name = os.getenv("DATABASE_NAME", "production")

140

141

# Configure client with production settings

142

client = AsyncIOMotorClient(

143

mongodb_url,

144

maxPoolSize=50,

145

minPoolSize=10,

146

maxIdleTimeMS=30000,

147

serverSelectionTimeoutMS=5000,

148

connectTimeoutMS=10000,

149

socketTimeoutMS=20000

150

)

151

152

database = client[database_name]

153

154

# Import all models

155

from myapp.models import User, Post, Comment, Category

156

from myapp.views import PostStatsView, UserActivityView

157

158

await init_beanie(

159

database=database,

160

document_models=[

161

User, Post, Comment, Category,

162

PostStatsView, UserActivityView

163

],

164

allow_index_dropping=False, # Prevent accidental index drops

165

recreate_views=False, # Don't recreate existing views

166

skip_indexes=False # Ensure indexes are created

167

)

168

169

# FastAPI integration

170

from fastapi import FastAPI

171

172

app = FastAPI()

173

174

@app.on_event("startup")

175

async def startup_event():

176

await init_production()

177

178

@app.on_event("shutdown")

179

async def shutdown_event():

180

# Close database connections

181

client = AsyncIOMotorClient.get_default_client()

182

if client:

183

client.close()

184

```

185

186

#### Error Handling

187

188

```python

189

from beanie import init_beanie

190

from beanie.exceptions import ConfigurationError

191

from pymongo.errors import ConnectionFailure, ServerSelectionTimeoutError

192

193

async def safe_init():

194

try:

195

await init_beanie(

196

connection_string="mongodb://localhost:27017/myapp",

197

document_models=[User, Post]

198

)

199

print("Beanie initialized successfully")

200

201

except ConfigurationError as e:

202

print(f"Configuration error: {e}")

203

# Handle invalid model configuration

204

205

except ConnectionFailure as e:

206

print(f"Database connection failed: {e}")

207

# Handle connection issues

208

209

except ServerSelectionTimeoutError as e:

210

print(f"Server selection timeout: {e}")

211

# Handle timeout issues

212

213

except Exception as e:

214

print(f"Unexpected error during initialization: {e}")

215

# Handle other errors

216

```

217

218

#### Advanced Configuration

219

220

```python

221

# Custom initialization with advanced features

222

async def init_advanced():

223

from motor.motor_asyncio import AsyncIOMotorClient

224

225

# Configure client with SSL and authentication

226

client = AsyncIOMotorClient(

227

"mongodb://username:password@cluster.mongodb.net/",

228

tls=True,

229

tlsCAFile="ca-cert.pem",

230

tlsCertificateKeyFile="client-cert.pem",

231

authSource="admin",

232

replicaSet="myReplicaSet"

233

)

234

235

database = client.production

236

237

# Initialize with multiprocessing support

238

await init_beanie(

239

database=database,

240

document_models=[User, Post, Comment],

241

multiprocessing_mode=True, # Enable for multiprocessing apps

242

allow_index_dropping=True, # Allow index management

243

recreate_views=True # Refresh views on startup

244

)

245

246

# Testing setup with in-memory database

247

async def init_testing():

248

from mongomock_motor import AsyncMongoMockClient

249

250

# Use mock client for testing

251

client = AsyncMongoMockClient()

252

database = client.test_db

253

254

await init_beanie(

255

database=database,

256

document_models=[User, Post],

257

skip_indexes=True # Skip index creation in tests

258

)

259

```

260

261

## Types

262

263

```python { .api }

264

from typing import Optional, List, Union, Dict, Any, Type

265

from motor.motor_asyncio import AsyncIOMotorDatabase

266

267

# Document model types

268

DocumentModel = Union[Type[Document], Type[View], str, Dict[str, Any]]

269

DocumentModels = List[DocumentModel]

270

271

# Database connection types

272

DatabaseType = Union[AsyncIOMotorDatabase, str]

273

ConnectionString = str

274

275

# Configuration options

276

InitOptions = Dict[str, Any]

277

```