我有一个简单的函数,可以连接到数据库并获取一些数据。
db.py
from sqlalchemy import create_engine
from sqlalchemy.pool import NullPool
def _create_engine(app):
impac_engine = create_engine(
app['DB'],
poolclass=NullPool # this setting enables NOT to use Pooling, preventing from timeout issues.
)
return impac_engine
def get_all_pos(app):
engine = _create_engine(app)
qry = """SELECT DISTINCT id, name FROM p_t ORDER BY name ASC"""
try:
cursor = engine.execute(qry)
rows = cursor.fetchall()
return rows
except Exception as re:
raise re
Run Code Online (Sandbox Code Playgroud)
我正在尝试通过模拟此连接来编写一些测试用例 -
测试.py
import unittest
from db import get_all_pos
from unittest.mock import patch
from unittest.mock import …Run Code Online (Sandbox Code Playgroud) 我有下面的代码片段,可以创建一个笔记并添加到笔记本中.
我的问题与全局变量有关last_id.当我将它声明为类变量时,即在Class Note中,我得到以下错误但是当我在类外声明时,我的代码工作正常.
以下是我的澄清:
last_id当我在函数中将其声明为全局变量时,为什么需要定义?Error:
C:\Python27\Basics\OOP\formytesting>python notebook.py
Traceback (most recent call last):
File "notebook.py", line 38, in <module>
firstnote = Note('This is my first memo','example')
File "notebook.py", line 10, in __init__
last_id += 1
NameError: global name 'last_id' is not defined
Run Code Online (Sandbox Code Playgroud)
code.py
import datetime
last_id = 0
class Note:
def __init__(self, memo, tags):
self.memo = memo
self.tags = tags
self.creation_date = datetime.date.today()
global last_id
last_id += 1
self.id = last_id
#global last_id
#last_id += 1 …Run Code Online (Sandbox Code Playgroud) 我是Django的新手,想了解filter vs get之间的区别
得到
Entry.objects.get(id__exact=14)
Run Code Online (Sandbox Code Playgroud)
过滤
Entry.objects.filter(id__exact=14)
Run Code Online (Sandbox Code Playgroud)
上述陈述有何不同?
提前致谢.
我是Numpy的新手并且试图理解什么是尺寸的基本问题,
我尝试了以下命令并试图理解为什么最后2个数组的ndim是相同的?
>>> a= array([1,2,3])
>>> a.ndim
1
>>> a= array([[1,2,3],[4,5,6]])
>>> a
array([[1, 2, 3],
[4, 5, 6]])
>>> a.ndim
2
>>> a=arange(15).reshape(3,5)
>>> a.ndim
2
>>> a
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
Run Code Online (Sandbox Code Playgroud)
我的理解..
Case 1:
array([[1, 2, 3],
[4, 5, 6]])
2 elements are present in main lists, so ndim is-2
Case 2:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, …Run Code Online (Sandbox Code Playgroud) 我正在使用Python多处理池模块来创建进程池并为其分配作业.
我创建了4个进程并分配了2个作业但是试图显示它们的进程号但是在显示中我只看到一个进程号"6952"...它不应该打印2个进程号
from multiprocessing import Pool
from time import sleep
def f(x):
import os
print "process id = " , os.getpid()
return x*x
if __name__ == '__main__':
pool = Pool(processes=4) # start 4 worker processes
result = pool.map_async(f, (11,)) #Start job 1
result1 = pool.map_async(f, (10,)) #Start job 2
print "result = ", result.get(timeout=1)
print "result1 = ", result1.get(timeout=1)
Run Code Online (Sandbox Code Playgroud)
结果: -
result = process id = 6952
process id = 6952
[121]
result1 = [100]
Run Code Online (Sandbox Code Playgroud) 我试图理解assert_called_with内部模拟,但我编写的代码引发了一些错误。
import os
import twitter
URL = "http://test.com"
def tweet(api, message):
if len(message) > 40:
message = message.strip("?.,.,.")
status = api.PostUpdate(message)
return status
def main():
api = twitter.Api(consumer_key=''
,consumer_secret='')
msg = 'This is test message'
tweet(api, msg)
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
单元测试
import unittest
from mock import Mock
import test
class TweetTest(unittest.TestCase):
def test_example(self):
mock_twitter = Mock()
test.tweet(mock_twitter,'msg')
mock_twitter.PostUpdate.assert_called_with('message')
if __name__ == '__main__':
unittest.main()
Run Code Online (Sandbox Code Playgroud)
我想了解assert_called_with这里有什么?
我正在使用我的pylintrc文件创建一个简单项目,并为测试方法获取此错误:
method name - test_calculator_add_method_returns_correct_result - doesn't conform to snake_case naming style
Run Code Online (Sandbox Code Playgroud)
class TddInPythonExample(unittest.TestCase):
""" This is a basic test class"""
def test_calculator_add_method_returns_correct_result(self):
""" This test the calculator add method """
calc = Calculator()
result = calc.add(2,2)
self.assertEqual(4, result)
Run Code Online (Sandbox Code Playgroud) 我尝试使用 geopy 获取纬度/经度,但它会抛出 http 403 禁止错误。
from geopy.geocoders import Nominatim
geolocator = Nominatim()
addr = '350 5th Ave, New York, NY 10118'
location = geolocator.geocode(addr)
print location
Run Code Online (Sandbox Code Playgroud)
过去几天一切都运转良好。
raise ERROR_CODE_MAP[code](message)
geopy.exc.GeocoderInsufficientPrivileges: HTTP Error 403: Forbidden
Run Code Online (Sandbox Code Playgroud) 我已经下载了 Pymssql 以连接到 sqlserver 数据库,但连接字符串抛出错误-pymssql.connect(pymssql.c.:7990)
import pymssql
pymssql.connect(host='username\SQLEXPRESS',user='username',password='pwd',database='master')
Run Code Online (Sandbox Code Playgroud)
有人有运气连接到 sqlserver 吗?
Error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pymssql.pyx", line 556, in pymssql.connect (pymssql.c:7990)
raise OperationalError(e[0])
pymssql.OperationalError: (20009, 'Net-Lib error during Unknown error')
Run Code Online (Sandbox Code Playgroud) 我需要一个不以dot开头或以[-_.]开头的正则表达式
以下正则表达式工作但第一个条件失败,即; 不是以dot开头的.
^[A-Za-z0-9][^.]*[^-_.][A-Za-z0-9]$
Run Code Online (Sandbox Code Playgroud)
例如:test.com应该是有效的字符串,但它失败了..
python ×8
python-mock ×2
geopy ×1
mocking ×1
numpy ×1
pylint ×1
pylintrc ×1
pymssql ×1
regex ×1
sqlalchemy ×1