首页 \ 问答 \ Groups&THREE.MultiMaterial(Groups & THREE.MultiMaterial)

Groups&THREE.MultiMaterial(Groups & THREE.MultiMaterial)

作为原型化一些调试器对象和方法的一部分,我创建了一个在每一侧都有不同颜色的简单立方体。 我决定使用绘图组和THREE.Multimaterial,而不是创建多个网格。 不幸的是,它只是半工作,我不明白为什么。

工作的是前两个边(4个三角形)。 什么是不起作用的是任何其他方面。 其他方面都不可见。 我添加了调试代码来绘制(基于索引的)顶点法线,(基于索引,手动计算)面法线和线框(THREE.WireframeHelper)。

如果我将第二组的计数增加到9,则没有任何反应。 如果我更改组以引用前8个顶点中的不同开始/计数值,则这些更改将按预期工作。 在第8个顶点以上做任何事都没有效果。

我还检查了drawRange设置为从0绘制到无穷大。 我还排除了数据中的拼写错误,因为否则法线和线框不起作用。 还有什么我想念的吗? 谢谢!

(我在r76中发现了这个问题。下面的代码在撰写本文时引用了r79。)

jsfiddle: http //jsfiddle.net/TheJim01/gumftkm4/

HTML:

<script src="http://threejs.org/build/three.js"></script>
<script src="http://threejs.org/examples/js/controls/TrackballControls.js"></script>
<script src="http://threejs.org/examples/js/libs/stats.min.js"></script>
<div id="host"></div>

<script>
// INITIALIZE
var WIDTH = window.innerWidth,
    HEIGHT = window.innerHeight,
    FOV = 35,
    NEAR = 1,
    FAR = 1000;

var renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(WIDTH, HEIGHT);
document.getElementById('host').appendChild(renderer.domElement);

var stats= new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0';
document.body.appendChild(stats.domElement);


var camera = new THREE.PerspectiveCamera(FOV, WIDTH / HEIGHT, NEAR, FAR);
camera.position.z = 250;

var trackballControl = new THREE.TrackballControls(camera, renderer.domElement);
trackballControl.rotateSpeed = 5.0; // need to speed it up a little

var scene = new THREE.Scene();

var light = new THREE.PointLight(0xffffff, 1, Infinity);
light.position.copy(camera.position);

scene.add(light);

function draw(){
    light.position.copy(camera.position);
    renderer.render(scene, camera);
  stats.update();
}
trackballControl.addEventListener('change', draw);

function navStartHandler(e) {
  renderer.domElement.addEventListener('mousemove', navMoveHandler);
  renderer.domElement.addEventListener('mouseup', navEndHandler);
}
function navMoveHandler(e) {
  trackballControl.update();
}
function navEndHandler(e) {
  renderer.domElement.removeEventListener('mousemove', navMoveHandler);
  renderer.domElement.removeEventListener('mouseup', navEndHandler);
}

renderer.domElement.addEventListener('mousedown', navStartHandler);
renderer.domElement.addEventListener('mousewheel', navMoveHandler);
</script>

CSS:

html *{
    padding: 0;
    margin: 0;
    width: 100%;
    overflow: hidden;
}

#host {
    width: 100%;
    height: 100%;
}

JavaScript的:

