我在我的 API 中使用了 ThreadPoolExecutor。在測驗用例中,我生成了一個 Movie 實體并將其保存在資料庫(PostgreSQL)中。我在測驗用例、API 和執行緒池函式中列印了電影計數。為什么在執行緒池中回傳一個空的查詢集?
視圖.py:
def movie_count():
print(Movie.objects.count(), "movie count in the thread")
class MovieListView(APIView):
renderer_classes = (
render.CamelCaseJSONRenderer,
renderers.BrowsableAPIRenderer,
)
def get(self, request, key, format=None):
print(Movie.objects.count(), "movie count before the thread")
with ThreadPoolExecutor(1) as executor:
bookmarked_future = executor.submit(movie_count)
bookmarked_future.result()
return Response({})
測驗.py
def test_mock_function(self):
Movie.objects.create(
title="Title"
)
print(Movie.objects.count(), "movie count in the test")
url = reverse('video_api:list', args=('tops',))
self.client.get(url, format='json', data={'limit': 30})
結果:
1 movie counts in the test
1 movie count before the thread
0 movie count in the thread
uj5u.com熱心網友回復:
我找到了答案。
django測驗中TestCase和TransactionTestCase類的區別
APITestCase 用 2 個 atomic() 塊包裝測驗,一個用于整個測驗類,一個用于類中的每個測驗。這實際上阻止了測驗更改資料庫以進行其他測驗,因為事務在每個測驗結束時回滾。通過在整個測驗類周圍使用第二個 atomic() 塊,特定的資料庫事務行為可能難以測驗,因此您希望退回使用 APITransactionTestCase。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/475219.html
標籤:Python 多线程 django-rest-framework 线程池 django 测试
上一篇:C執行緒不在linux終端中運行
