在django视图中存储用户访问令牌

时间:2017-12-01 06:19:49

标签: python django shopify

我尝试在首次安装/验证时(在创建帐户和连接到数据库之前)在django视图中存储shopify访问令牌。

我是django的新手所以请你好。

如何存储此访问令牌以供日后使用?它可以存储在" session&#34 ;?是吗?

这是我的repo和python视图:

def finalize(request):
    shop_url = request.GET['shop']
    auth_code = request.GET['code']
    hashed = request.GET['hmac']
    ts = request.GET['timestamp']
    print("shopURL", shop_url)

    print("success request")
    try:
        r = requests.post('https://'+shop_url+'/admin/oauth/access_token', data = {'client_id':'xx','client_secret':'xx','code':auth_code})

        print("request response > > > > ", r.json())
        this_response = r.json()
        print(this_response["access_token"],"this_response[access_token]")
       # >>>>>> STORE THIS TOKEN SOMEWHERE?
        request.session['shopify'] = {
            "shop_url": shop_url,
            "access_token": this_response["access_token"]
        }

    except Exception:
        messages.error(request, "Could not log in to Shopify store.")

        return redirect(reverse('shopify_app_login'))

    messages.info(request, "Logged in to shopify store.")

    response = redirect(_return_address(request))
    request.session.pop('return_to', None)
    return response

1 个答案:

答案 0 :(得分:1)

最佳选择是将其存储在Django用户中。您可以扩展Django用户以添加您自己的文件

class Profile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    shopify_access_token = models.CharField(max_length=200)

稍后您可以使用request.user.profile.shopify_access_token

访问此令牌