我想提供两种不同的序列化器,并且能够从ModelViewSet的所有功能中受益:

当查看对象列表时,我希望每个对象都有一个url,该url重定向到其详细信息,并且每个其他关系都使用目标模型的__unicode __出现;

例子:

{
  "url": "http://127.0.0.1:8000/database/gruppi/2/",
  "nome": "universitari",
  "descrizione": "unitn!",
  "creatore": "emilio",
  "accesso": "CHI",
  "membri": [
    "emilio",
    "michele",
    "luisa",
    "ivan",
    "saverio"
  ]
}

在查看对象的详细信息时,我希望使用默认的HyperlinkedModelSerializer

例子:

{
  "url": "http://127.0.0.1:8000/database/gruppi/2/",
  "nome": "universitari",
  "descrizione": "unitn!",
  "creatore": "http://127.0.0.1:8000/database/utenti/3/",
  "accesso": "CHI",
  "membri": [
    "http://127.0.0.1:8000/database/utenti/3/",
    "http://127.0.0.1:8000/database/utenti/4/",
    "http://127.0.0.1:8000/database/utenti/5/",
    "http://127.0.0.1:8000/database/utenti/6/",
    "http://127.0.0.1:8000/database/utenti/7/"
  ]
}

我通过以下方法做到了这一切:

serializers.py

# serializer to use when showing a list
class ListaGruppi(serializers.HyperlinkedModelSerializer):
    membri = serializers.RelatedField(many = True)
    creatore = serializers.RelatedField(many = False)

    class Meta:
        model = models.Gruppi

