【问题标题】:Best way to refrence json block that doesn't have a unique field in order to pass it to another page?引用没有唯一字段的 json 块以将其传递到另一个页面的最佳方法?
【发布时间】:2020-10-05 05:24:10
【问题描述】:

我有一个大型模板文件here,我正在 for 循环中访问它以打印一个包含一些值的表。当用户单击其中一个值时,我希望它仅将 1 个 json 块转移到另一个页面,以使其预填充某些字段。我无法让我的程序在 json 字典中选择该单个条目以呈现下一页。以下是涉及的代码:

views.py

@apps.route('/add')
@login_required
@admin_required
def view_apps():
    """ View available apps """
    template = Template.query.all()
    dir_path = os.path.dirname(os.path.realpath(__file__))
    json_content = combine_json_templates()
    print(json_content)
    print(len(json_content))
    return render_template('apps/add_app.html', apps=json_content)

def combine_json_templates():

    master_list = []

    cwd = os.getcwd()
    print(cwd)
    json_storage = 'app/storage/templates/json/'


    for file in os.listdir(json_storage):
        with open(json_storage + file) as json_path:
            json_content = json.load(json_path)
            for item in json_content:
                master_list.append(item)


    return master_list

@apps.route('/add/<int:app_id>')
@apps.route('/add/<int:app_id>/info')
def app_info(app_id):
    app = json_content[""+app_id+""]
    print(app)

add_app.html(显示表格并包含 onclick 的代码:

<div style="overflow-x: scroll;">
                <table class="ui searchable sortable unstackable selectable celled table">
                    <thead>
                        <tr onclick="window.location.href = '{{ url_for('apps.app_info', app_id=apps.pop(['name'])) }}';">
                            <th class="sorted ascending">Title</th>
                            <th>Desctiption</th>
                            <th>Catagory</th>
                            <th>Platform</th>
                        </tr>
                    </thead>
                    <tbody>
                    {% for a in apps | sort(attribute='title') %}
                        <tr>
                            <td>{{ a.title }}</td>
                            <td>{{ a.description }}</td>
                            <td>{{ a.categories }}</td>
                            <td>{{ a.platform }}</td>
                        </tr>
                    {% endfor %}
                    </tbody>
                </table>
            </div>

我遇到问题的部分是获取一个唯一值,以便将其传递到下一页并引用正确的 json。

<tr onclick="window.location.href = '{{ url_for('apps.app_info', app_id=apps.pop(['name'])) }}';">

我应该使用不同的方法来引用 json 文件吗?我应该在加载 json 文件时修改它以添加某种密钥吗?

这是我的第一个烧瓶项目,所以我不确定最好的方法。

【问题讨论】:

  • “应用程序”中的索引是什么意思?
  • 这绝对可以理解。我对烧瓶还是陌生的,所以有点混乱。有没有更好的方式让我与您取得联系并进行更深入的解释?
  • 基本上在 onclick 函数应用程序中是一个包含目录的列表(每个目录都有上面链接的模板中的一个 json 块的内容)我不相信它现在还在排序。该视图是一个表格,其中显示了来自每个 json 块的信息(使用 for 循环),单击时我试图传递某种标识符以在下一页中引用所选字典(json 块及其内容)。
  • 有没有办法让我们把它移到聊天中?
  • 我不知道聊天,但想想我的答案。这就是你想要的吗?

标签: javascript python json flask


【解决方案1】:

我觉得我有办法,问题是你喜不喜欢。

# ./__init__.py 
def create_app():
    app = Flask(__name__,
        # default: ./var/app-instance/
        instance_relative_config=True,
    )
    app.config.from_mapping(
        SECRET_KEY=b'change-me\n',
    )
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # init endpoints/blueprints here
    from .apps import create_module as apps_create_module
    apps_create_module(app)

    return app
# ./app/apps/view.py 

# TODO: move this to the apps configuration file
JSON_TEMPLATES_DIR = 'storage/templates/json'

def load_json_data(path):
    data = []
    for fname in glob(os.path.join(path, '*.json')):
        with open(fname) as fp:
            dataset = json.load(fp)
            data.extend(dataset)
    return data

@apps.route('/add')
@login_required
@admin_required
def list_apps():
    '''View available apps'''
    apps = load_json_data(
        os.path.join(current_app.instance_path,
        JSON_TEMPLATES_DIR))
    return render_template('apps/add_app.html', **locals())

@apps.route('/add/info', methods=['POST'])
@csrf.exempt
def app_info():
    '''View selected app'''
    ident = request.form.get('ident', None)
    if ident:
        try:
            app = json.loads(ident)
            print(app)
        except: pass
    return render_template('apps/app_info.html', **locals())
<!-- "./app/templates/apps/add_app.html" -->
<div style="overflow-x: scroll;">
    <table class="ui searchable sortable unstackable selectable celled table">
        <thead>
            <tr>
                <th class="sorted ascending">Title</th>
                <th>Description</th>
                <th>Catagory</th>
                <th>Platform</th>
            </tr>
        </thead>
        <tbody>
            {% for a in apps | sort(attribute='title') %}
            <tr id="app-entry-{{loop.index}}">
                <td>
                    <div class="namecell">
                        <span class="nametext" style="display: block;">{{ a.title }}</span>
                        <span class="btn-group" role="group" style="margin-top: 1rem">
                            <form method="post" action="{{url_for('apps.app_info')}}">
                                <input type="hidden" name="ident" value='{{app | tojson | safe}}' />
                                <button type="submit">Setup</button>
                            </form>
                        </span>
                    </div>
                </td>
                <td>{{ a.description }}</td>
                <td>{{ a.categories }}</td>
                <td>{{ a.platform }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>

【讨论】:

  • 这将返回文件“/home/user/dev/selfhosted/SelfhostinGUI/app/apps/views.py”,第 54 行,在 return list(sorted(master_list, key=lambda k : k['name'])) KeyError: 'name'
  • 因为“名称”键并非在所有条目中都可用。我会修改我的版本。
  • 感谢您的帮助。如果可以的话,我会和你聊天以提供帮助。我不确定为什么这个平台不支持它。我不知道在尝试扩展而不是追加时是否有帮助,它只用第一个键(名称、网络、标题等)填充它,但没有与它们关联的值。
  • 没问题我愿意帮忙。将 json 数据存储在全局变量中是否更有意义,还是您不想这样做?您的应用程序中的数据是否以修改后的形式再次保存?
  • 我不想这样做。它是在每次页面加载时生成的(由于用户可能添加了模板),我确实为用户添加的模板存储了单独的值,以便使它们易于更新。其中的数据将使用模板中的所有值在下一页上预填充表单,以便用户可以在部署之前对其进行修改。
猜你喜欢
  • 2011-03-13
  • 1970-01-01
  • 1970-01-01
  • 2020-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-30
  • 1970-01-01
相关资源
最近更新 更多