小编jia*_*mmy的帖子

超出范围的浮点值与 Django 渲染不兼容

我正在使用django-restframework并使用它JSONRenderer来呈现我的返回响应。

但我总是遇到这样的错误:

    response = response.render()
  File "C:\Users\Domob\Desktop\dev\venv_bv_crm\lib\site-packages\django\template\response.py", line 106, in render
    self.content = self.rendered_content
  File "C:\Users\Domob\Desktop\dev\venv_bv_crm\lib\site-packages\rest_framework\response.py", line 70, in rendered_content
    ret = renderer.render(self.data, accepted_media_type, context)
  File "C:\Users\Domob\Desktop\dev\venv_bv_crm\lib\site-packages\rest_framework\renderers.py", line 104, in render
    allow_nan=not self.strict, separators=separators
  File "C:\Users\Domob\Desktop\dev\venv_bv_crm\lib\site-packages\rest_framework\utils\json.py", line 25, in dumps
    return json.dumps(*args, **kwargs)
  File "D:\python3\lib\json\__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "D:\python3\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "D:\python3\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)

ValueError: Out of range float values are …
Run Code Online (Sandbox Code Playgroud)

django json python-3.x django-rest-framework

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

如何在Python中从URL读取XML文件?

我想访问子节点中存在的信息。这是因为文件的结构吗?

尝试单独提取文件中的作者子节点信息并运行python代码。效果很好

import urllib
import xml.etree.ElementTree as ET

url = 'https://dailymed.nlm.nih.gov/dailymed/services/v2/spls/fe9e8b7d-61ea-409d-84aa-3ebd79a046b5.xml'

print 'Retrieving', url

document = urllib.urlopen (url).read()
print 'Retrieved', len(document), 'characters.'

print document[:50]

tree = ET.fromstring(document)

lst = tree.findall('title')
print lst[:100]
Run Code Online (Sandbox Code Playgroud)

python xml-parsing

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

ValueError:使用节俭时,filedescriptor超出了select()的范围?

我想通过提供一个远程服务器thrift,下面是我的服务器端试用版:

from test_thrift.test_server.TestService import Iface,Processor
from thrift.Thrift import TType,TException
from thrift.Thrift import TProcessor
from thrift.transport import TSocket
from thrift.protocol import TBinaryProtocol
from thrift.server import TNonblockingServer


port = int(config["server"]["port"])
handler = SmbService()
processor = Processor(handler)
socket = TSocket.TServerSocket(port=port)
server = TNonblockingServer.TNonblockingServer(processor, socket)

server.setNumThreads(100)
server.serve()

Run Code Online (Sandbox Code Playgroud)

在客户端,对于每个请求,我都会创建一个新的连接,并在服务器响应后关闭它。

from thrift.transport.TSocket import TTransportException
from thrift.Thrift import TException
from thrift.protocol import TBinaryProtocol, TCompactProtocol
from thrift.transport import TTransport
from thrift.transport import TSocket
from thrift import Thrift
from test_thrift.test_server import TestService


class SmbClient(object):
    def __init__(self):
        try: …
Run Code Online (Sandbox Code Playgroud)

python thrift

6
推荐指数
0
解决办法
234
查看次数

KeyError:“请求的级别(日期)与索引名称不匹配(无)”

我在重塑数据框数据时遇到错误。

KeyError: 'Requested level (date) does not match index name (None)'
Run Code Online (Sandbox Code Playgroud)

更多详情如下:

# dataframe

# print(df.head(3))
       
    
...
account_id    entity     ae     is_pc   is_new_customer agency  related_entity  type    medium   our_side_entity      settlement_title  settlement_short_title  settlement_type  system_value   account_status  date    sale
12323         entity1   ae1     PC        yes            MB                     EC     TWITTER   our_side_entity1    settlement_title   settlement_short_title      1                0.2          active    2020-07-01     jimmy 
12323         entity1   ae1     PC        yes            MB                     EC     GOOGLE    our_side_entity2    settlement_title   settlement_short_title      1                0.5          active    2020-07-02    jimmy
1037093       Bentity1  ae1     PC        yes            MB                     APP    Google    our_side_entity3    settlement_title   settlement_short_title      2                0            disable …
Run Code Online (Sandbox Code Playgroud)

python pandas

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

当 Debug 为 False 时,如何从 Django 打印 sql 查询

从 doc如何查看 Django 正在运行的原始 SQL 查询?

我可以通过以下方式执行sql:

from django.db import connection
connection.queries
Run Code Online (Sandbox Code Playgroud)

但它只在一段时间内可用 Debug == True

如何将sql打印为Debug == False

谢谢

更新

我想要这样的东西:

from django.db import connection
from django.db import reset_queries

reset_queries()  # Clears the query.
with transaction.atomic():
    r = Amodel.objects.create(
        ...
    )

    Bmodel.objects.filter(id__in=handle_ids_).update(status=4)

# Prints the sql executed in this transaction block.
logger.info("[sql_execute]: {}".format(connection.queries))


