小编luk*_*kik的帖子

SQLite存储以零开头的字符串,例如"001"

我在SQLite中选择哪种数据类型来在数据库中存储字符串,如"001".

我尝试过使用Text但是当我输入字符串001时,它会丢弃00并且只会输入1.

我甚至尝试使用"blob"数据类型,但仍然没有运气.它们都会在数字之前删除零.

sqlite types

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

Python3.2:安装MySQL-python失败,错误"没有名为ConfigParser的模块"

我想在MySQL数据库中使用SQLAlchemy.我已经创建了引擎并尝试连接但是我收到如下错误.

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
Engine = create_engine('mysql+mysqldb://dbuser:pass@localhost/mydb')
Base = declarative_base(Engine)
Run Code Online (Sandbox Code Playgroud)

失败并出现错误:

File "/usr/local/lib/python3.2/dist-packages/SQLAlchemy-0.8.0b2-py3.2.egg/sqlalchemy/connectors/mysqldb.py", line 57, in dbapi
return __import__('MySQLdb')
ImportError: No module named MySQLdb
Run Code Online (Sandbox Code Playgroud)

搜索我发现你必须安装MySQLdb for python才能与MySQL一起玩.因此尝试使用pip-3.2或easy_install-3.2安装它会失败,如下所示.

sudo pip-3.2 install MySQL-python
Downloading/unpacking MySQL-python
Running setup.py egg_info for package MySQL-python
Traceback (most recent call last):
  File "<string>", line 16, in <module>
  File "/tmp/pip-build/MySQL-python/setup.py", line 14, in <module>
    from setup_posix import get_config
  File "setup_posix.py", line 2, in <module>
    from ConfigParser import SafeConfigParser
ImportError: No module …
Run Code Online (Sandbox Code Playgroud)

python pip python-3.2

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

将'6E + 007'转换为十进制

我有一个python函数,检查传递的值是否为有效数字.传递的值是字符串格式.

def is_valid_numeral(text_to_check):
    '''Check if passed value is a valid numeral figure'''
    try: 
        float(text_to_check)
        return True
    except ValueError:
        return False
Run Code Online (Sandbox Code Playgroud)

6E+007传递一个值,此函数返回True,这是正确的.

在上面的函数之后,我需要将传递的数字保存到Decimal字段中.所以我运行format_decimal如下函数

def format_decimal(value, decimals): 
    '''Format a value to "n" decimal places
    http://mkaz.com/solog/python/python-string-format.html
    '''
    try:
        if decimals == 2:
            value =  int(value)/100
            return "{:.2f}".format(int(value))
    except ValueError:
        raise 
Run Code Online (Sandbox Code Playgroud)

此时,它失败并显示错误:

`Value Error: Invalid literal for int() with base 10:6E+007`
Run Code Online (Sandbox Code Playgroud)

因为这只是一个有效的数字,只是用不同的符号,是否有一个函数可以为我转换这种类型的值,然后通过format_decimal函数传递它?

python exponential

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

如何替换除字母,数字,正斜杠和反斜杠之外的所有字符

想要解析文本并仅返回字母,数字,正斜杠和反斜杠,并替换所有其他内容''.

是否可以只使用一个正则表达式模式而不是几个然后调用循环?我无法得到下面的模式,不能替换后退和正斜杠.

line1 = "1/R~e`p!l@@a#c$e%% ^A&l*l( S)-p_e+c=ial C{har}act[er]s ;E  xce|pt Forw:ard\" $An>d B,?a..ck Sl'as<he#s\\2"
line2 = line
RGX_PATTERN = "[^\w]", "_"

for pattern in RGX_PATTERN:
    line = re.sub(r"%s" %pattern, '', line)
print("replace1: " + line)
#Prints: 1ReplaceAllSpecialCharactersExceptForwardAndBackSlashes2
Run Code Online (Sandbox Code Playgroud)

在从SO下面的代码已经过测试,发现比正则表达式快,但随后它取代所有特殊字符,包括/和\,我希望保留.有没有办法编辑它以适用于我的用例并仍然保持其优于正则表达式的优势?

line2 = ''.join(e for e in line2 if e.isalnum())
print("replace2: " + line2)
#Prints: 1ReplaceAllSpecialCharactersExceptForwardAndBackSlashes2
Run Code Online (Sandbox Code Playgroud)

作为额外的障碍,正在解析的文本应该是ASCII格式,因此如果可能的话,来自任何其他编码的字符也应该替换为''

python regex

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

Python:file.readline在行尾添加一个空格

我使用python来读取平面空格填充的文本文件.文本文件验证的一部分是文本文件中的每一行都应该是一个特定的文件长度,包括空间填充.

当我使用下面的代码时,python最终会给我一个额外空格的行.例如,我希望fileX中的所有行都有143个字符.Python虽然会将其读作144个字符,因此说该文件无效.如果我在VB.NET中做同样的事情,我会得到正确的143个字符.

为什么Python的 readline函数会添加额外的字符?(使用python 3.2)

