sqlalchemy-serializer-meta 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2017 Yuri Boiko
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,392 @@
1
+ Metadata-Version: 2.1
2
+ Name: sqlalchemy_serializer_meta
3
+ Version: 0.1.0
4
+ Summary: A simple serializer for SQLAlchemy models and Flask Models
5
+ Home-page: https://github.com/Wehda23/sqlalchemy_serializer_meta
6
+ Author: Waheed Khaled Elhariri
7
+ Author-email: waheedkhaled95@gmail.com
8
+ License: MIT
9
+ Keywords: sqlalchemy serializer pydantic flask
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: sqlalchemy
20
+ Requires-Dist: pydantic==2.7.4
21
+ Requires-Dist: pydantic_core==2.18.4
22
+
23
+ # Serializer Module for Flask Application
24
+
25
+ This module provides a set of serializers for your Flask application, allowing you to easily validate and serialize data. The serializers are built with flexibility and extendability in mind, providing features such as nested serialization and integration with Pydantic models.
26
+
27
+ ## Installation
28
+
29
+ To use the serializers in your project, simply include the necessary files in your application directory.
30
+
31
+ ## Usage
32
+
33
+ Can be used to Serialize SQLAlchemy Model or Flask-SQLAlchemy model.
34
+
35
+ ### Basic Usage
36
+
37
+ Here's an example of how to use the `UserRegisterSerializer` to validate and create a new user:
38
+
39
+ ```python
40
+ from your_application.serializers import UserRegisterSerializer
41
+ from your_application.models import User
42
+
43
+ data = {
44
+ "first_name": "John",
45
+ "last_name": "Doe",
46
+ "email": "john.doe@example.com",
47
+ "password": "securepassword123"
48
+ }
49
+
50
+ serializer = UserRegisterSerializer(data=data)
51
+ if serializer.is_valid():
52
+ user = serializer.save()
53
+ print("User created:", user)
54
+ else:
55
+ print("Errors:", serializer.errors)
56
+ ```
57
+
58
+ In this example your custom serializer module/package
59
+
60
+ ```py
61
+ from sqlalchemy_serializer_meta import Serializer, ModelSerializer, SerializerError
62
+ from your_application.models import User
63
+
64
+ class UserRegisterSerializer(Serializer):
65
+ class Meta:
66
+ model = User
67
+ fields = ['first_name', 'last_name', 'email', 'password']
68
+
69
+ def validate_first_name(self, value) -> str:
70
+ # Your Code
71
+ return value
72
+
73
+ class UserSerializer(ModelSerializer):
74
+ class Meta:
75
+ model = User
76
+ fields = ["first_name", "last_name", "email", "password"]
77
+
78
+ class UserLoginSerializer(Serializer):
79
+ class Meta:
80
+ model = User
81
+ fields = ['email', 'password']
82
+
83
+ def validate_email(self, email: str) -> str:
84
+ # Your Code
85
+ # Code pass
86
+ self.instance = object # User Object
87
+ return email
88
+
89
+ def validate_password(self, password: str) -> str:
90
+ # Your Code
91
+ return password
92
+
93
+ # Override serializer
94
+ def to_representation(self, instance: object) -> dict:
95
+ # Your Code
96
+ return UserSerializer(instance=instance).data
97
+ ```
98
+
99
+ ### Nested Serialization
100
+
101
+ To handle nested relationships, you can define nested serializers and use them in your main serializer.
102
+
103
+ #### Single Nested Object
104
+
105
+ When dealing with a single nested object, you do not need to specify `many=True`. Here's an example:
106
+
107
+ ```python
108
+ from your_application.serializers import UserSerializer, ShippingAddressSerializer
109
+
110
+ class UserDetailSerializer(UserSerializer):
111
+ shipping_address = ShippingAddressSerializer()
112
+
113
+ class Meta:
114
+ model = User
115
+ fields = ['id', 'first_name', 'last_name', 'email', 'shipping_address']
116
+
117
+ # Usage
118
+ user = User.query.get(1)
119
+ serializer = UserDetailSerializer(instance=user)
120
+ print(serializer.data)
121
+ ```
122
+
123
+ This will serialize the `shipping_address` field as a dictionary:
124
+
125
+ ```json
126
+ {
127
+ "id": 1,
128
+ "first_name": "John",
129
+ "last_name": "Doe",
130
+ "email": "john.doe@example.com",
131
+ "shipping_address": {
132
+ "street": "123 Main St",
133
+ "city": "Anytown",
134
+ "zipcode": "12345"
135
+ }
136
+ }
137
+ ```
138
+
139
+ #### Multiple Nested Objects
140
+
141
+ When dealing with multiple nested objects, use `many=True` to return a list of dictionaries. Here's an example:
142
+
143
+ ```python
144
+ from your_application.serializers import UserSerializer, ShippingAddressSerializer
145
+
146
+ class UserDetailSerializer(UserSerializer):
147
+ shipping_addresses = ShippingAddressSerializer(many=True)
148
+
149
+ class Meta:
150
+ model = User
151
+ fields = ['id', 'first_name', 'last_name', 'email', 'shipping_addresses']
152
+
153
+ # Usage
154
+ user = User.query.get(1)
155
+ serializer = UserDetailSerializer(instance=user)
156
+ print(serializer.data)
157
+ ```
158
+
159
+ This will serialize the `shipping_addresses` field as a list of dictionaries:
160
+
161
+ ```json
162
+ {
163
+ "id": 1,
164
+ "first_name": "John",
165
+ "last_name": "Doe",
166
+ "email": "john.doe@example.com",
167
+ "shipping_addresses": [
168
+ {
169
+ "street": "123 Main St",
170
+ "city": "Anytown",
171
+ "zipcode": "12345"
172
+ },
173
+ {
174
+ "street": "456 Elm St",
175
+ "city": "Othertown",
176
+ "zipcode": "67890"
177
+ }
178
+ ]
179
+ }
180
+ ```
181
+
182
+ ### Integration with Pydantic Models
183
+
184
+ You can also integrate Pydantic models for additional validation. Here's an example:
185
+
186
+ ```python
187
+ from your_application.serializers import UserSerializer, SerializerError
188
+ from pydantic import BaseModel, EmailStr, ValidationError
189
+
190
+ class UserPydanticModel(BaseModel):
191
+ first_name: str
192
+ last_name: str
193
+ email: EmailStr
194
+
195
+ class UserPydanticSerializer(UserSerializer):
196
+ pydantic_model = UserPydanticModel
197
+
198
+ def validate_pydantic(self, data):
199
+ try:
200
+ pydantic_instance = self.pydantic_model(**data)
201
+ return pydantic_instance.model_dump() # Dump the validated model to dictionary
202
+ except ValidationError as e:
203
+ raise SerializerError(e, "Invalid data")
204
+
205
+ # Usage
206
+ data = {
207
+ "first_name": "John",
208
+ "last_name": "Doe",
209
+ "email": "john.doe@example.com"
210
+ }
211
+
212
+ serializer = UserPydanticSerializer(data=data)
213
+ if serializer.is_valid():
214
+ print("Valid data:", serializer.validated_data)
215
+ else:
216
+ print("Errors:", serializer.errors)
217
+ ```
218
+
219
+ ### Updating Existing Instances
220
+
221
+ The `.save()` method is designed to update an instance if it already exists, rather than creating a new one. If the `instance` attribute is set, `.save()` will call the `.update()` method. If `instance` is `None`, it will call `.create()`.
222
+
223
+ Here's an example:
224
+
225
+ ```python
226
+ from your_application.serializers import UserSerializer
227
+ from your_application.models import User
228
+
229
+ # Update an existing user
230
+ user_instance = User.query.get(1)
231
+ data = {
232
+ "first_name": "Jane",
233
+ "last_name": "Doe",
234
+ "email": "jane.doe@example.com"
235
+ }
236
+
237
+ serializer = UserSerializer(instance=user_instance, data=data)
238
+ if serializer.is_valid():
239
+ user = serializer.save()
240
+ print("User updated:", user)
241
+ else:
242
+ print("Errors:", serializer.errors)
243
+ ```
244
+
245
+ ## Custom Serializers
246
+
247
+ You can create custom serializers by inheriting from `Serializer` or `ModelSerializer`. Here's an example:
248
+
249
+ ```python
250
+ from sqlalchemy_serializer_meta import ModelSerializer
251
+ from your_application.models import CustomModel
252
+
253
+ class CustomModelSerializer(ModelSerializer):
254
+ class Meta:
255
+ model = CustomModel
256
+ fields = ['id', 'name', 'description']
257
+
258
+ # Usage
259
+ instance = CustomModel.query.get(1)
260
+ serializer = CustomModelSerializer(instance=instance)
261
+ print(serializer.data)
262
+ ```
263
+
264
+ ## Serializer Validated Fields
265
+
266
+ You can customize your field validation by adding `validate_<field_name>` methods in your `Serializer class`.
267
+
268
+ Can be used in SQLAlchemy and Flask API
269
+
270
+ ```py
271
+ from sqlalchemy_serializer_meta import Serializer
272
+ from your_application.models import CustomModel
273
+ from your_application.validators import CustomValidator
274
+ from typing import Union
275
+
276
+ class CustomPydantic(BaseModel):
277
+ id: str
278
+ name: str
279
+ description: EmailStr
280
+
281
+ class CustomModelSerializer(Serializer):
282
+ # If not specified the validate_pydantic method won't be called hence no errors will occure
283
+ pydantic_model: BaseModel = CustomPydantic
284
+
285
+ class Meta:
286
+ model = CustomModel
287
+ fields = ['id', 'name', 'description']
288
+
289
+ # Custom Validation for name
290
+ def validate_name(self, value):
291
+ # This will trigger Custome made Validator or pass
292
+ CustomValidator(SerializerError).validate(value)
293
+ return value
294
+
295
+
296
+ def serialize(data: dict) -> Union[dict, list[dict]]:
297
+ # To trigger validators you have to initiate .is_valid() method
298
+ serializer = CustomModelSerializer(data=data)
299
+
300
+ try:
301
+ # Trigger validation
302
+ if serializer.is_valid():
303
+ serializer.save()
304
+ return serializer.data
305
+ # If validation did not pass custom validation Grab Errors
306
+ return serializer.errors
307
+ # if validation did not pass Pydantic Validation
308
+ except ValidationError as e: # If pydanic model not defined this error will not occure because validate_pydantic wont be called.
309
+ return e.errors()
310
+ # other unexpected or unhandled errors.
311
+ except Exception as e:
312
+ return e
313
+
314
+ serialize({'name': 'test', 'description': 'test@test.com',"id":1})
315
+ ```
316
+
317
+ ### Reusable Serializer Design with SQLAlchemy and Flask-SQLAlchemy
318
+
319
+ The design of the `CustomModelSerializer` class in our Flask application leverages the flexibility and robustness of SQLAlchemy and Flask-SQLAlchemy, allowing it to be highly reusable across different projects. This approach ensures that the main views or functions in your API can remain focused on returning data or handling errors, rather than getting bogged down in validation logic.
320
+
321
+ #### Key Features of the Design:
322
+
323
+ 1. **Modular Validation:**
324
+ - By using Pydantic for model validation, we ensure that data is consistently validated before it is processed or saved.
325
+ - Custom validation methods like `validate_name` allow for specific field-level validation rules, making the serializer adaptable to different models and requirements.
326
+
327
+ 2. **Separation of Concerns:**
328
+ - The serializer handles data validation, deserialization, and serialization, keeping these concerns separate from the view logic.
329
+ - This separation allows the view functions to focus on API response generation, improving readability and maintainability.
330
+
331
+ 3. **Custom Error Handling:**
332
+ - The design includes robust error handling, catching validation errors from Pydantic and custom validators, and other exceptions.
333
+ - This ensures that the API can provide meaningful error messages to the client, improving the user experience and making debugging easier.
334
+
335
+ 4. **Ease of Integration:**
336
+ - The `CustomModelSerializer` can be easily integrated with Flask routes, as demonstrated in the example.
337
+ - This flexibility makes it simple to reuse the serializer across different endpoints or even different projects, as long as they use SQLAlchemy and Flask-SQLAlchemy.
338
+
339
+ #### Example Usage in Flask API:
340
+
341
+ ```py
342
+ from flask import Flask, request, jsonify
343
+ from sqlalchemy_serializer_meta import Serializer
344
+ from your_application.models import CustomModel
345
+ from your_application.validators import CustomValidator
346
+ from pydantic import BaseModel, EmailStr, ValidationError
347
+ from typing import Union
348
+
349
+ class CustomPydantic(BaseModel):
350
+ id: str
351
+ name: str
352
+ description: EmailStr
353
+
354
+ class CustomModelSerializer(Serializer):
355
+ pydantic_model: BaseModel = CustomPydantic
356
+
357
+ class Meta:
358
+ model = CustomModel
359
+ fields = ['id', 'name', 'description']
360
+
361
+ def validate_name(self, value):
362
+ CustomValidator(SerializerError).validate(value)
363
+ return value
364
+
365
+ app = Flask(__name__)
366
+
367
+ @app.route('/serialize', methods=['POST'])
368
+ def serialize_data():
369
+ data = request.json
370
+ serializer = CustomModelSerializer(data=data)
371
+
372
+ try:
373
+ if serializer.is_valid():
374
+ serializer.save()
375
+ return jsonify(serializer.data), 201
376
+ return jsonify(serializer.errors), 400
377
+ except ValidationError as e:
378
+ return jsonify(e.errors()), 422
379
+ except Exception as e:
380
+ return jsonify({"error": str(e)}), 500
381
+
382
+ if __name__ == '__main__':
383
+ app.run(debug=True)
384
+ ```
385
+
386
+ #### Benefits for Different Projects:
387
+
388
+ - **Consistency:** Ensures consistent data validation across various projects, reducing the likelihood of errors and inconsistencies.
389
+ - **Reusability:** The modular design means the same serializer class can be used across different models and endpoints, minimizing duplicate code.
390
+ - **Focus on Business Logic:** By handling validation and serialization within the serializer, the main view functions can focus on business logic and API response handling, making the codebase cleaner and more maintainable.
391
+
392
+ By adopting this design, you can create scalable, maintainable, and robust APIs that leverage the power of SQLAlchemy and Flask-SQLAlchemy, ensuring that your application remains flexible and adaptable to changing requirements.