// New Color Cube
(function () {

    var pos = new Float32Array([
        // front
        -1, 1, 1,
        -1, -1, 1,
        1, 1, 1,
        1, -1, 1,
        // right
        1, 1, 1,
        1, -1, 1,
        1, 1, -1,
        1, -1, -1,
        // back
        1, 1, -1,
        1, -1, -1,
        -1, 1, -1,
        -1, -1, -1,
        // left
        -1, 1, -1,
        -1, -1, -1,
        -1, 1, 1,
        -1, -1, 1,
        // top
        -1, 1, -1,
        -1, 1, 1,
        1, 1, -1,
        1, 1, 1,
        // bottom
        -1, -1, 1,
        -1, -1, -1,
        1, -1, 1,
        1, -1, -1
    ]),
    nor = new Float32Array([
        // front
        0, 0, 1,
        0, 0, 1,
        0, 0, 1,
        0, 0, 1,
        // right
        1, 0, 0,
        1, 0, 0,
        1, 0, 0,
        1, 0, 0,
        // back
        0, 0, -1,
        0, 0, -1,
        0, 0, -1,
        0, 0, -1,
        // left
        -1, 0, 0,
        -1, 0, 0,
        -1, 0, 0,
        -1, 0, 0,
        // top
        0, 1, 0,
        0, 1, 0,
        0, 1, 0,
        0, 1, 0,
        // bottom
        0, -1, 0,
        0, -1, 0,
        0, -1, 0,
        0, -1, 0
    ]),
    idx = new Uint32Array([
        // front
        0, 1, 2,
        3, 2, 1,
        // right
        4, 5, 6,
        7, 6, 5,
        // back
        8, 9, 10,
        11, 10, 9,
        // left
        12, 13, 14,
        15, 14, 13,
        // top
        16, 17, 18,
        19, 18, 17,
        // bottom
        20, 21, 22,
        23, 22, 21
    ]);

    var sideColors = new THREE.MultiMaterial([
        new THREE.MeshLambertMaterial({ color: 'red' }), // front
        new THREE.MeshLambertMaterial({ color: 'green' }), // right
        new THREE.MeshLambertMaterial({ color: 'orange' }), // back
        new THREE.MeshLambertMaterial({ color: 'blue' }), // left
        new THREE.MeshLambertMaterial({ color: 'white' }), // top
        new THREE.MeshLambertMaterial({ color: 'yellow' }) // bottom
    ]);

    var cubeGeometry = new THREE.BufferGeometry();
    cubeGeometry.addAttribute("position", new THREE.BufferAttribute(pos, 3));
    cubeGeometry.addAttribute("normal", new THREE.BufferAttribute(nor, 3));
    cubeGeometry.setIndex(new THREE.BufferAttribute(idx, 3));
    cubeGeometry.clearGroups();
    cubeGeometry.addGroup(0, 6, 0);
    cubeGeometry.addGroup(6, 6, 1);
    cubeGeometry.addGroup(12, 6, 2);
    cubeGeometry.addGroup(18, 6, 3);
    cubeGeometry.addGroup(24, 6, 4);
    cubeGeometry.addGroup(30, 6, 5);

    THREE.ColorCube = function (scaleX, scaleY, scaleZ) {
        THREE.Mesh.call(this, cubeGeometry, sideColors);
        var scaler = new THREE.Matrix4().makeScale(scaleX, scaleY, scaleZ);
        this.applyMatrix(scaler);
    };
    THREE.ColorCube.prototype = Object.create(THREE.Mesh.prototype);
    THREE.ColorCube.prototype.constructor = THREE.ColorCube;

    THREE.ColorCube.prototype.clearVertexNormals = function () {
        if (this.vNormals === undefined) {
            this.vNormals = [];
        }
        for (var i = 0, len = this.vNormals.length; i < len; ++i) {
            this.parent.remove(this.vNormals[i]);
        }
        this.vNormals.length = 0;
    }
    THREE.ColorCube.prototype.drawVertexNormals = function (scale, color) {
        this.clearVertexNormals();
        scale = (scale === undefined) ? 1 : scale;
        color = (color === undefined) ? 0xff : color;
        var origin = new THREE.Vector3(),
            normalArrow = null,
            vert = null,
            norm = null,
            index = null,
            vertexArray = this.geometry.attributes.position.array,
            normalArray = this.geometry.attributes.normal.array,
            indexArray = this.geometry.index.array;

        for (var i = 0, len = indexArray.length; i < len; ++i) {
            index = indexArray[i];
            vert = new THREE.Vector3(...vertexArray.slice((index * 3), (index * 3) + 3)).applyMatrix4(this.matrix);
            norm = new THREE.Vector3(...normalArray.slice((index * 3), (index * 3) + 3));

            normalArrow = new THREE.ArrowHelper(
                norm,
                origin,
                1 * scale,
                color,
                0.2 * scale,
                0.1 * scale
            );

            normalArrow.position.copy(vert);

            this.vNormals.push(normalArrow);
            this.parent.add(normalArrow);
        }
    };

    THREE.ColorCube.prototype.clearFaceNormals = function () {
        if (this.fNormals === undefined) {
            this.fNormals = [];
        }
        for (var i = 0, len = this.fNormals.length; i < len; ++i) {
            this.parent.remove(this.fNormals[i]);
        }
        this.fNormals.length = 0;
    }
    THREE.ColorCube.prototype.drawFaceNormals = function (scale, color) {
        this.clearFaceNormals();
        scale = (scale === undefined) ? 1 : scale;
        color = (color === undefined) ? 0xffaa00 : color;
        var origin = new THREE.Vector3(),
            normalArrow = null,
            vertices = [new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3()],
            normals = [new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3()],
            indices = [0, 0, 0],
            centroid = new THREE.Vector3(),
            faceNormal = new THREE.Vector3(),
            vertexArray = this.geometry.attributes.position.array,
            normalArray = this.geometry.attributes.normal.array,
            indexArray = this.geometry.index.array;

        for (var i = 0, len = indexArray.length; i < len; i += 3) {
            indices = indexArray.slice(i, i + 3);

            vertices[0].set(...vertexArray.slice((indices[0] * 3), (indices[0] * 3) + 3)).applyMatrix4(this.matrix);
            vertices[1].set(...vertexArray.slice((indices[1] * 3), (indices[1] * 3) + 3)).applyMatrix4(this.matrix);
            vertices[2].set(...vertexArray.slice((indices[2] * 3), (indices[2] * 3) + 3)).applyMatrix4(this.matrix);

            normals[0].set(...normalArray.slice((indices[0] * 3), (indices[0] * 3) + 3));
            normals[1].set(...normalArray.slice((indices[1] * 3), (indices[1] * 3) + 3));
            normals[2].set(...normalArray.slice((indices[2] * 3), (indices[2] * 3) + 3));

            centroid.set(
                (vertices[0].x + vertices[1].x + vertices[2].x) / 3,
                (vertices[0].y + vertices[1].y + vertices[2].y) / 3,
                (vertices[0].z + vertices[1].z + vertices[2].z) / 3
            );

            faceNormal.set(
                (normals[0].x + normals[1].x + normals[2].x) / 3,
                (normals[0].y + normals[1].y + normals[2].y) / 3,
                (normals[0].z + normals[1].z + normals[2].z) / 3
            );
            faceNormal.normalize();

            normalArrow = new THREE.ArrowHelper(
                faceNormal,
                origin,
                1 * scale,
                color,
                0.2 * scale,
                0.1 * scale
            );

            normalArrow.position.copy(centroid);

            this.fNormals.push(normalArrow);
            this.parent.add(normalArrow);
        }
    };

    THREE.ColorCube.prototype.clearAllNormals = function () {
        THREE.ColorCube.prototype.clearVertexNormals();
        THREE.ColorCube.prototype.clearFaceNormals();
    }

    THREE.ColorCube.prototype.drawWireframe = function (color) {
        if (this.wireframe === undefined) {
            color = (color === undefined) ? 0 : color;
            this.wireframe = new THREE.WireframeHelper(this, color);
            this.parent.add(this.wireframe);
        }
    }

    THREE.ColorCube.prototype.clearWireframe = function () {
        if (this.wireframe) {
            this.parent.remove(this.wireframe);
            delete this.wireframe;
        }
    }

})();

