Skip to content

Commit 398fbaa

Browse files
committed
Changed the the entity_type kwarg to table_name joegasewicz#111
1 parent df18129 commit 398fbaa

9 files changed

+51
-43
lines changed

CHANGELOG.md

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
**Unreleased**
2+
- Changed the the `entity_type` kwarg to `table_name` in the public method `register_entity`
3+
[Ref issue #111](https://github.com/joegasewicz/Flask-JWT-Router/issues/111)

README.md

+4-4
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ app.config["WHITE_LIST_ROUTES"] = [
103103
def register():
104104
"""I'm registering a new user & returning a token!"""
105105
return jsonify({
106-
"token": jwt_routes.register_entity(entity_id=1, entity_type='users')
106+
"token": jwt_routes.register_entity(entity_id=1, table_name='users')
107107
})
108108

109109
@app.route("/login", methods=["POST"])
@@ -114,7 +114,7 @@ def login():
114114
})
115115
```
116116

117-
*Warning: The `entity_type` must be the same as your tablename or `__tablename__` attribute's value.
117+
*Warning: The `table_name` must be the same as your tablename or `__tablename__` attribute's value.
118118
(With SqlAlchemy, you can define a `__tablename__` attribute directly or else
119119
the name is derived from your entity’s database table name).
120120

@@ -129,7 +129,7 @@ Create a new entity & return a new token
129129
user.create_user() # your entity creation logic
130130

131131
# Here we pass the id as a kwarg to `register_entity`
132-
token: str = jwt_routes.register_entity(entity_id=user.id, entity_type="users")
132+
token: str = jwt_routes.register_entity(entity_id=user.id, table_name="users")
133133

134134
# Now we can return a new token!
135135
return {
@@ -169,7 +169,7 @@ If you are handling a request with a token in the headers you can call::
169169
If you are handling a request without a token in the headers you can call::
170170

171171
```python
172-
jwt_routes.register_entity(entity_id=user_data.id, entity_type="users")
172+
jwt_routes.register_entity(entity_id=user_data.id, table_name="users")
173173
```
174174

175175

flask_jwt_router/_authentication.py

+11-11
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,11 @@ def register_entity(self, extensions: Config, exp: int, **kwargs):
3434
pass
3535

3636
@abstractmethod
37-
def update_entity(self, extensions: Config, exp: int, entity_type, **kwarg):
37+
def update_entity(self, extensions: Config, exp: int, table_name, **kwarg):
3838
# pylint:disable=missing-function-docstring
3939
pass
4040

41-
def encode_token(self, extensions: Config, entity_id: Any, exp: int, entity_type: str):
41+
def encode_token(self, extensions: Config, entity_id: Any, exp: int, table_name: str):
4242
# pylint:disable=missing-function-docstring
4343
pass
4444

@@ -62,19 +62,19 @@ def __init__(self):
6262
# pylint:disable=useless-super-delegation
6363
super(JWTAuthStrategy, self).__init__()
6464

65-
def encode_token(self, extensions: Config, entity_id: Any, exp: int, entity_type) -> str:
65+
def encode_token(self, extensions: Config, entity_id: Any, exp: int, table_name) -> str:
6666
"""
6767
:param extensions: See :class:`~flask_jwt_router._extensions`
6868
:param entity_id: Normally the primary key `id` or `user_id`
6969
:param exp: The expiry duration set when encoding a new token
70-
:param entity_type: The Model Entity `__tablename__`
70+
:param table_name: The Model Entity `__tablename__`
7171
:return: str
7272
"""
7373
self.entity_key = extensions.entity_key
7474
self.secret_key = extensions.secret_key
7575
# pylint: disable=line-too-long
7676
encoded = jwt.encode({
77-
"entity_type": entity_type,
77+
"table_name": table_name,
7878
self.entity_key: entity_id,
7979
# pylint: disable=no-member
8080
"exp": datetime.utcnow() + relativedelta(days=+exp)
@@ -85,28 +85,28 @@ def register_entity(self, extensions: Config, exp: int, **kwargs) -> str:
8585
"""
8686
kwargs:
8787
- entity_id: Represents the entity's primary key
88-
- entity_type: The table name of the entity
88+
- table_name: The table name of the entity
8989
:param extensions: See :class:`~flask_jwt_router._extensions`
9090
:param exp: The expiry duration set when encoding a new token
9191
:param kwargs:
9292
:return: Union[str, None]
9393
"""
9494
self.entity_id = kwargs.get("entity_id", None)
95-
entity_type = kwargs.get("entity_type", None)
96-
return self.encode_token(extensions, self.entity_id, exp, entity_type)
95+
table_name = kwargs.get("table_name", None)
96+
return self.encode_token(extensions, self.entity_id, exp, table_name)
9797

9898
def update_entity(self,
9999
extensions: Config,
100100
exp: int,
101-
entity_type: str,
101+
table_name: str,
102102
**kwargs,
103103
) -> str:
104104
"""
105105
:param extensions:
106106
:param exp:
107-
:param entity_type:
107+
:param table_name:
108108
:param kwargs:
109109
:return: Union[str, None]
110110
"""
111111
self.entity_id = kwargs.get("entity_id", None)
112-
return self.encode_token(extensions, self.entity_id, exp, entity_type)
112+
return self.encode_token(extensions, self.entity_id, exp, table_name)

flask_jwt_router/_entity.py

+11-11
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
class BaseEntity(ABC):
1313
# pylint:disable=missing-class-docstring
1414
@abstractmethod
15-
def get_attr_name(self, entity_type: str = None) -> str:
15+
def get_attr_name(self, table_name: str = None) -> str:
1616
# pylint:disable=missing-function-docstring
1717
pass
1818

@@ -22,7 +22,7 @@ def get_entity_from_token(self, decoded_token: str) -> str:
2222
pass
2323

2424
@abstractmethod
25-
def get_entity_from_ext(self, entity_type: str = None) -> _ORMType:
25+
def get_entity_from_ext(self, table_name: str = None) -> _ORMType:
2626
# pylint:disable=missing-function-docstring
2727
pass
2828

@@ -44,7 +44,7 @@ class Entity(BaseEntity):
4444
def __init__(self, extensions: ClassVar):
4545
self.extensions = extensions
4646

47-
def get_attr_name(self, entity_type: str = None) -> str:
47+
def get_attr_name(self, table_name: str = None) -> str:
4848
"""
4949
If SQLAlchemy is the ORM then expect there to be a
5050
__mapper__.primary_key path. This returns a list
@@ -53,11 +53,11 @@ def get_attr_name(self, entity_type: str = None) -> str:
5353
existing option of specifying a primary key name directly
5454
for scenarios when not using SqlAlchemy etc & also assigns
5555
a default primary key to `id`.
56-
:param entity_type:
56+
:param table_name:
5757
:return:
5858
"""
5959
if not self.auth_model:
60-
self.auth_model = self.get_entity_from_ext(entity_type)
60+
self.auth_model = self.get_entity_from_ext(table_name)
6161
if hasattr(self.auth_model, "__mapper__"):
6262
# SqlAlchemy is the ORM being used
6363
return self.auth_model.__mapper__.primary_key[0].name
@@ -72,26 +72,26 @@ def _get_from_model(self, entity_id: int) -> _ORMType:
7272
result = self.auth_model.query.filter_by(**{entity_key: entity_id}).one()
7373
return result
7474

75-
def get_entity_from_ext(self, entity_type: str = None) -> _ORMType:
75+
def get_entity_from_ext(self, table_name: str = None) -> _ORMType:
7676
"""
7777
Exception raised if SQLAlchemy ORM not being used
7878
(SQLAlchemy will throw if `__tablename__` doesn't exist
7979
or it can't create the name from the db engine's table object.
8080
:return: {_ORMType}
8181
"""
82-
if not entity_type:
83-
# In case `update_entity()` is called, `entity_type` is in the token
84-
entity_type = self.decoded_token.get("entity_type")
82+
if not table_name:
83+
# In case `update_entity()` is called, `table_name` is in the token
84+
table_name = self.decoded_token.get("table_name")
8585
auth_model = None
8686

8787
for model in self.extensions.entity_models:
8888
if hasattr(model, "__tablename__"):
89-
if entity_type == model.__tablename__:
89+
if table_name == model.__tablename__:
9090
auth_model = model
9191
else:
9292
raise Exception(
9393
"[FLASK-JWT-ROUTER ERROR]: Your Entity model must have a `__tablename__` that"
94-
" is equal to the entity_type specified in register_entity()."
94+
" is equal to the table_name specified in register_entity()."
9595
"For details visit:\n"
9696
# pylint:disable=line-too-long
9797
"https://flask-jwt-router.readthedocs.io/en/latest/jwt_routes.html#authorization-tokens"

flask_jwt_router/_jwt_router.py

+13-8
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
The super class for Flask-JWT-Router
33
"""
44
import logging
5+
from warnings import warn
56

67
from ._extensions import BaseExtension, Extensions, Config
78
from ._entity import BaseEntity, Entity
@@ -102,10 +103,14 @@ def register_entity(self, **kwargs) -> str:
102103
:param kwargs:
103104
:return: str
104105
"""
105-
if 'entity_type' not in kwargs:
106-
raise KeyError("register_entity() missing 1 required argument: entity_type")
107-
entity_type = kwargs.get("entity_type")
108-
self.extensions.entity_key = self.entity.get_attr_name(entity_type)
106+
if 'entity_type' in kwargs:
107+
warn(("'entity_type' argument name has been deprecated and will be replaced"
108+
"in the next release. Use 'table_name' instead"))
109+
kwargs['table_name'] = kwargs['entity_type']
110+
if 'table_name' not in kwargs:
111+
raise KeyError("register_entity() missing 1 required argument: table_name")
112+
table_name = kwargs.get("table_name")
113+
self.extensions.entity_key = self.entity.get_attr_name(table_name)
109114
return self.auth.register_entity(self.extensions, self.exp, **kwargs)
110115

111116
def update_entity(self, **kwargs) -> str:
@@ -114,14 +119,14 @@ def update_entity(self, **kwargs) -> str:
114119
:return: str
115120
"""
116121
self.extensions.entity_key = self.entity.get_attr_name()
117-
entity_type = self.entity.get_entity_from_ext().__tablename__
118-
return self.auth.update_entity(self.extensions, self.exp, entity_type, **kwargs)
122+
table_name = self.entity.get_entity_from_ext().__tablename__
123+
return self.auth.update_entity(self.extensions, self.exp, table_name, **kwargs)
119124

120125
def encode_token(self, entity_id) -> str:
121126
"""
122127
:param entity_id:
123128
:return:
124129
"""
125130
self.extensions.entity_key = self.entity.get_attr_name()
126-
entity_type = self.entity.get_entity_from_ext().__tablename__
127-
return self.auth.encode_token(self.extensions, entity_id, self.exp, entity_type)
131+
table_name = self.entity.get_entity_from_ext().__tablename__
132+
return self.auth.encode_token(self.extensions, entity_id, self.exp, table_name)

flask_jwt_router/_jwt_routes.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ def register():
112112
user.create_user() # your entity creation logic
113113
114114
# Here we pass the id as a kwarg to `register_entity`
115-
token: str = jwt_routes.register_entity(entity_id=user.id, entity_type="user")
115+
token: str = jwt_routes.register_entity(entity_id=user.id, table_name="user")
116116
117117
# Now we can return a new token!
118118
return {
@@ -137,7 +137,7 @@ def login():
137137
}, 401
138138
return {
139139
"data": user_dumped,
140-
"token": jwt_routes.register_entity(entity_id=user_data.id, entity_type="user"),
140+
"token": jwt_routes.register_entity(entity_id=user_data.id, table_name="user"),
141141
}, 200
142142
143143
If you are handling a request with a token in the headers you can call::
@@ -146,7 +146,7 @@ def login():
146146
147147
If you are handling a request without a token in the headers you can call::
148148
149-
jwt_routes.register_entity(entity_id=user_data.id, entity_type="user")
149+
jwt_routes.register_entity(entity_id=user_data.id, table_name="user")
150150
151151
"""
152152
from ._authentication import JWTAuthStrategy

tests/fixtures/main_fixture.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def test_entity():
4343
from tests.fixtures.models import TeacherModel
4444
teacher = TeacherModel(name="joe")
4545
teacher.save()
46-
token = jwt_routes.register_entity(entity_id=1, entity_type="teachers")
46+
token = jwt_routes.register_entity(entity_id=1, table_name="teachers")
4747
return jsonify({
4848
"token": token,
4949
})

tests/fixtures/token_fixture.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66

77
new_token = jwt.encode({
8-
"entity_type": "test_entities",
8+
"table_name": "test_entities",
99
"id": 1,
1010
"exp": datetime.utcnow() + relativedelta(days=+30)
1111
},
@@ -29,7 +29,7 @@ def mock_decoded_token():
2929

3030

3131
new_token_two = jwt.encode({
32-
"entity_type": "test_two_entities",
32+
"table_name": "test_two_entities",
3333
"id": 1,
3434
"exp": datetime.utcnow() + relativedelta(days=+30)
3535
},
@@ -53,7 +53,7 @@ def mock_decoded_token_two():
5353

5454

5555
new_token_three = jwt.encode({
56-
"entity_type": "test_3_entities",
56+
"table_name": "test_3_entities",
5757
"teacher_id": 1,
5858
"exp": datetime.utcnow() + relativedelta(days=+30)
5959
},

tests/test_entity.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ def test_get_attr_name(self, test_client):
9090
algorithms="HS256"
9191
)
9292

93-
assert decoded_token["entity_type"] == "teachers"
93+
assert decoded_token["table_name"] == "teachers"
9494

9595
headers = {
9696
"Content-Type": "application/json",
@@ -110,5 +110,5 @@ def test_get_attr_name(self, test_client):
110110
algorithms="HS256"
111111
)
112112

113-
assert decoded_token_two["entity_type"] == "teachers"
113+
assert decoded_token_two["table_name"] == "teachers"
114114

0 commit comments

Comments
 (0)