我想知道如何直接在Django的模板中获取静态文件的绝对URL?
现在在我的模板中:
<link rel="stylesheet" href="{% static "css/bootstrap.min.css" %}">
Run Code Online (Sandbox Code Playgroud)
返回
<link rel="stylesheet" href="/static/css/bootstrap.min.css">
Run Code Online (Sandbox Code Playgroud)
我如何上开发:
<link rel="stylesheet" href="http://127.0.0.1:8000/static/css/bootstrap.min.css">
Run Code Online (Sandbox Code Playgroud)
在生产上
<link rel="stylesheet" href="https://mycompany.com/static/css/bootstrap.min.css">
Run Code Online (Sandbox Code Playgroud) 在构建HTTP响应时,Flask会替换我的Location标头的内容.它用绝对值改变我的实际相对URI Location标题.
@app.route('/votes', methods=['POST'])
def votes():
return jsonify(), 201, {'location': '/votes/1'}
Run Code Online (Sandbox Code Playgroud)
我的测试:
def test_vote_creation(self):
response = self.app.post('/votes',
data=json.dumps({
'name': 'Test vote'
}), content_type='application/json')
print(response.headers['location'])
Run Code Online (Sandbox Code Playgroud)
返回http://localhost/votes/1而不是/votes/1
如何使用Flask jsonify返回相对URI Location标头?
编辑:根据HTTP/1.1标准RFC 2616的当前版本,Location头的值必须是绝对URI.但RCF也将改为允许相对URI.因此,我想更改API的默认行为,以便在我的位置标头中使用相对URI进行回答.
这篇文章的更多细节
我尝试与XMLRPC api建立本地HTTPS连接.由于我升级到默认证书验证启用的 python 2.7.9,因此当我使用API时出现CERTIFICATE_VERIFY_FAILED错误
>>> test=xmlrpclib.ServerProxy('https://admin:bz15h9v9n@localhost:9999/API',verbose=False, use_datetime=True)
>>> test.list_satellites()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/xmlrpclib.py", line 1233, in __call__
return self.__send(self.__name, args)
File "/usr/local/lib/python2.7/xmlrpclib.py", line 1591, in __request
verbose=self.__verbose
File "/usr/local/lib/python2.7/xmlrpclib.py", line 1273, in request
return self.single_request(host, handler, request_body, verbose)
File "/usr/local/lib/python2.7/xmlrpclib.py", line 1301, in single_request
self.send_content(h, request_body)
File "/usr/local/lib/python2.7/xmlrpclib.py", line 1448, in send_content
connection.endheaders(request_body)
File "/usr/local/lib/python2.7/httplib.py", line 997, in endheaders
self._send_output(message_body)
File "/usr/local/lib/python2.7/httplib.py", line 850, in _send_output
self.send(msg)
File "/usr/local/lib/python2.7/httplib.py", line …Run Code Online (Sandbox Code Playgroud)
我的目标是在Django 1.5中创建自定义用户模型
# myapp.models.py
from django.contrib.auth.models import AbstractBaseUser
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
db_index=True,
)
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, blank=True)
company = models.ForeignKey('Company')
...
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['company']
Run Code Online (Sandbox Code Playgroud)
由于公司字段(models.ForeignKey('Company')(python manage.py createsuperuser),我
无法创建超级用户.我的问题:如何在没有公司的情况下为我的应用程序创建超级用户.我试图制作自定义MyUserManager但没有任何成功:
class MyUserManager(BaseUserManager):
...
def create_superuser(self, email, company=None, password):
"""
Creates and saves a superuser with the given email and password.
"""
user = self.create_user(
email,
password=password,
)
user.save(using=self._db)
return user
Run Code Online (Sandbox Code Playgroud)
或者我是否必须为此用户创建虚假公司?谢谢
我想知道如何检索文件的内容,保留FileReader对象的特殊字符.
<form enctype="multipart/form-data">
<input type="file" id="file" name="file">
</form>
Run Code Online (Sandbox Code Playgroud)
<script>
$('#file').change(function () {
var file = document.getElementById('file').files[0];
var reader = new FileReader();
reader.onload = function (event) {
var file_content = event.target.result;
console.log(file_content);
}
reader.readAsBinaryString(file);
}
</script>
Run Code Online (Sandbox Code Playgroud)
这段代码打印
"line1line2"
Run Code Online (Sandbox Code Playgroud)
除了我的文件内容是
line1
line2
Run Code Online (Sandbox Code Playgroud)
我怎样才能得到 ?
line1\nline2
Run Code Online (Sandbox Code Playgroud)
我尝试了readAsBinaryString和readAsText方法,没有任何成功.难道我做错了什么 ?谢谢
编辑:
关于JSfiddle http://jsfiddle.net/yTgp7/的一个例子

问题仅存在于mac Os X上的Firefox上
为了简化我的工作,我想从Python 2.7.6迁移到Python 2.7.9/2.7.10.
我需要证明我的Python 2.7.10不会破坏我的软件"使用"Python 2.7.6
我按照将python 2移植到python 3中描述的步骤进行了操作
我不能确定100%我的代码不会破坏,但我怎么能有信心?
例如,我是否应该查看2.7.6和2.7.10之间修复的所有Core和Builtins错误?如果我们使用这些方法,请搜索我的代码?
是否存在更好的策略?
100%的代码覆盖率是一个很好的解决方案,但是使用2.7.6和2.7.10之间的修改方法可能比50%覆盖率+ 100%代码更难获得测试.
我想将python脚本转换为javascript脚本.我的python脚本加载一个DLL并使用它的API.
processings2D = ctypes.CDLL('processings2D.dll')
print(processings2D.ImageProcessor2DCreate())
Run Code Online (Sandbox Code Playgroud)
我尝试使用node-gyp做同样的事情,但我的脚本找不到dll.
console.log(processings2D.ImageProcessor2DCreate());
^
TypeError: Cannot load processings2D.dll library
Run Code Online (Sandbox Code Playgroud)
test.js
var processings2D = require('./build/Release/processings2D.node');
console.log(processings2D.ImageProcessor2DCreate());
Run Code Online (Sandbox Code Playgroud)
addon.cc
#include <nan.h>
#include "processings2D/processings2D.h"
HINSTANCE hDLL = NULL;
typedef int(*Fn)();
void ImageProcessor2DCreate(const Nan::FunctionCallbackInfo<v8::Value>& info) {
hDLL = LoadLibrary("processings2D.dll");
if(!hDLL)
{
Nan::ThrowTypeError("Cannot load processings2D.dll library");
return;
}
Fn fn = (Fn)GetProcAddress(hDLL, "ImageProcessor2DCreate");
if (!fn) {
Nan::ThrowTypeError("Could not load ImageProcessor2DCreate function");
FreeLibrary(hDLL);
return;
}
info.GetReturnValue().Set(Nan::New(fn()));
}
void Init(v8::Local<v8::Object> exports) {
exports->Set(Nan::New("ImageProcessor2DCreate").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(ImageProcessor2DCreate)->GetFunction());
}
NODE_MODULE(twoD, Init)
Run Code Online (Sandbox Code Playgroud)
binding.gyp
{
"targets": [
{
"target_name": "processings2D", …Run Code Online (Sandbox Code Playgroud) 我使用 router.beforeEach 来保护一些视图。我在进入我的 vue 之前获取我的用户。我想在所有经过身份验证的页面中使用此用户。如何在我的 vuejs 组件的 router.beforeEach 中注入数据?
这是我的路线定义:
import Vue from 'vue';
import VueRouter from 'vue-router';
import AuthService from './services/AuthService';
import Index from './pages/Index.vue';
Vue.use(VueRouter);
const routes = [
{path: '/', name: 'index', component: Index, meta: {requiresAuth: true}},
...
];
const router = new VueRouter({
routes
});
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
AuthService().getUser(user => {
if (user) {
next(vm => {
vm.user = user
});
} else {
...
}
});
}
... …Run Code Online (Sandbox Code Playgroud) 从 Django 1.4(我认为)开始,当我启动项目时,django 会为我的项目创建一个文件夹。Django在项目文件夹的同一级别为我创建的任何应用程序(使用python manage.py startapp )添加一个文件夹。
Project_name
|---project_name_dir/
|---application_dir/
`---manage.py
Run Code Online (Sandbox Code Playgroud)
我非常喜欢以下文件夹结构:
Project_name
|---project_name_dir/
| |---application_dir/
| | |-- __init__.py
| | |-- models.py
| | |-- tests.py
| | `-- views.py
| |-- __init__.py
| |-- settings.py
| |-- urls.py
| |-- wsgi.py
| |---templates/
| | `---application_dir/
| `---static/
| |---css/
| |---font/
| |---img/
| `---js/
|---deployment/
|---documentation/
|---config/
`---manage.py
Run Code Online (Sandbox Code Playgroud)
因为我有一个包含所有 django 文件的文件夹(project_name_dir/)以及非 django 文件的其他目录。
那么为什么 Django 将应用程序放在我的项目文件夹的同一级别呢?
我在Django中有一个带有选择字段的对象
class CustomFieldType(models.Model):
STRING = 'STRING'
DATE = 'DATE'
BOOLEAN = 'BOOLEAN'
NUMERIC = 'NUMERIC'
EMAIL = 'EMAIL'
TYPE_CHOICES = (
(STRING, _('String')),
(DATE, _('Date')),
(BOOLEAN, _('Boolean')),
(NUMERIC, _('Numeric')),
(EMAIL, _('Email'))
)
name = models.CharField(max_length=256)
field_type = models.CharField(choices=TYPE_CHOICES, default=STRING, max_length=10)
company = models.ForeignKey('Company')
class Meta:
unique_together = ('name', 'company')
def __unicode__(self):
return self.name
Run Code Online (Sandbox Code Playgroud)
在我的django控制台中
$> CustomFieldType.objects.create(name='custom_name',field_type='noError',company=mycompany)
<CustomFieldType: custom_name>
$> CustomFieldType.objects.get(name='custom_name').field_type
u'noError'
Run Code Online (Sandbox Code Playgroud)
为什么django没有引发错误(ValidationError)?还是我错过了什么?
django ×4
python ×4
dll ×1
filereader ×1
flask ×1
foreign-keys ×1
html5 ×1
javascript ×1
node-gyp ×1
node.js ×1
python-2.7 ×1
ssl ×1
vue-router ×1
vue.js ×1
vuejs2 ×1