質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

1回答

6645閲覧

認証時のトークン発行コードのエラー

gabri_1207

総合スコア1

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2021/03/12 15:27

編集2021/03/13 06:18

プログラミング初心者です。
現在、PythonのフレームワークFastAPIでWebアプリを初めて作成しております。

ユーザー認証機能を作成しているのですが、ユーザー認証時のトークンの発行コード内でTypeErrorが出てきて、解決に困っております。

def create_tokens(user_id:int): """トークンの発行 """ access_payload={ "token_type": "access_token", "exp": datetime.utcnow() + timedelta(minutes=60), "user_id": user_id } refresh_payload={ "token_type": "refresh_token", "exp": datetime.utcnow() + timedelta(days=60), "user_id": user_id } access_token= jwt.encode(access_payload, "SECRET_KEY1234", algorithm="HS256") refresh_token= jwt.encode(refresh_payload, "SECRET_KEY1234", algorithm="HS256") Users.update(refresh_token=refresh_token).where(Users.id == user_id).execute() return {'access_token': access_token, 'refresh_token': refresh_token, 'token_type': 'bearer'}

現在、トークンはサンプルとして上記の様にコードを書きました。
すると以下の様にエラーが発生しました。

FROM users api | WHERE users.name = %s api | LIMIT %s api | 2021-03-12 15:02:39,699 INFO sqlalchemy.engine.base.Engine ('Goku', 1) api | INFO: 172.18.0.1:52272 - "POST /v0/admin/token HTTP/1.1" 500 Internal Server Error api | ERROR: Exception in ASGI application api | Traceback (most recent call last): api | File "/usr/local/lib/python3.8/site-packages/uvicorn/protocols/http/h11_impl.py", line 394, in run_asgi api | result = await app(self.scope, self.receive, self.send) api | File "/usr/local/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__ api | return await self.app(scope, receive, send) api | File "/usr/local/lib/python3.8/site-packages/fastapi/applications.py", line 179, in __call__ api | await super().__call__(scope, receive, send) api | File "/usr/local/lib/python3.8/site-packages/starlette/applications.py", line 111, in __call__ api | await self.middleware_stack(scope, receive, send) api | File "/usr/local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__ api | raise exc from None api | File "/usr/local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__ api | await self.app(scope, receive, _send) api | File "/usr/local/lib/python3.8/site-packages/starlette/middleware/cors.py", line 86, in __call__ api | await self.simple_response(scope, receive, send, request_headers=headers) api | File "/usr/local/lib/python3.8/site-packages/starlette/middleware/cors.py", line 142, in simple_response api | await self.app(scope, receive, send) api | File "/usr/local/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__ api | raise exc from None api | File "/usr/local/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__ api | await self.app(scope, receive, sender) api | File "/usr/local/lib/python3.8/site-packages/starlette/routing.py", line 566, in __call__ api | await route.handle(scope, receive, send) api | File "/usr/local/lib/python3.8/site-packages/starlette/routing.py", line 227, in handle api | await self.app(scope, receive, send) api | File "/usr/local/lib/python3.8/site-packages/starlette/routing.py", line 41, in app api | response = await func(request) api | File "/usr/local/lib/python3.8/site-packages/fastapi/routing.py", line 182, in app api | raw_response = await run_endpoint_function( api | File "/usr/local/lib/python3.8/site-packages/fastapi/routing.py", line 135, in run_endpoint_function api | return await run_in_threadpool(dependant.call, **values) api | File "/usr/local/lib/python3.8/site-packages/starlette/concurrency.py", line 34, in run_in_threadpool api | return await loop.run_in_executor(None, func, *args) api | File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 57, in run api | result = self.fn(*self.args, **self.kwargs) api | File "./routers/admin.py", line 69, in login api | return create_tokens(user.id) api | File "./routers/admin.py", line 42, in create_tokens api | Users.update(refresh_token=refresh_token).where(Users.id == user_id).execute() api | TypeError: update() got an unexpected keyword argument 'refresh_token'

TypeErrorということですが、これはupdate()の引数の定義の仕方に不備があるのでしょうか?
解決方法が分からない状態です。
何かお力添えを頂けますと嬉しいです。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

Usersはどのように定義していますか。

もしもUsersがsqlalchemy.TableのインスタンスならUsers.updateは引数を持ちません。

投稿2021/03/13 09:53

ppaul

総合スコア24666

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

gabri_1207

2021/03/13 11:18 編集

回答ありがとうございます。 Usersは下記のように定義しております。 ``` from datetime import datetime from sqlalchemy import Column, String, Integer, DateTime from sqlalchemy.orm import relationship from passlib.context import CryptContext from settings.db import Base from .groups import users_groups pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") class Users(Base): """ユーザーアカウント.""" __tablename__ = "users" name = Column(String(50), nullable=False) email = Column(String(50), nullable=False, unique=True) password = Column(String(255), nullable=False) age = Column(Integer, nullable=False) gender = Column(String(3), nullable=False) height = Column(Integer, nullable=False) weight = Column(Integer, nullable=False) kind_of_sport = Column(String(6), nullable=False) type_of_team = Column(String(20), nullable=False) years_of_experience = Column(Integer, nullable=False) group_id = Column(Integer, nullable=True) last_login = Column(DateTime, nullable=False, default=datetime.now) created_at = Column(DateTime, nullable=False, default=datetime.now) updated_at = Column(DateTime, nullable=True, default=None) refresh_token = Column(String(255), nullable=True) objectives = relationship( "Objectives", back_populates="user", uselist=True, order_by="Objectives.id", cascade="all, delete", passive_deletes=True ) groups = relationship( "Groups", back_populates="users", uselist=True, order_by="Groups.id", secondary=users_groups ) def __init__( self, name: str, email: str, password: str, age: int, gender: str, height: int, weight: int, kind_of_sport: str, type_of_team: str, years_of_experience: int, group_id:int, refresh_token:str ): self.name = name self.email = email self.password = pwd_context.hash(password) self.age = age self.gender = gender self.height = height self.weight = weight self.kind_of_sport = kind_of_sport self.type_of_team = type_of_team self.years_of_experience = years_of_experience self.group_id = group_id self.refresh_token = refresh_token ``` こちらではうまくいきませんでした。 どのような原因が考えられますでしょうか?
ppaul

2021/03/13 12:15

エラーメッセージの意味は、update()はrefresh_tokenという名前の付いたキーワード引数は持っていませんです。 from settings.db import Baseが何をimport しているのかが分からないので、なんとももいえません。 以下の結果を見れば何かわかるかもしれません。 help(Users.update)
gabri_1207

2021/03/13 15:44

help(Users.update)としてみました。 結果に update(self, payload)と返ってきました。 payload=fresh_token selfには何が入ってくるべきなのでしょうか?
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問