我有以下代码来创建一个内存zip文件,该文件抛出在Python 3中运行的错误.
from io import StringIO
from pprint import pprint
import zipfile
in_memory_data = StringIO()
in_memory_zip = zipfile.ZipFile(
in_memory_data, "w", zipfile.ZIP_DEFLATED, False)
in_memory_zip.debug = 3
filename_in_zip = 'test_filename.txt'
file_contents = 'asdf'
in_memory_zip.writestr(filename_in_zip, file_contents)
Run Code Online (Sandbox Code Playgroud)
要清楚这只是一个Python 3问题.我可以在Python 2上运行良好的代码.确切地说,我使用的是Python 3.4.3.堆栈跟踪如下:
Traceback (most recent call last):
File "in_memory_zip_debug.py", line 14, in <module>
in_memory_zip.writestr(filename_in_zip, file_contents)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/zipfile.py", line 1453, in writestr
self.fp.write(zinfo.FileHeader(zip64))
TypeError: string argument expected, got 'bytes'
Exception ignored in: <bound method ZipFile.__del__ of <zipfile.ZipFile object at 0x1006e1ef0>>
Traceback (most recent call last):
File …Run Code Online (Sandbox Code Playgroud) 我有一个Django表单向导,可以很好地创建我的一个模型的内容.我想使用相同的向导来编辑现有内容的数据,但无法找到如何执行此操作的良好示例.
这是我的项目代码的简化版本:
forms.py
class ProjectEssentialsForm(forms.ModelForm):
class Meta:
model = Project
fields = [
'title',
'short_description',
'who_description',
'problem_description',
'solution_description'
]
class ProjectYourInfoForm(forms.ModelForm):
class Meta:
model = Project
fields = [
'gender',
'location',
'post_code',
'sector',
]
Run Code Online (Sandbox Code Playgroud)
views.py
TEMPLATES = {
'project_essentials': 'projects/essentials-form.html',
'project_your_info': 'projects/your-info-form.html',
}
class ProjectWizard(SessionWizardView):
instance = None
def get_form_instance(self, step):
"""
Provides us with an instance of the Project Model to save on completion
"""
if self.instance is None:
self.instance = Project()
return self.instance
def done(self, form_list, **kwargs):
""" …Run Code Online (Sandbox Code Playgroud) 我有以下C程序,需要与Python集成:
#include <Python.h>
PyObject* get_details(){
PyObject *details = PyDict_New();
PyObject *key, *value;
key = PyUnicode_FromString("full name");
value = PyUnicode_FromString("Pete Graham");
PyDict_SetItem(details, key, value);
return details;
}
Run Code Online (Sandbox Code Playgroud)
我可以使用以下命令在OS X上编译程序:
gcc -I /Library/Frameworks/Python.framework/Versions/3.4/Headers \
-L /Library/Frameworks/Python.framework/Versions/3.4/lib \
-lpython3.4 get_person_dict.c
Run Code Online (Sandbox Code Playgroud)
尝试在Ubuntu上编译程序时出现错误 /usr/bin/ld: cannot find -lpython3.4.
这是我在Ubuntu上使用的命令,我已经尝试了python lib路径的各种值。
gcc -I /usr/include/python3.4 \
-L /usr/local/lib \
-lpython3.4 get_person_dict.c
Run Code Online (Sandbox Code Playgroud)
我安装sudo apt-get install python3.4-dev了版本为Ubuntu trusty64的python,并在Vagrant上使用。
我想使用Django ORM返回30个项目,即使该模型的数据库中少于30个.有没有办法强制它返回这么多项目,即使它意味着返回重复项?
projects = Project.objects.filter(approved=True).order_by('?')[0:30]
Run Code Online (Sandbox Code Playgroud)
这可能吗?上面的代码返回4个项目,因为这是我在数据库中的数量.
更好的方法是操纵项目变量以使其包含30个项目吗?我希望这些项目随机化.