小编Gui*_*ent的帖子

在我的Django模板中获取绝对静态文件URL

我想知道如何直接在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)

django django-templates

8
推荐指数
1
解决办法
2707
查看次数

如何使用Flask返回相对URI Location标头?

在构建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进行回答.

这篇文章的更多细节

python flask

8
推荐指数
1
解决办法
7138
查看次数

在python 2.7.9中禁用默认证书验证

我尝试与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)

python ssl

8
推荐指数
2
解决办法
2万
查看次数

无法在Django 1.5中使用自定义用户模型创建超级用户


我的目标是在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)

或者我是否必须为此用户创建虚假公司?谢谢

django foreign-keys django-models

7
推荐指数
2
解决办法
4848
查看次数

使用FileReader导入javascript文件时如何保留换行符?

我想知道如何检索文件的内容,保留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方法,没有任何成功.难道我做错了什么 ?谢谢

FileReader doc

编辑:

关于JSfiddle http://jsfiddle.net/yTgp7/的一个例子

在此输入图像描述 在此输入图像描述

问题仅存在于mac Os X上的Firefox上

javascript html5 filereader

6
推荐指数
1
解决办法
3032
查看次数

如何确信Python 2.7.10不会破坏我的Python 2.7.6代码?

为了简化我的工作,我想从Python 2.7.6迁移到Python 2.7.9/2.7.10.

我需要证明我的Python 2.7.10不会破坏我的软件"使用"Python 2.7.6

我按照将python 2移植到python 3中描述的步骤进行了操作

  • 将我的测试覆盖率从0增加到40%
  • 运行pylint(没有关键的bug)
  • 了解Python 2.7.10和2.7.6之间的差异<我阅读了发行说明

我不能确定100%我的代码不会破坏,但我怎么能有信心?

例如,我是否应该查看2.7.6和2.7.10之间修复的所有Core和Builtins错误?如果我们使用这些方法,请搜索我的代码?

是否存在更好的策略?

100%的代码覆盖率是一个很好的解决方案,但是使用2.7.6和2.7.10之间的修改方法可能比50%覆盖率+ 100%代码更难获得测试.

python python-2.7

6
推荐指数
1
解决办法
1150
查看次数

与node-gyp的python ctypes相当的javascript

我想将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)

dll node.js node-gyp

6
推荐指数
1
解决办法
508
查看次数

如何在我的 vuejs 组件的 router.beforeEach 中注入数据?

我使用 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)

vue.js vue-router vuejs2

6
推荐指数
1
解决办法
2万
查看次数

为什么 Django 将应用程序放在我的项目文件夹的同一级别?

从 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 directory-structure

5
推荐指数
1
解决办法
1873
查看次数

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)?还是我错过了什么?

python django

5
推荐指数
1
解决办法
1231
查看次数