var cc = new THREE.ColorCube(25, 25, 25);
scene.add(cc);

cc.drawVertexNormals(25);
cc.drawFaceNormals(25);
cc.drawWireframe(0xffffff);
draw();

As part of prototyping some debugger objects and methods, I created a simple cube with a different color on each side. Rather than creating multiple meshes, I decided to use draw groups and THREE.Multimaterial. Unfortunately, it's only half-working, and I don't understand why.

What IS working is the first two sides (4 triangles). What's NOT working is any of the other sides. None of the other sides are visible. I've added debug code to draw the (index-based) vertex normals, the (index-based, manually calculated) face normals, and the wireframe (THREE.WireframeHelper).

If I increase the count for the second group to 9, nothing happens. If I change the groups to reference different start/count values within the first 8 vertices, those changes work as expected. Doing anything above 8th vertex has no effect.

I've also checked that the drawRange is set to draw from 0 to Infinity. I've also ruled out typos in my data, because otherwise the normals and wireframe wouldn't work. Is there anything else I'm missing? Thanks!

(I found the issue in r76. Code below referenced r79 at the time of writing.)

jsfiddle: http://jsfiddle.net/TheJim01/gumftkm4/

HTML:

<script src="http://threejs.org/build/three.js"></script>
<script src="http://threejs.org/examples/js/controls/TrackballControls.js"></script>
<script src="http://threejs.org/examples/js/libs/stats.min.js"></script>
<div id="host"></div>