# serializer to use when showing the details
class DettaglioGruppi(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = models.Gruppi

views.py

class DualSerializerViewSet(viewsets.ModelViewSet):
    """
    ViewSet providing different serializers for list and detail views.

    Use list_serializer and detail_serializer to provide them
    """
    def list(self, *args, **kwargs):
        self.serializer_class = self.list_serializer
        return viewsets.ModelViewSet.list(self, *args, **kwargs)

    def retrieve(self, *args, **kwargs):
        self.serializer_class = self.detail_serializer
        return viewsets.ModelViewSet.retrieve(self, *args, **kwargs)

class GruppiViewSet(DualSerializerViewSet):
    model = models.Gruppi
    list_serializer = serializers.ListaGruppi
    detail_serializer = serializers.DettaglioGruppi

    # etc.

基本上,我检测用户何时请求列表视图或详细视图,并更改serializer_class以满足我的需要。但我对这段代码并不满意,它看起来像一个肮脏的黑客,最重要的是,如果两个用户同时请求一个列表和一个细节怎么办?

是否有更好的方法来实现这个使用ModelViewSets或我必须返回使用GenericAPIView?

编辑: 下面是如何使用一个自定义的基础ModelViewSet:

class MultiSerializerViewSet(viewsets.ModelViewSet):
    serializers = { 
        'default': None,
    }

    def get_serializer_class(self):
            return self.serializers.get(self.action,
                        self.serializers['default'])

class GruppiViewSet(MultiSerializerViewSet):
    model = models.Gruppi

    serializers = {
        'list':    serializers.ListaGruppi,
        'detail':  serializers.DettaglioGruppi,
        # etc.
    }

我使用Python 2从ASCII编码的文本文件解析JSON。

当用json或simplejson加载这些文件时,我的所有字符串值都转换为Unicode对象而不是字符串对象。问题是,我必须将数据与一些只接受字符串对象的库一起使用。我不能更改库也不能更新它们。

是否有可能获得字符串对象而不是Unicode对象?

例子

>>> import json
>>> original_list = ['a', 'b']
>>> json_list = json.dumps(original_list)
>>> json_list
'["a", "b"]'
>>> new_list = json.loads(json_list)
>>> new_list
[u'a', u'b']  # I want these to be of type `str`, not `unicode`

(2017年一个简单而干净的解决方案是使用最新版本的Python——即Python 3和更高版本。)

这是我的错误:

(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install lxml
Downloading/unpacking lxml
  Running setup.py egg_info for package lxml
    Building lxml version 2.3.
    Building without Cython.
    ERROR: /bin/sh: xslt-config: not found

    ** make sure the development packages of libxml2 and libxslt are installed **

    Using build configuration of libxslt
Installing collected packages: lxml
  Running setup.py install for lxml
    Building lxml version 2.3.
    Building without Cython.
    ERROR: /bin/sh: xslt-config: not found

    ** make sure the development packages of libxml2 and libxslt are installed **

    Using build configuration of libxslt
    building 'lxml.etree' extension
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.6 -c src/lxml/lxml.etree.c -o build/temp.linux-i686-2.6/src/lxml/lxml.etree.o -w
    src/lxml/lxml.etree.c:4: fatal error: Python.h: 没有那个文件或目录
    compilation terminated.
    error: command 'gcc' failed with exit status 1
    Complete output from command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/lxml/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-jOhgvD-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6:
    Building lxml version 2.3.

Building without Cython.

ERROR: /bin/sh: xslt-config: not found



** make sure the development packages of libxml2 and libxslt are installed **



Using build configuration of libxslt

running install

running build

running build_py

running build_ext

building 'lxml.etree' extension

gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.6 -c src/lxml/lxml.etree.c -o build/temp.linux-i686-2.6/src/lxml/lxml.etree.o -w

src/lxml/lxml.etree.c:4: fatal error: Python.h: 没有那个文件或目录

compilation terminated.

error: command 'gcc' failed with exit status 1

----------------------------------------
Command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/lxml/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-jOhgvD-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6 failed with error code 1
Storing complete log in /home/zjm1126/.pip/pip.log

我该怎么办?

更新:

(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install lxml
Downloading/unpacking lxml
  Running setup.py egg_info for package lxml
    Building lxml version 2.3.
    Building without Cython.
    Using build configuration of libxslt 1.1.26
    Building against libxml2/libxslt in the following directory: /usr/lib
Installing collected packages: lxml
  Running setup.py install for lxml
    Building lxml version 2.3.
    Building without Cython.
    Using build configuration of libxslt 1.1.26
    Building against libxml2/libxslt in the following directory: /usr/lib
    building 'lxml.etree' extension
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/libxml2 -I/usr/include/python2.6 -c src/lxml/lxml.etree.c -o build/temp.linux-i686-2.6/src/lxml/lxml.etree.o -w
    src/lxml/lxml.etree.c:4: fatal error: Python.h: 没有那个文件或目录
    compilation terminated.
    error: command 'gcc' failed with exit status 1
    Complete output from command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/lxml/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-NJw2ws-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6:
    Building lxml version 2.3.

Building without Cython.

Using build configuration of libxslt 1.1.26

Building against libxml2/libxslt in the following directory: /usr/lib

running install

running build

running build_py

running build_ext

building 'lxml.etree' extension

gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/libxml2 -I/usr/include/python2.6 -c src/lxml/lxml.etree.c -o build/temp.linux-i686-2.6/src/lxml/lxml.etree.o -w

src/lxml/lxml.etree.c:4: fatal error: Python.h: 没有那个文件或目录

compilation terminated.

error: command 'gcc' failed with exit status 1

----------------------------------------
Command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/lxml/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-NJw2ws-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6 failed with error code 1
Storing complete log in /home/zjm1126/.pip/pip.log

日志:

------------------------------------------------------------
/home/zjm1126/zjm_test/mysite/bin/pip run on Thu Mar  3 17:07:27 2011
Downloading/unpacking mysql-python
  Running setup.py egg_info for package mysql-python
    running egg_info
    creating pip-egg-info/MySQL_python.egg-info
    writing pip-egg-info/MySQL_python.egg-info/PKG-INFO
    writing top-level names to pip-egg-info/MySQL_python.egg-info/top_level.txt
    writing dependency_links to pip-egg-info/MySQL_python.egg-info/dependency_links.txt
    writing pip-egg-info/MySQL_python.egg-info/PKG-INFO
    writing top-level names to pip-egg-info/MySQL_python.egg-info/top_level.txt
    writing dependency_links to pip-egg-info/MySQL_python.egg-info/dependency_links.txt
    writing manifest file 'pip-egg-info/MySQL_python.egg-info/SOURCES.txt'
    warning: manifest_maker: standard file '-c' not found
    reading manifest file 'pip-egg-info/MySQL_python.egg-info/SOURCES.txt'
    reading manifest template 'MANIFEST.in'
    warning: no files found matching 'MANIFEST'
    warning: no files found matching 'ChangeLog'
    warning: no files found matching 'GPL'
    writing manifest file 'pip-egg-info/MySQL_python.egg-info/SOURCES.txt'
Installing collected packages: mysql-python
  Running setup.py install for mysql-python
    Running command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-XuVIux-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6
    running install
    running build
    running build_py
    creating build
    creating build/lib.linux-i686-2.6
    copying _mysql_exceptions.py -> build/lib.linux-i686-2.6
    creating build/lib.linux-i686-2.6/MySQLdb
    copying MySQLdb/__init__.py -> build/lib.linux-i686-2.6/MySQLdb
    copying MySQLdb/converters.py -> build/lib.linux-i686-2.6/MySQLdb
    copying MySQLdb/connections.py -> build/lib.linux-i686-2.6/MySQLdb
    copying MySQLdb/cursors.py -> build/lib.linux-i686-2.6/MySQLdb
    copying MySQLdb/release.py -> build/lib.linux-i686-2.6/MySQLdb
    copying MySQLdb/times.py -> build/lib.linux-i686-2.6/MySQLdb
    creating build/lib.linux-i686-2.6/MySQLdb/constants
    copying MySQLdb/constants/__init__.py -> build/lib.linux-i686-2.6/MySQLdb/constants
    copying MySQLdb/constants/CR.py -> build/lib.linux-i686-2.6/MySQLdb/constants
    copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-i686-2.6/MySQLdb/constants
    copying MySQLdb/constants/ER.py -> build/lib.linux-i686-2.6/MySQLdb/constants
    copying MySQLdb/constants/FLAG.py -> build/lib.linux-i686-2.6/MySQLdb/constants
    copying MySQLdb/constants/REFRESH.py -> build/lib.linux-i686-2.6/MySQLdb/constants
    copying MySQLdb/constants/CLIENT.py -> build/lib.linux-i686-2.6/MySQLdb/constants
    running build_ext
    building '_mysql' extension
    creating build/temp.linux-i686-2.6
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,3,'final',0) -D__version__=1.2.3 -I/usr/include/mysql -I/usr/include/python2.6 -c _mysql.c -o build/temp.linux-i686-2.6/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -DUNIV_LINUX -DUNIV_LINUX
    In file included from _mysql.c:29:
    pymemcompat.h:10: fatal error: Python.h: 没有那个文件或目录
    compilation terminated.
    error: command 'gcc' failed with exit status 1
    Complete output from command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-XuVIux-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6:
    running install

running build

running build_py

creating build

creating build/lib.linux-i686-2.6

copying _mysql_exceptions.py -> build/lib.linux-i686-2.6

creating build/lib.linux-i686-2.6/MySQLdb

copying MySQLdb/__init__.py -> build/lib.linux-i686-2.6/MySQLdb

copying MySQLdb/converters.py -> build/lib.linux-i686-2.6/MySQLdb

copying MySQLdb/connections.py -> build/lib.linux-i686-2.6/MySQLdb

copying MySQLdb/cursors.py -> build/lib.linux-i686-2.6/MySQLdb

copying MySQLdb/release.py -> build/lib.linux-i686-2.6/MySQLdb

copying MySQLdb/times.py -> build/lib.linux-i686-2.6/MySQLdb

creating build/lib.linux-i686-2.6/MySQLdb/constants

copying MySQLdb/constants/__init__.py -> build/lib.linux-i686-2.6/MySQLdb/constants

copying MySQLdb/constants/CR.py -> build/lib.linux-i686-2.6/MySQLdb/constants

copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-i686-2.6/MySQLdb/constants

copying MySQLdb/constants/ER.py -> build/lib.linux-i686-2.6/MySQLdb/constants

copying MySQLdb/constants/FLAG.py -> build/lib.linux-i686-2.6/MySQLdb/constants

copying MySQLdb/constants/REFRESH.py -> build/lib.linux-i686-2.6/MySQLdb/constants

copying MySQLdb/constants/CLIENT.py -> build/lib.linux-i686-2.6/MySQLdb/constants

running build_ext

building '_mysql' extension

creating build/temp.linux-i686-2.6

gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,3,'final',0) -D__version__=1.2.3 -I/usr/include/mysql -I/usr/include/python2.6 -c _mysql.c -o build/temp.linux-i686-2.6/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -DUNIV_LINUX -DUNIV_LINUX

In file included from _mysql.c:29:

pymemcompat.h:10: fatal error: Python.h: 没有那个文件或目录

compilation terminated.

error: command 'gcc' failed with exit status 1

----------------------------------------
Command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-XuVIux-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6 failed with error code 1
Exception information:
Traceback (most recent call last):
  File "/home/zjm1126/zjm_test/mysite/lib/python2.6/site-packages/pip-0.8.1-py2.6.egg/pip/basecommand.py", line 130, in main
    self.run(options, args)
  File "/home/zjm1126/zjm_test/mysite/lib/python2.6/site-packages/pip-0.8.1-py2.6.egg/pip/commands/install.py", line 228, in run
    requirement_set.install(install_options, global_options)
  File "/home/zjm1126/zjm_test/mysite/lib/python2.6/site-packages/pip-0.8.1-py2.6.egg/pip/req.py", line 1043, in install
    requirement.install(install_options, global_options)
  File "/home/zjm1126/zjm_test/mysite/lib/python2.6/site-packages/pip-0.8.1-py2.6.egg/pip/req.py", line 559, in install
    cwd=self.source_dir, filter_stdout=self._filter_install, show_stdout=False)
  File "/home/zjm1126/zjm_test/mysite/lib/python2.6/site-packages/pip-0.8.1-py2.6.egg/pip/__init__.py", line 249, in call_subprocess
    % (command_desc, proc.returncode))
