小编Fom*_*aut的帖子

Django REST框架中不允许405"方法POST"

我是Django REST框架的新手.如果我向'/ api/index /'发出POST请求,有人可以解释为什么我会收到这样的错误

405 Method Not Allowed
{"detail":"Method \"POST\" not allowed."}
Run Code Online (Sandbox Code Playgroud)

我的代码如下:

# views.py
class ApiIndexView(APIView):
    permission_classes = (permissions.AllowAny,)

    def post(self, request, format=None):
        return Response("ok")

# urls.py
urlpatterns = [
    url(r'^api/index/$', views.ApiIndexView.as_view()),
]

# settings.py
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.DjangoModelPermissions',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    )
}
Run Code Online (Sandbox Code Playgroud)

但如果我添加<pk>到我的模式中,一切正常:

# views.py
class ApiIndexView(APIView):
    permission_classes = (permissions.AllowAny,)

    def post(self, request, pk, format=None):
        return Response("ok")

# urls.py
urlpatterns = [
    url(r'^api/index/(?P<pk>\d+)/$', views.ApiIndexView.as_view()),
]
Run Code Online (Sandbox Code Playgroud)

我完全糊涂了.为什么有必要使用<pk>并且有没有办法避免在URL模式中使用此参数?

python django django-rest-framework

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

如何使字段在 Django REST framework 中创建时可编辑和只读

我想实现一种 Django 模型的常量字段。我希望在创建模型实例时设置该字段(通过 REST 框架 API),但在更新此字段时必须禁止更改。在 Django 本身或 REST framework 序列化器选项中是否有一种优雅的方法来做到这一点?

django django-rest-framework

12
推荐指数
1
解决办法
1982
查看次数

为什么multiprocessing.Lock()没有锁定Python中的共享资源?

假设我有一个非常大的文本文件,包含许多我想要反转的行.而且我不关心最终的订单.输入文件包含西里尔符号.我multiprocessing用来处理几个核心.

我写了这样的程序:

# task.py

import multiprocessing as mp


POOL_NUMBER = 2


lock_read = mp.Lock()
lock_write = mp.Lock()

fi = open('input.txt', 'r')
fo = open('output.txt', 'w')

def handle(line):
    # In the future I want to do
    # some more complicated operations over the line
    return line.strip()[::-1]  # Reversing

def target():
    while True:
        try:
            with lock_read:
                line = next(fi)
        except StopIteration:
            break

        line = handle(line)

        with lock_write:
            print(line, file=fo)

pool = [mp.Process(target=target) for _ in range(POOL_NUMBER)]
for p in pool: …
Run Code Online (Sandbox Code Playgroud)

python multithreading multiprocessing python-3.x

9
推荐指数
1
解决办法
486
查看次数

fields.E304 Django中的反向访问器冲突

我正在尝试迁移这两个模型:

# models.py

from django.db import models


class Person(models.Model):
    name = models.CharField(max_length=64)


class Person2Person(models.Model):
    person = models.ForeignKey(Person)
    friend = models.ForeignKey(Person)
Run Code Online (Sandbox Code Playgroud)

但我有这个错误:

SystemCheckError: System check identified some issues:

ERRORS:
website.Person2Person.friend: (fields.E304) Reverse accessor for 'Person2Person.friend' clashes with reverse accessor for 'Person2Person.person'.
    HINT: Add or change a related_name argument to the definition for 'Person2Person.friend' or 'Person2Person.person'.
website.Person2Person.person: (fields.E304) Reverse accessor for 'Person2Person.person' clashes with reverse accessor for 'Person2Person.friend'.
    HINT: Add or change a related_name argument to the definition for 'Person2Person.person' or 'Person2Person.friend'. …
Run Code Online (Sandbox Code Playgroud)

django

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

如何使用Python中的argparse.ArgumentParser从命令行传递和解析字符串列表?

我想将一个名字列表传递给我从控制台用Python编写的程序.例如,我想使用类似于此的方法(我知道它不应该工作因为bash):

$ python myprog.py -n name1 name2
Run Code Online (Sandbox Code Playgroud)

所以,我尝试了这段代码:

# myprog.py

from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument('-n', '--names-list', default=[])
args = parser.parse_args()

print(args.names_list) # I need ['name1', 'name2'] here
Run Code Online (Sandbox Code Playgroud)

这导致了错误:

usage: myprog.py [-h] [-n NAMES_LIST]
myprog.py: error: unrecognized arguments: name2
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用引号传递名称"name1 name2"并将其拆分为我的代码args.names_list.split().但我很好奇,是否有更好的方法通过argparse模块传递字符串列表.

任何想法,将不胜感激.

谢谢!

python argparse

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

带有 Nginx 的 Django 的 build_absolute_uri 中的本地主机

在生产中,我使用链 Django - UWSGI - Docker - Nxing。UWSGI使用50012端口,Ngxin配置为:

proxy_pass http://localhost:50012;
Run Code Online (Sandbox Code Playgroud)