<script>
// INITIALIZE
var WIDTH = window.innerWidth,
    HEIGHT = window.innerHeight,
    FOV = 35,
    NEAR = 1,
    FAR = 1000;

var renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(WIDTH, HEIGHT);
document.getElementById('host').appendChild(renderer.domElement);

var stats= new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0';
document.body.appendChild(stats.domElement);


var camera = new THREE.PerspectiveCamera(FOV, WIDTH / HEIGHT, NEAR, FAR);
camera.position.z = 250;

var trackballControl = new THREE.TrackballControls(camera, renderer.domElement);
trackballControl.rotateSpeed = 5.0; // need to speed it up a little

var scene = new THREE.Scene();

var light = new THREE.PointLight(0xffffff, 1, Infinity);
light.position.copy(camera.position);

scene.add(light);

function draw(){
    light.position.copy(camera.position);
    renderer.render(scene, camera);
  stats.update();
}
trackballControl.addEventListener('change', draw);

function navStartHandler(e) {
  renderer.domElement.addEventListener('mousemove', navMoveHandler);
  renderer.domElement.addEventListener('mouseup', navEndHandler);
}
function navMoveHandler(e) {
  trackballControl.update();
}
function navEndHandler(e) {
  renderer.domElement.removeEventListener('mousemove', navMoveHandler);
  renderer.domElement.removeEventListener('mouseup', navEndHandler);
}

renderer.domElement.addEventListener('mousedown', navStartHandler);
renderer.domElement.addEventListener('mousewheel', navMoveHandler);
</script>

CSS:

html *{
    padding: 0;
    margin: 0;
    width: 100%;
    overflow: hidden;
}

#host {
    width: 100%;
    height: 100%;
}

JavaScript:

