我正在制作一个与API连接的网络应用程序。当用户授权我的webapp使用第三方API时,API会发送与用户相关的信息。我想在我的模型中保存这些信息,以便将来使用它。我不确定如何针对已经登录的用户在模型中保存该信息。这是我的代码:
views.py:
from .models import UserInfo
def auth_finish(request):
app_session = request.session
try:
oa_auth = auth_flow(app_session).finish(request.GET)
if request.method == 'GET':
UserInfo.user = request.user # How to save this model?
UserInfo.access_token = oa_auth.access_token # How to save this model?
UserInfo.account_id = oa_auth.account_id # How to save this model?
UserInfo.dbx_user_id = oa_auth.user_id # How to save this model?
return render(request, 'index.html')
except oauth.BadRequestException as e:
return HttpResponse(e)
models.py
from django.contrib.auth.models import User
class UserInfo(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
access_token = models.CharField(max_length=20, blank=False)
account_id = models.CharField(max_length=10, blank=False)
dbx_user_id = models.CharField(max_length=10, blank=False)
信息正确地出现在我的视图中,我可以在views.py中用它构建一个字典。如何保存此信息?
def auth_finish(request):
app_session = request.session
try:
oa_auth = auth_flow(app_session).finish(request.GET)
user_auth_info = dict()
user_auth_info['access_token'] = oa_auth.access_token
user_auth_info['account_id'] = oa_auth.account_id
user_auth_info['user_id'] = oa_auth.user_id
user_auth_info['app_user'] = request.user
print(user_auth_info)
return render(request, 'index.html')
except oauth.BadRequestException as e:
return HttpResponse(e)
答案 0 :(得分:1)
from .models import UserInfo
def auth_finish(request):
app_session = request.session
try:
oa_auth = auth_flow(app_session).finish(request.GET)
if request.method == 'GET':
user_info_instance = UserInfo(user=request.user, access_token=oa_auth.access_token, account_id=oa_auth.account_id, dbx_user_id=oa_auth.user_id)
user_info_instance.save()
return render(request, 'index.html')
except oauth.BadRequestException as e:
return HttpResponse(e)