Python + Flask REST API, how to convert data keys between camelcase and snakecase?

2024/10/10 0:28:58

I am learning Python, and coding simple REST API using Flask micro-framework.

I am using SQLAlchemy for Object-relational-mapping and Marshmallow for Object-serialization/deserialization.

I am using snakecase for my variable names(according to PEP8).

I need to convert JSON object keys from camelcase to snakecase when receiving data from front-end(Angular) and vice versa, when returning response data.

What is the best approach to do this using Flask ?

I was unable to find a good answer on the internet.

Answer

You don't convert your keys, because you don't need to. Data is not code, the keys in JSON are not variables. They are not subject to PEP8 and you don't convert them.

If you have a convention for your JSON object keys, stick to it everywhere, in your front end and back end. Then use the Marshmallow 3.x data_key argument for a field to set the key name in the JSON document when loading and dumping.

E.g.

class UserSchema(Schema):first_name = fields.String(data_key="firstName")last_name = fields.Email(data_key='lastName')

If you want to automate this for all your fields, you could provide your own Schema.on_bind_field() implementation to generate a data_key value from the field name:

import re
from functools import partialfrom marshmallow import Schema_snake_case = re.compile(r"(?<=\w)_(\w)")
_to_camel_case = partial(_snake_case.sub, lambda m: m[1].upper())class CamelCasedSchema(Schema):"""Gives fields a camelCased data key"""def on_bind_field(self, field_name, field_obj, _cc=_to_camel_case):field_obj.data_key = _cc(field_name.lower())

Demo:

>>> from marshmallow import fields
>>> class UserSchema(CamelCasedSchema):
...     first_name = fields.String()
...     last_name = fields.String()
...
>>> schema = UserSchema()
>>> schema.load({"firstName": "Eric", "lastName": "Idle"})
{'first_name': 'Eric', 'last_name': 'Idle'}
>>> schema.dump({"first_name": "John", "last_name": "Cleese"})
{'firstName': 'John', 'lastName': 'Cleese'}

The examples section of the Marshmallow documentation has a similar recipe.

If you are using Marshmallow 2.x, then there are two arguments to set: load_from and dump_to.

https://en.xdnf.cn/q/69960.html

Related Q&A

pytest reports too much on assert failures

Is there a way for pytest to only output a single line assert errors?This problem arises when you have modules with asserts, If those asserts fails, it dumps the entire function that failed the assert…

pulp.solvers.PulpSolverError: PuLP: cannot execute glpsol.exe

I am a newbie with python and optimization. I am getting some error, please help me resolve it. I tried running the below mentioned code in PyCharm where I am running Anaconda 3from pulp import * x = L…

Django urldecode in template file

is there any way do the urldecode in Django template file? Just opposite to urlencode or escapeI want to convert app%20llc to app llc

Structure accessible by attribute name or index options

I am very new to Python, and trying to figure out how to create an object that has values that are accessible either by attribute name, or by index. For example, the way os.stat() returns a stat_resul…

Loading data from Yahoo! Finance with pandas

I am working my way through Wes McKinneys book Python For Data Analysis and on page 139 under Correlation and Covariance, I am getting an error when I try to run his code to obtain data from Yahoo! Fin…

Run Multiple Instances of ChromeDriver

Using selenium and python I have several tests that need to run in parallel. To avoid using the same browser I added the parameter of using a specific profile directory and user data (see below). The p…

numpy 2d array max/argmax

I have a numpy matrix:>>> A = np.matrix(1 2 3; 5 1 6; 9 4 2) >>> A matrix([[1, 2, 3],[5, 1, 6],[9, 4, 2]])Id like to get the index of the maximum value in each row along with the valu…

How do I add a python script to the startup registry?

Im trying to make my python script run upon startup but I get the error message windowserror access denied, but I should be able to make programs start upon boot because teamviewer ( a third-party prog…

Python: How can I filter a n-nested dict of dicts by leaf value?

Ive got a dict that looks something like this:d = {Food: {Fruit : {Apples : {Golden Del. : [Yellow],Granny Smith : [Green],Fuji : [Red], },Cherries : [Red],Bananas : [Yellow],Grapes …

contour plot - clabel spacing

I have trouble with matplotlib / pyplot / basemap. I plot contour lines (air pressure) on a map. I use clabel to show the value of the contour lines. But the problem is: the padding between the value a…