// New Color Cube
(function () {

    var pos = new Float32Array([
        // front
        -1, 1, 1,
        -1, -1, 1,
        1, 1, 1,
        1, -1, 1,
        // right
        1, 1, 1,
        1, -1, 1,
        1, 1, -1,
        1, -1, -1,
        // back
        1, 1, -1,
        1, -1, -1,
        -1, 1, -1,
        -1, -1, -1,
        // left
        -1, 1, -1,
        -1, -1, -1,
        -1, 1, 1,
        -1, -1, 1,
        // top
        -1, 1, -1,
        -1, 1, 1,
        1, 1, -1,
        1, 1, 1,
        // bottom
        -1, -1, 1,
        -1, -1, -1,
        1, -1, 1,
        1, -1, -1
    ]),
    nor = new Float32Array([
        // front
        0, 0, 1,
        0, 0, 1,
        0, 0, 1,
        0, 0, 1,
        // right
        1, 0, 0,
        1, 0, 0,
        1, 0, 0,
        1, 0, 0,
        // back
        0, 0, -1,
        0, 0, -1,
        0, 0, -1,
        0, 0, -1,
        // left
        -1, 0, 0,
        -1, 0, 0,
        -1, 0, 0,
        -1, 0, 0,
        // top
        0, 1, 0,
        0, 1, 0,
        0, 1, 0,
        0, 1, 0,
        // bottom
        0, -1, 0,
        0, -1, 0,
        0, -1, 0,
        0, -1, 0
    ]),
    idx = new Uint32Array([
        // front
        0, 1, 2,
        3, 2, 1,
        // right
        4, 5, 6,
        7, 6, 5,
        // back
        8, 9, 10,
        11, 10, 9,
        // left
        12, 13, 14,
        15, 14, 13,
        // top
        16, 17, 18,
        19, 18, 17,
        // bottom
        20, 21, 22,
        23, 22, 21
    ]);

    var sideColors = new THREE.MultiMaterial([
        new THREE.MeshLambertMaterial({ color: 'red' }), // front
        new THREE.MeshLambertMaterial({ color: 'green' }), // right
        new THREE.MeshLambertMaterial({ color: 'orange' }), // back
        new THREE.MeshLambertMaterial({ color: 'blue' }), // left
        new THREE.MeshLambertMaterial({ color: 'white' }), // top
        new THREE.MeshLambertMaterial({ color: 'yellow' }) // bottom
    ]);

    var cubeGeometry = new THREE.BufferGeometry();
    cubeGeometry.addAttribute("position", new THREE.BufferAttribute(pos, 3));
    cubeGeometry.addAttribute("normal", new THREE.BufferAttribute(nor, 3));
    cubeGeometry.setIndex(new THREE.BufferAttribute(idx, 3));
    cubeGeometry.clearGroups();
    cubeGeometry.addGroup(0, 6, 0);
    cubeGeometry.addGroup(6, 6, 1);
    cubeGeometry.addGroup(12, 6, 2);
    cubeGeometry.addGroup(18, 6, 3);
    cubeGeometry.addGroup(24, 6, 4);
    cubeGeometry.addGroup(30, 6, 5);

    THREE.ColorCube = function (scaleX, scaleY, scaleZ) {
        THREE.Mesh.call(this, cubeGeometry, sideColors);
        var scaler = new THREE.Matrix4().makeScale(scaleX, scaleY, scaleZ);
        this.applyMatrix(scaler);
    };
    THREE.ColorCube.prototype = Object.create(THREE.Mesh.prototype);
    THREE.ColorCube.prototype.constructor = THREE.ColorCube;

    THREE.ColorCube.prototype.clearVertexNormals = function () {
        if (this.vNormals === undefined) {
            this.vNormals = [];
        }
        for (var i = 0, len = this.vNormals.length; i < len; ++i) {
            this.parent.remove(this.vNormals[i]);
        }
        this.vNormals.length = 0;
    }
    THREE.ColorCube.prototype.drawVertexNormals = function (scale, color) {
        this.clearVertexNormals();
        scale = (scale === undefined) ? 1 : scale;
        color = (color === undefined) ? 0xff : color;
        var origin = new THREE.Vector3(),
            normalArrow = null,
            vert = null,
            norm = null,
            index = null,
            vertexArray = this.geometry.attributes.position.array,
            normalArray = this.geometry.attributes.normal.array,
            indexArray = this.geometry.index.array;

        for (var i = 0, len = indexArray.length; i < len; ++i) {
            index = indexArray[i];
            vert = new THREE.Vector3(...vertexArray.slice((index * 3), (index * 3) + 3)).applyMatrix4(this.matrix);
            norm = new THREE.Vector3(...normalArray.slice((index * 3), (index * 3) + 3));

            normalArrow = new THREE.ArrowHelper(
                norm,
                origin,
                1 * scale,
                color,
                0.2 * scale,
                0.1 * scale
            );

            normalArrow.position.copy(vert);

            this.vNormals.push(normalArrow);
            this.parent.add(normalArrow);
        }
    };

    THREE.ColorCube.prototype.clearFaceNormals = function () {
        if (this.fNormals === undefined) {
            this.fNormals = [];
        }
        for (var i = 0, len = this.fNormals.length; i < len; ++i) {
            this.parent.remove(this.fNormals[i]);
        }
        this.fNormals.length = 0;
    }
    THREE.ColorCube.prototype.drawFaceNormals = function (scale, color) {
        this.clearFaceNormals();
        scale = (scale === undefined) ? 1 : scale;
        color = (color === undefined) ? 0xffaa00 : color;
        var origin = new THREE.Vector3(),
            normalArrow = null,
            vertices = [new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3()],
            normals = [new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3()],
            indices = [0, 0, 0],
            centroid = new THREE.Vector3(),
            faceNormal = new THREE.Vector3(),
            vertexArray = this.geometry.attributes.position.array,
            normalArray = this.geometry.attributes.normal.array,
            indexArray = this.geometry.index.array;

        for (var i = 0, len = indexArray.length; i < len; i += 3) {
            indices = indexArray.slice(i, i + 3);

            vertices[0].set(...vertexArray.slice((indices[0] * 3), (indices[0] * 3) + 3)).applyMatrix4(this.matrix);
            vertices[1].set(...vertexArray.slice((indices[1] * 3), (indices[1] * 3) + 3)).applyMatrix4(this.matrix);
            vertices[2].set(...vertexArray.slice((indices[2] * 3), (indices[2] * 3) + 3)).applyMatrix4(this.matrix);

            normals[0].set(...normalArray.slice((indices[0] * 3), (indices[0] * 3) + 3));
            normals[1].set(...normalArray.slice((indices[1] * 3), (indices[1] * 3) + 3));
            normals[2].set(...normalArray.slice((indices[2] * 3), (indices[2] * 3) + 3));

            centroid.set(
                (vertices[0].x + vertices[1].x + vertices[2].x) / 3,
                (vertices[0].y + vertices[1].y + vertices[2].y) / 3,
                (vertices[0].z + vertices[1].z + vertices[2].z) / 3
            );

            faceNormal.set(
                (normals[0].x + normals[1].x + normals[2].x) / 3,
                (normals[0].y + normals[1].y + normals[2].y) / 3,
                (normals[0].z + normals[1].z + normals[2].z) / 3
            );
            faceNormal.normalize();

            normalArrow = new THREE.ArrowHelper(
                faceNormal,
                origin,
                1 * scale,
                color,
                0.2 * scale,
                0.1 * scale
            );

            normalArrow.position.copy(centroid);

            this.fNormals.push(normalArrow);
            this.parent.add(normalArrow);
        }
    };

    THREE.ColorCube.prototype.clearAllNormals = function () {
        THREE.ColorCube.prototype.clearVertexNormals();
        THREE.ColorCube.prototype.clearFaceNormals();
    }

    THREE.ColorCube.prototype.drawWireframe = function (color) {
        if (this.wireframe === undefined) {
            color = (color === undefined) ? 0 : color;
            this.wireframe = new THREE.WireframeHelper(this, color);
            this.parent.add(this.wireframe);
        }
    }

    THREE.ColorCube.prototype.clearWireframe = function () {
        if (this.wireframe) {
            this.parent.remove(this.wireframe);
            delete this.wireframe;
        }
    }

})();