Django 进程认为它的主机localhost:50012不是 Nginx 监听的域。所以当函数build_absolute_uri被调用时,localhost:50012不是我的域。有没有办法让 Django 在build_absolute_uri被调用时使用自定义主机名?

注意:在某些build_absolute_uri隐式调用的库中(如social-django或 example),因此在我的情况下避免使用此函数不是解决方案。

django nginx docker

7
推荐指数
1
解决办法
1094
查看次数

如何在Python中重复with语句的主体?

我想实现一种仅使用上下文管理器来重复一段代码所需次数的方法,因为它的语法很漂亮。像这样:

with try_until_success(attempts=10):
    command1()
    command2()
    command3()
Run Code Online (Sandbox Code Playgroud)

如果没有发生错误,命令必须执行一次。如果发生错误,它们应该再次执行,直到经过 10 次尝试,如果是这样,则必须引发错误。例如,重新连接到数据库可能很有用。我表示的语法是字面的,我不想修改它(所以不建议我用某种语句替换它forwhile

有没有办法用try_until_successPython实现我想要的功能?

我尝试的是:

from contextlib import contextmanager

@contextmanager
def try_until_success(attempts=None):
    counter = 0

    while True:
        try:
            yield
        except Exception as exc:
            pass
        else:
            break

        counter += 1
        if attempts is not None and counter >= attempts:
            raise exc
Run Code Online (Sandbox Code Playgroud)

这给了我错误:

RuntimeError: generator didn't stop after throw()
Run Code Online (Sandbox Code Playgroud)

我知道,有很多方法可以使用循环而不是with-statement装饰器或在装饰器的帮助下达到我的需要。但两者都有语法缺点。例如,如果是循环,我必须插入try-except块,如果是装饰器,我必须定义一个新函数。

我已经看过这些问题:

如何制作一个内部有循环的上下文管理器?

有条件地跳过 Python With 语句的主体

他们对我的问题没有帮助。

python python-3.x

7
推荐指数
1
解决办法
918
查看次数

装饰器的类方法

假设我有一个函数(装饰器)来测量给定函数的持续时间:

#include <unistd.h>

void measure(void (*f)()) {
    time_t tBegin = time(NULL);
    f();
    time_t tEnd = time(NULL);
    cout << "Duration: " << (tEnd - tBegin) << " sec" << endl;
}
Run Code Online (Sandbox Code Playgroud)

我想测量一个类的方法的持续时间.例如:

class Myclass {
private:
    double _d;

public:
    Myclass(double d) : _d(d) {}

    void run() {
        measure(m);
    }

    void m() const {
        usleep(1000000 * _d);
    }
};

int main() {
    Myclass obj(2.0);
    obj.run();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这样的实现会导致错误:

error: invalid use of non-static member function
Run Code Online (Sandbox Code Playgroud)

有没有一种方法在C++中正确实现它?它应该不修改外部函数measure,并且测量的方法完全是非静态的(它使用实例的数据).测量应该在方法内部run.

我需要C++ …

c++

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

如何将时差与 Postgres 中的秒数进行比较?

我想在 Postgres 中创建一个过期条件。我有一个变量last_sync::timestamp和一个限制86400 * 30秒。我试过这种方式:

NOW() - last_sync > 86400 * 30
Run Code Online (Sandbox Code Playgroud)

但它给出了一个错误:区间 > 整数没有运算符。

即使last_sunc是,我也想让它工作-infinity

我怎样才能正确地进行这种比较?

postgresql

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

为什么Python3在我的任务上比Python2慢得多?

我很惊讶地知道这Python 3.5.2比慢得多Python 2.7.12.我写了一个简单的命令行命令来计算巨大的CSV文件中的行数.

$ cat huge.csv | python -c "import sys; print(sum(1 for _ in sys.stdin))"
101253515
# it took 15 seconds

$ cat huge.csv | python3 -c "import sys; print(sum(1 for _ in sys.stdin))"
101253515
# it took 66 seconds
Run Code Online (Sandbox Code Playgroud)

Python 2.7.12耗时15秒,Python 3.5.2耗时66秒.我预计差异可能会发生,但为什么会如此巨大呢?Python 3中有哪些新功能使得这类任务变得更慢?有没有更快的方法来计算Python 3中的行数?

我的CPU是Intel(R) Core(TM) i5-3570 CPU @ 3.40GHz.

大小huge.csv为18.1 Gb,包含101253515行.

问这个问题,我不需要不惜一切代价找到一个大文件的行数.我刚刚编写了一个特殊情况,其中Python 3要慢得多.实际上,我正在使用Python 3开发一个处理大型CSV文件的脚本,有些操作不会假设使用csv库.我知道,我可以用Python 2编写脚本,这对速度来说是可以接受的.但是我想知道一种在Python 3中编写类似脚本的方法.这就是为什么我感兴趣的是在我的示例中使Python 3变慢的原因以及如何通过"诚实"的python方法来改进它.

python performance python-2.7 python-3.x

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