import io
myfile = open("file_path", "r")
while True:
    line = myfile.readline()
    if not line:
            break
    print(len(line))  #This prints 144 characters
Run Code Online (Sandbox Code Playgroud)

VB.NET给出了143个字符的正确长度.

Using objStreamReader As StreamReader = New StreamReader(myFilePath)
    While objStreamReader.EndOfStream = False
            line = objStreamReader.ReadLine
            len(line)   'This returns the correct length of 143.
Run Code Online (Sandbox Code Playgroud)

使用line.strip将不是正确的机制,因为我可能会摆脱有用的空间.请记住,文件是空间填充的,最大给定长度.

python

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

搜索多个表,并在结果行中显示表名

如何构造SQL语句以跨多个平面无关表运行,并使用select的结果和结果来自的表的名称显示结果.

这个场景是我有几个表中每个都有相同列名的表.我收集的是来自外部各方的数据,因为它存储在不同的表中.

相同的表格如下:

Table 1: pid, parent_name, student_name, student_number, class_name, columnN
Table 2: pid, previous_school, previous_school, student_number, columnN
Table 3: pid, student_name, student_number, parent_name, column4, columnN
Table 14: pid, student_number, parent_name, column4, columnN
Table N: pid, previous_school, parent_name, column4, columnN
Run Code Online (Sandbox Code Playgroud)

我需要一个student_name在所有表中搜索的SQL语句在伪代码中:for each table, find a student named john doe and return to me the row where you got the result and the table where you found the result

在以下演示文稿中给出结果:

john doe, Table 1, pid
john doe, Table …
Run Code Online (Sandbox Code Playgroud)

sql postgresql database-design dynamic-sql

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

多处理脚本比普通脚本慢

我似乎无法绕过多处理.我试图做一些基本的操作,但多处理脚本似乎需要永远.

import multiprocessing, time, psycopg2

class Consumer(multiprocessing.Process):

    def __init__(self, task_queue, result_queue):
        multiprocessing.Process.__init__(self)
        self.task_queue = task_queue
        self.result_queue = result_queue

    def run(self):
        proc_name = self.name
        while True:
            next_task = self.task_queue.get()
            if next_task is None:
                print ('Tasks Complete')
                self.task_queue.task_done()
                break            
            answer = next_task()
            self.task_queue.task_done()
            self.result_queue.put(answer)
        return

class Task(object):
    def __init__(self, a):
        self.a = a

    def __call__(self):
        #Some more work will go in here but for now just return the value
        return self.a

    def __str__(self):
        return 'ARC'
    def run(self):
        print ('IN')


if __name__ == …
Run Code Online (Sandbox Code Playgroud)

python multiprocessing

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

使用DRF序列化程序验证字典列表

我该如何编写验证字典列表的序列化程序?

发送的有效负载样本为:

"payment_discount": [
    {
        "discount_rule_id": 1,
        "discount_rule_name": "10 day early payment",
        "discount_earned": "298.00"
    },
    {
        "discount_rule_id": 2,
        "discount_rule_name": "Store discount",
        "discount_earned": "5.50"
    },
]
Run Code Online (Sandbox Code Playgroud)

从这个答案和这个:

class PaymentDiscountSerializer(serializers.DictField):

    discount_rule_id = serializers.IntegerField(required=False)
    discount_rule_name = serializers.CharField(max_length=50)
    discount_earned = serializers.DecimalField(max_digits=10, decimal_places=3)

class PaymentDiscountListSerializer(serializers.ListField):
    """Serialize discount object"""
    child = PaymentDiscountSerializer()

class PaymentSerializer(serializers.ModelSerializer):
    payment_discount = PaymentDiscountListSerializer()
    # Other model fields
Run Code Online (Sandbox Code Playgroud)

这样,我可以使用serializer.data来访问有效负载中的payment_discount对象,但是不幸的是,如果例如有效负载包括非十进制类型的Discount_earned值,则不会对字典进行验证

使用:Django == 1.10.2&djangorestframework == 3.5.1

django django-rest-framework

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

SQLAlchemy:逗号如何确定查询是返回String还是Tuple?

在SQLAlchemy中,如果你在查询中放一个逗号,如下所示,你会得到一个"字符串".如果你没有逗号,你会得到一个元组.为什么会这样?我看不到文档中解释的任何地方

使用SQLAlchemy0.8

以下代码返回一个字符串:

def get_password(self, member_id):
    for password, in session.query(Member.__table__.c.password).filter(self.__table__.c.id == member_id): 
        return password
Run Code Online (Sandbox Code Playgroud)

这将返回一个类'str': 'mypassword'

虽然下面的代码返回一个元组;

def get_password(self, member_id):
    for password in session.query(Member.__table__.c.password).filter(self.__table__.c.id == member_id): 
        return password
Run Code Online (Sandbox Code Playgroud)

这将返回一个类'sqlalchemy.util._collections.KeyedTuple':('mypassword',)

python sqlalchemy

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