var cc = new THREE.ColorCube(25, 25, 25);
scene.add(cc);

cc.drawVertexNormals(25);
cc.drawFaceNormals(25);
cc.drawWireframe(0xffffff);
draw();

原文:https://stackoverflow.com/questions/38775928
更新时间:2023-10-01 12:10

最满意答案

答案给了你更多的问题

所有它的“扩展”hstore实际上可以存储JSON,而不仅仅是键值所以这个结构也行:

{"key":{"inner_object_key":{"Another_key":"Done!","list":["no","problem"]}}}

所以,首先你的ModelView应该使用自定义转换器

class ExtendedModelView(ModelView):
   model_form_converter=CustomAdminConverter

转换器本身应该知道如何使用hstore方言:

class CustomAdminConverter(AdminModelConverter):
    @converts('sqlalchemy.dialects.postgresql.hstore.HSTORE')
    def conv_HSTORE(self, field_args, **extra):
        return DictToHstoreField(**field_args)

您可以看到这一个使用自定义的WTForms字段,可以在两个方向上转换数据:

class DictToHstoreField(TextAreaField):
    def process_data(self, value):
        if value is None:
            value = {}
        else:
            for key,obj in value.iteritems():
                if (obj.startswith("{") and obj.endswith("}")) or (obj.startswith("[") and obj.endswith("]")):
                    try:
                        value[key]=json.loads(obj)
                    except:
                        pass #

        self.data=json.dumps(value)

    def process_formdata(self, valuelist):
        if valuelist:
            self.data = json.loads(valuelist[0])
            for key,obj in self.data.iteritems():
                if isinstance(obj,dict) or isinstance(obj,list):
                    self.data[key]=json.dumps(obj)
                if isinstance(obj,int):
                    self.data[key]=str(obj)

