minimal-fastapi-postgres-template icon indicating copy to clipboard operation
minimal-fastapi-postgres-template copied to clipboard

unsupported operand type(s) for |: type and type

Open mbnoimi opened this issue 3 years ago • 3 comments
trafficstars

$ bash init.sh 
Run migrations
INFO  [alembic.runtime.migration] Context impl PostgresqlImpl.
INFO  [alembic.runtime.migration] Will assume transactional DDL.
Create initial data in DB
Traceback (most recent call last):
  File "/usr/lib/python3.9/runpy.py", line 197, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/lib/python3.9/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/home/laptop/playground/backend/api/app/initial_data.py", line 12, in <module>
    from app.core import config, security
  File "/home/laptop/playground/backend/api/app/core/security.py", line 55, in <module>
    def generate_access_token_response(subject: str | int):
TypeError: unsupported operand type(s) for |: 'type' and 'type'

The following line throws an error during executing bash init.sh

class JWTTokenPayload(BaseModel):
    sub: str | int #-----> This line
    refresh: bool
    issued_at: int
    expires_at: int

I fixed it by using sub: str and modifying the other related methods.

What's wrong with sub: str | int ?

mbnoimi avatar Jul 25 '22 04:07 mbnoimi

Hi @mbnoimi Hmm, are you using Python 3.10?? This syntax (str | int) requires it.

Template was written with python 3.10 in mind.

And by the way it has sort of sense (see https://jwt.io/introduction, wikipedia or other sources for more info) JWT has 3 parts and second one is your own payload, when you can store string, int, float, bool for sure and maybe even some more complex types (it would require some investigation in jwt reference and python module included in this template also).

And sub states for "id", "uuid", "something unique", "serial" that can be really both int and str, and when user or part that use this token for authentication send it in header, you grab user from database by this unique something

rafsaf avatar Jul 25 '22 18:07 rafsaf

Hmm, are you using Python 3.10?? This syntax (str | int) requires it.

Python 3.9.5

mbnoimi avatar Jul 25 '22 18:07 mbnoimi

Waited like 1-2years for this new sytax to work, really cool stuff

But unfortunately template doesn't have something like backward compatible types based on typing module since it has not really use in python 3.10+ (for base types! Literal, Generic etc. are still in use)

So you have 2 ways, either upgrade (Python 3.10 was first released in October 2021) or remove all this syntax around code

rafsaf avatar Jul 25 '22 18:07 rafsaf

Upgraded docs a bit so there won't be situations like this hopefully

rafsaf avatar Oct 19 '22 19:10 rafsaf