Run Code Online (Sandbox Code Playgroud)

django

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

lxml + django + uwsgi 无法生成正确格式的excel文件?

当我的项目lxml安装在我的环境中时使用 uwsgi 启动时,生成的 excel 文件无法打开,因为它可以使用django manage.py runserver和成功打开gunicorn

我的主要代码如下:


?? test_excel
           ??? urls.py
           ??? wsgi.py
           ??? settings.py

?? manage.py


Run Code Online (Sandbox Code Playgroud)

网址.py

from django.contrib import admin
from django.urls import path
from django.views import View
from openpyxl.writer.excel import save_virtual_workbook
import pandas as pd
from django.http import HttpResponse, StreamingHttpResponse


import xlrd
import openpyxl
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment
from openpyxl.writer.excel import save_virtual_workbook
from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE



class TestExcelView(View):
    def get(self, request):
        # indexs = {0: ['cost', …
Run Code Online (Sandbox Code Playgroud)

python django excel lxml uwsgi

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

如何在 django 命令中使用多进程?

我尝试ProcessPoolExecutor在 django 命令中使用来同时获得一些结果。我尝试使用下面的代码来获取它

# main codes


import json
import time
import datetime
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor


from redis import Redis
from django.conf import settings
from django.core.management.base import BaseCommand
from thrift.transport import TSocket, TTransport
from thrift.protocol import TBinaryProtocol

from utils.cache import pool
from services.analysis.thrift.Analysis import Client, Dashparam
from api.analysis.models import MDashBoard


redis_con = Redis(connection_pool=pool)

class AnalysisThriftService(object):

    def __init__(self):
        ...

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.transport.close()



class Command(BaseCommand):
    help = 'python manage.py --settings "xxx"'

    def …
Run Code Online (Sandbox Code Playgroud)

django multiprocessing python-3.6

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

无法使用使用 Python 编写的 Robot Framework 自定义库

使用如下函数创建了一个示例 Python 脚本(Elements.py):

from robot.api.deco import keyword

@keyword("join two strings")
def join_two_strings(arg1, arg2):
   return arg1 + " " + arg2
Run Code Online (Sandbox Code Playgroud)

然后我将机器人框架脚本(.robot 文件)作为库导入:

*** Settings ***
Library                 AppiumLibrary
Library                 Selenium2Library
Library                 BuiltIn
#Here is the import of Custom Lib
Library                 Elements.py 

*** Variable ***

*** Test Cases ***
Example that calls a Python keyword
   ${result}=   join two strings   hello world
   Should be equal     ${result}    hello world
Run Code Online (Sandbox Code Playgroud)

在脚本上方运行后,出现“找不到名称为‘连接两个字符串’的关键字”之类的错误。即使我已经导入了自定义库。

错误信息:

[ ERROR ] Error in file C:\Users\ramana.gouda\PycharmProjects\SafeMobile\Test_Suite\TestCase_346.robot: Test library 'Elements.py' does not exist. …
Run Code Online (Sandbox Code Playgroud)

python pycharm robotframework

4
推荐指数
1
解决办法
5710
查看次数

d3 = {** d1,** d2}`和d4 = dict(** d1,** d2)之间的区别?

假设有两个命令,而其中一些关键则受到质疑。然后,我想结合这两个字典,并使用d2的键替换d1。

d1 = {
    "2222": {1:3},
    "3333":{1:5}
}

d2 = {
    "2222": {1:5},
    "4444":"a"
}


# expected output is
# {'2222': {1: 5}, '3333': {1: 5}, '4444': 'a'}

Run Code Online (Sandbox Code Playgroud)

我尝试过



d3 = {**d1, **d2}  # works

d4 = dict(**d1, **d2)  # failed

TypeError: type object got multiple values for keyword argument '2222'


Run Code Online (Sandbox Code Playgroud)

我很困惑为什么d3 = {**d1, **d2}起作用但d4 = dict(**d1, **d2)失败了**,这两个表达式分别意味着什么?

python python-3.x

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

如何使用指定的方法抽象基类?

说所有的子类都可以有自己的选择,比如 class.choice()

from enum import IntEnum

class CompanyType(IntEnum):
    BySelf = 1
    Agency = 2

    @staticmethod
    def choice():
        return  [
        (i.value, i.name) for i in CompanyType
    ]


class CompanyStatus(IntEnum):
    StartUp = 1
    LargeCompany = 2

    @staticmethod
    def choice():
        return [
            (i.value, i.name) for i in CompanyStatus
        ]
...

Run Code Online (Sandbox Code Playgroud)

如何抽象一个可以用方法继承的基类 choice

预期为:

from enum import IntEnum

class ChoiceBase_():

    @staticmethod
    def choice():
        return [
            (i.value, i.name) for i in specified_subclass
        ]


class CompanyType(ChoiceBase_, IntEnum):
    BySelf = 1
    Agency = 2


class CompanyStatus(ChoiceBase_, IntEnum): …
Run Code Online (Sandbox Code Playgroud)

python

0
推荐指数
1
解决办法
38
查看次数