最后一步将是在应用程序中实际使用这些数据

对于SQLalchemy而言,我并没有把它做成一个很好的方式,因为它被用在了安静的环境中,所以我只在一个方向上采用这种方式,但我认为很容易从这里获得想法,然后完成剩下的工作。

如果你的情况是简单的键值存储,所以不应该做任何额外的事情,只要按原样使用即可。 但是如果你想在代码中的某个地方打开JSON,只要使用它就很简单,只需要在函数中包装即可

 if (value.startswith("{") and value.endswith("}")) or (value.startswith("[") and value.endswith("]")):
        value=json.loads(value)

通过扩展FormField并添加一些用于添加/删除字段的javascript,为实际的非JSON方法创建动态字段也是可能的,但这是完全不同的故事,在我的情况下,我需要实际的json存储,带有二十一点和列表: )


The answer gives you a bit more then asked

Fist of all it "extends" hstore to be able to store actually JSON, not just key-value So this structure is also OK:

{"key":{"inner_object_key":{"Another_key":"Done!","list":["no","problem"]}}}

So, first of all your ModelView should use custom converter

class ExtendedModelView(ModelView):
   model_form_converter=CustomAdminConverter

Converter itself should know how to use hstore dialect:

class CustomAdminConverter(AdminModelConverter):
    @converts('sqlalchemy.dialects.postgresql.hstore.HSTORE')
    def conv_HSTORE(self, field_args, **extra):
        return DictToHstoreField(**field_args)

This one as you can see uses custom WTForms field which converts data in both directions:

class DictToHstoreField(TextAreaField):
    def process_data(self, value):
        if value is None:
            value = {}
        else:
            for key,obj in value.iteritems():
                if (obj.startswith("{") and obj.endswith("}")) or (obj.startswith("[") and obj.endswith("]")):
                    try:
                        value[key]=json.loads(obj)
                    except:
                        pass #

        self.data=json.dumps(value)

    def process_formdata(self, valuelist):
        if valuelist:
            self.data = json.loads(valuelist[0])
            for key,obj in self.data.iteritems():
                if isinstance(obj,dict) or isinstance(obj,list):
                    self.data[key]=json.dumps(obj)
                if isinstance(obj,int):
                    self.data[key]=str(obj)

The final step will be to actual use this data in application

I did not make it in common nice way for SQLalchemy, since was used with flask-restful, so I have only adoption for flask-restful in one direction, but I think it's easy to get the idea from here and do the rest.

And if your case is simple key-value storage so nothing additionaly should be done, just use it as is. But if you want to unwrap JSON somewhere in code, it's simple like this whenever you use it, just wrap in function

 if (value.startswith("{") and value.endswith("}")) or (value.startswith("[") and value.endswith("]")):
        value=json.loads(value)

Creating dynamical field for actual nice non-JSON way for editing of data also possible by extending FormField and adding some javascript for adding/removing fields, but this is whole different story, in my case I needed actual json storage, with blackjack and lists :)

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)