【问题标题】:Django app with Rails API带有 Rails API 的 Django 应用程序
【发布时间】:2017-07-14 18:51:56
【问题描述】:

如何从 API 中获取 JSON 对象,然后在模板中很好地显示它?

一段时间以来,我一直在反对这个。我有一些使用 Django 应用程序的经验,但我以前从未构建过仅 API 的应用程序,因此 requestsjson 库对我来说是新的。 API 是用 Rails 构建的。在文档中磕磕绊绊,我已经能够验证并获取数据。现在我只是在纠结如何在模板中显示它。

Views.py

def accounts(request):
    # To-Do: Better check for user logged with API
    if not request.session.get('api_token'):
        return HttpResponseRedirect('/')
    token = 'Token token=' + request.session.get('api_token')
    path = 'https://myrailsapi.heroku.com/accounts'
    req = requests.get(path, headers={'Authorization': token})
    accounts = req.json()

    print(accounts)

    context = {'accounts': accounts}
    return render(request, 'accounts.html', context)

accounts(数据)如下所示:

[{'created_at':无,'account_username':'woof','id':12, 'updated_at':无,'account_password':'woof','user_id':3, 'account_type': 'credit', 'institution_name': 'test'}, {'created_at':无,'account_username':'ge','id':22,'updated_at': 无,'account_password':'ge','user_id':3,'account_type': '检查','机构名称':'test2'}]

accounts.html

{% for account in accounts %}
          <div class="card small>
            <div class="card-content white-text">
              <span class="card-title no_margin">
                {{ account.account_name }}
              </span>
              <span class="card_subtitle">
                {{ account.account_type }}
                <span class="right">Balance</span>
              </span>
            </div>
{% endfor %}

如何像使用 queryset/python 对象一样访问 json 数据?

到目前为止,我已经尝试按照here 的描述创建一个类并创建一个 python 对象。

class j_object(object):
    def __init__(self,j):
        self.__dict__ = json.loads(j)

这给了我一个错误TypeError: the JSON object must be str, not 'list'。然后我尝试解析数据,使其成为一个字符串并得到错误ValueError: Expecting property name enclosed in double quotes: line 1 column 3 (char 2)。 我知道在 accounts 上调用 json.loads 可能会遇到问题,因为它设置为 req.json(),所以我也尝试过不使用它,但仍然不行。

【问题讨论】:

    标签: python json django django-templates


    【解决方案1】:

    建议

    views.py

    data = [{'created_at': None, 'account_username': 'woof', 'id': 12, 'updated_at': None, 'account_password': 'woof', 'user_id': 3, 'account_type': 'credit', 'institution_name': 'test'}, {'created_at': None, 'account_username': 'ge', 'id': 22, 'updated_at': None, 'account_password': 'ge', 'user_id': 3, 'account_type': 'checking', 'institution_name': 'test2'}]
    
    print type(data) ## list
    result_data = {}
    result_data['data'] = data
    
    print type(result_data) ## dict    
    print "FFFFFFFFFFFFFFFFFFFFFFfffffffffffffffffffffffffff"
    ddd = json.dumps(result_data)
    dd = json.loads(ddd)
    
    return render(request,'accounts.html',
            {
              'accounts':dd['data'],
            }
        )
    
    
    ## HTML
    {% for account in accounts %}
              <div class="card small>
                <div class="card-content white-text">
                  <span class="card-title no_margin">
                    {{ account.account_name }}
                  </span>
                  <span class="card_subtitle">
                    {{ account.account_type }}
                    <span class="right">Balance</span>
                  </span>
                </div>
    {% endfor %}
    

    【讨论】:

    • 效果很好!这很简单——我还有很多东西要学。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    • 1970-01-01
    • 2015-09-05
    • 1970-01-01
    • 1970-01-01
    • 2013-07-31
    相关资源
    最近更新 更多