InstallationError: Command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-XuVIux-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6 failed with error code 1

我用unsigned user_id创建了一个迁移。我如何编辑user_id在一个新的迁移,也使它为空()?

Schema::create('throttle', function(Blueprint $table)
{
    $table->increments('id');
    // this needs to also be nullable, how should the next migration be?
    $table->integer('user_id')->unsigned();
}

Apache Thrift和谷歌的协议缓冲区最大的优点和缺点是什么?

  Bitmap bmp   = intent.getExtras().get("data");
  int size     = bmp.getRowBytes() * bmp.getHeight();
  ByteBuffer b = ByteBuffer.allocate(size);

  bmp.copyPixelsToBuffer(b);

  byte[] bytes = new byte[size];

  try {
     b.get(bytes, 0, bytes.length);
  } catch (BufferUnderflowException e) {
     // always happens
  }
  // do something with byte[]

当我在调用copyPixelsToBuffer后查看缓冲区时,字节都是0…从相机返回的位图是不可变的…但这不重要,因为它正在复制。

这段代码可能有什么问题?

如何在IntelliJ IDEA中生成这个值?

我去设置->错误-> Serialization问题-> Serializable类没有' serialVersionUID ',但它仍然没有显示警告。我的类PKladrBuilding父类实现了接口Serializable。

部分代码:

public class PKladrBuilding extends PRQObject

public abstract class PRQObject extends PObject

public abstract class PObject implements Serializable

我正在为朋友构建一个小型聊天应用程序,但不确定如何及时获取信息,而不是像强制刷新页面那样手动或基本。

目前,我正在使用简单的AJAX实现这一点,但这有一个缺点,即在短计时器过去时定期撞击服务器。

在研究长/短轮询时,我遇到了HTML5 WebSockets。这似乎很容易实现,但我不确定是否有一些隐藏的缺点。例如,我认为只有某些浏览器支持WebSockets。WebSockets还有其他我应该注意的缺点吗?

既然这两种技术做的是同样的事情,那么在什么样的场景下人们会更喜欢使用其中一种而不是另一种呢?更具体地说,HTML5 WebSockets使AJAX长/短轮询过时了吗,或者有令人信服的理由更喜欢AJAX而不是WebSockets吗?

假设我有一个可序列化的类AppMessage。

我想通过套接字将它作为字节[]传输到另一台机器,在那里它从接收到的字节重建。

我怎么才能做到呢?

如何在PHP中计算两个日期时间之间的分钟差异?