Python 2.7은 지원이 종료되었으며 2026년 1월 31일에 지원 중단됩니다. 지원 중단 후에는 조직에서 이전에 조직 정책을 사용하여 레거시 런타임의 배포를 다시 사용 설정한 경우에도 Python 2.7 애플리케이션을 배포할 수 없습니다. 기존 Python 2.7 애플리케이션은 지원 중단 날짜 이후에도 계속 실행되고 트래픽을 수신합니다. 지원되는 최신 Python 버전으로 마이그레이션하는 것이 좋습니다.
컨텍스트 옵션을 사용하면 특정한 Datastore 작업을 다른 구성으로 실행할 수 있습니다. 예를 들어 개별 요청에 대한 읽기 정책이나 RPC 기한을 변경해야 할 수 있습니다.
이를 위해 컨텍스트 옵션을 거의 모든 작업에 전달할 수 있습니다.
일부 트랜잭션 관련 함수는 컨텍스트 옵션 집합 외에 추가적인 옵션을 포함하는 트랜잭션 옵션을 사용합니다.
다음은 컨텍스트 옵션 사용을 보여 주는 몇 가지 예입니다. 항목을 읽을 때 다음 명령어를 사용하여 RPC 기한을 1초로 설정할 수 있습니다.
key.get(deadline=1)
항목을 작성할 때 다음 명령어를 사용하여 Memcache 제한 시간을 30초로 설정할 수 있습니다.
ent.put(ndb_memcache_timeout=30)
다음 명령어를 사용하여 캐시된 항목을 삭제하고 강제로 다시 로드할 수 있습니다.
key.delete(use_datastore=False)
특수 키워드 인수 options와 config(기록상의 이유로 동일한 의미를 가짐)를 사용하면 여러 옵션을 구성 객체 1개로 지정할 수 있습니다. ndb.ContextOptions 객체이거나 (거래 함수 및 데코레이터의 경우) ndb.TransactionOptions 객체일 수 있습니다.
예를 들어 key.get(options=ndb.ContextOptions(use_cache=True))는 key.get(use_cache=True)와 동일합니다.
이러한 옵션 객체에서 설정된 옵션은 키워드 매개변수에 의해 재정의될 수 있습니다.
다음 컨텍스트 옵션을 사용할 수 있습니다.
옵션
유형
설명
deadline
float
Datastore API 호출 기한으로, 초 단위 시간으로 지정됩니다.
(기본적으로 호출은 요청 핸들러 기한에 의해서만 중단됩니다.)
read_policy
ndb.EVENTUAL_CONSISTENCY
Datastore가 반환된 모든 결과에 변경사항을 적용하기를 기다리는 대신 현재 결과가 아닌 결과를 더 빨리 가져오려면 이를 ndb.EVENTUAL_CONSISTENCY로 설정합니다.
force_writes
bool
앱이 읽기 전용인 경우라도 쓰기 요청이 성공해야 하는지 여부를 지정합니다.
(이는 사용자가 제어하는 읽기 전용 기간에만 적용됩니다.)
use_cache
bool
항목을 프로세스 내 캐시에 저장할지 여부를 지정합니다. 이 작업에 대한 프로세스 내 캐시 정책을 재정의합니다.
use_memcache
bool
항목을 Memcache에 저장할지 여부를 지정합니다. 이 작업에 대한 Memcache 정책을 재정의합니다.
use_datastore
bool
항목을 Datastore에 저장할지 여부를 지정합니다. 이 작업에 대한 Datastore 정책을 재정의합니다.
memcache_timeout
int
Memcache에서의 항목 최대 수명이며, 이 작업에 대한 Memcache 제한 시간 정책을 재정의합니다.
max_memcache_items
int
컨텍스트 Memcache 메서드의 자동 배치 처리 기능에 대한 최대 배치 크기입니다.
예를 들어 기본 크기가 max_memcache_items(100)인 Memcache 집합 작업은 최대 100개까지 단일 set_multi 작업으로 결합됩니다.
일부 트랜잭션 관련 함수의 경우, 다음 트랜잭션 옵션을 사용할 수 있습니다(위에 나열한 상속된 컨텍스트 옵션과 함께).
옵션
유형
설명
xg
bool
교차 그룹(XG) 트랜잭션을 허용합니다.
기본적으로 False개입니다.
propagation
int
NDB는 '중첩 트랜잭션'이라 하는 트랜잭션 내의 트랜잭션을 제한적으로 지원합니다.
코드가 중첩 트랜잭션을 시작하려는 경우, 전파 매개변수는 수행되는 작업을 제어합니다.
@ndb.transactional의 전파 정책은 기본적으로 ALLOWED입니다.
ndb.transaction()의 전파 정책은 기본적으로 NESTED입니다.
NESTED 정책은 NDB에서 지원되지 않으므로 코드가 BadRequestError 예외를 발생시킵니다. 이 경우, NDB는 프로그래머가 중첩 트랜잭션의 한계에 대해 명확히 알 수 있도록 지원되지 않는 기본값을 설정합니다.
전파 매개변수는 다음 값 중 하나일 수 있습니다.
ndb.TransactionOptions.NESTED
외부 정책이 커밋되면 NESTED 전파 정책은 외부와 내부 트랜잭션의 모든 변경 내용을 함께 커밋합니다. 그러나 내부 트랜잭션에서 예외가 발생하면 여기에 있는 모든 변경 사항이 삭제되지만 외부 트랜잭션은 선택적으로 복구되고 계속 진행될 수 있습니다. NESTED 정책은 지원되지 않습니다. 이 정책을 사용하면 코드가 BadRequestError 예외를 발생시킵니다.
ndb.TransactionOptions.MANDATORY
항상 기존 트랜잭션을 전파합니다. 기존 트랜잭션이 없으면 예외를 발생시킵니다.
이 정책을 사용하는 함수에서 예외가 발생하면 예외 포착 및 외부 트랜잭션 커밋이 안전하지 않을 수 있으며, 함수로 인해 외부 트랜잭션이 잘못된 상태로 남겨질 수 있습니다.
ndb.TransactionOptions.ALLOWED
기존 트랜잭션이 있으면 이 트랜잭션을 전파합니다.
이 정책을 사용하는 함수에서 예외가 발생하면 예외 포착 및 외부 트랜잭션 커밋이 안전하지 않을 수 있으며, 함수로 인해 외부 트랜잭션이 잘못된 상태로 남겨질 수 있습니다.
ndb.TransactionOptions.INDEPENDENT
항상 모든 기존 트랜잭션을 '일시중지'하고 새 트랜잭션을 사용합니다.
항목이 호출자 트랜잭션과 일관성을 유지하지 않으므로, 이 정책을 사용하는 함수는 새 트랜잭션에서 읽은 항목을 반환하지 않습니다.
retries
int
트랜잭션이 실패하는 경우, 자동으로 다시 시도하는 횟수입니다.
0은 한 번만 시도하고 다시 시도하지 않음을 의미합니다.
캐싱으로 인해 옵션이 무시되는 경우도 있습니다.
예를 들어 컨텍스트 내 캐시에서 만족되는 읽기 작업의 RPC 기한을 지정하면 이 기한은 무시됩니다.
한편, 인식할 수 없는 옵션은 TypeError를 발생시킵니다.
자동 일괄 처리가 적용되면 다른 옵션을 포함한 작업이 함께 그룹화됩니다. 예를 들어 put_async()를 사용하여 일부 항목을 deadline = 5로 작성하고 다른 일부 항목을 기한을 지정하지 않은 채 작성한 후 모두 자동 일괄 처리할 수 있는 경우 기본 RPC 기한이 5이더라도 자동 일괄 처리기가 deadline = 5인 항목 그룹에 1개, 다른 그룹에 1개 등 개별 RPC 호출을 총 2개 만듭니다.
이는 지정된 옵션이 RPC 작업과 무관한 경우에도 적용됩니다(예: ndb_should_cache).
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-04(UTC)"],[[["\u003cp\u003eThis page documents the use of legacy bundled services and APIs, which are specifically designed for first-generation runtimes in the App Engine standard environment.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003endb\u003c/code\u003e API provides functions for managing entities, including operations like fetching, deleting, and storing entities, both synchronously and asynchronously.\u003c/p\u003e\n"],["\u003cp\u003eTransactions can be managed through the \u003ccode\u003endb\u003c/code\u003e API, allowing you to run operations in a transactional context, which can be done either directly or using decorators like \u003ccode\u003e@ndb.transactional\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eContext and transaction options are available to configure datastore operations, allowing customization of settings like deadlines, caching behavior, and read policies for individual requests.\u003c/p\u003e\n"],["\u003cp\u003eSpecific exceptions, such as \u003ccode\u003ewebob.exc.HTTPException\u003c/code\u003e and \u003ccode\u003endb.Rollback\u003c/code\u003e, are not logged by default, and users can specify additional exceptions to be excluded from logging via \u003ccode\u003endb.add_flow_exception\u003c/code\u003e.\u003c/p\u003e\n"]]],[],null,["# NDB Functions\n\nFunctions\n---------\n\n| This page describes how to use the legacy bundled services and APIs. This API can only run in first-generation runtimes in the App Engine standard environment. If you are updating to the App Engine Python 3 runtime, refer to the [migration guide](/appengine/migration-center/standard/migrate-to-second-gen/python-differences) to learn about your migration options for legacy bundled services.\n\nndb.add_flow_exception(exc)\n: Specify that an exception should *not* be logged, but is just part of\n normal program flow. (Normally, raising an exception writes a warning\n message to the application's logs.)\n\n **Arguments**\n\n exc\n\n : Exception class that should not be logged. By default, the following exceptions are not logged:\n\n - `webob.exc.HTTPException` (and its subclasses)\n - `ndb.Rollback`\n\nndb.delete_multi(keys, \\*\\*ctx_options)\n\n: Deletes entities identified by the passed sequence of keys. **Arguments**\n\n keys\n : Sequence of [keys](/appengine/docs/legacy/standard/python/ndb/keyclass)\n\n \\*\\*ctx_options\n : [Context options](#context_options)\n\nndb.delete_multi_async(keys, \\*\\*ctx_options)\n\n: Asynchronously deletes entities identified by the passed sequence of keys. **Arguments**\n\n keys\n : Sequence of [keys](/appengine/docs/legacy/standard/python/ndb/keyclass)\n\n \\*\\*ctx_options\n : [Context options](#context_options)\n\n Returns a list of [Future](/appengine/docs/legacy/standard/python/ndb/futureclass)\n objects. Each future's result will be `None`.\n\nndb.get_multi(keys, \\*\\*ctx_options)\n\n: Fetches entities identified by the passed sequence of keys. **Arguments**\n\n keys\n : Sequence of [keys](/appengine/docs/legacy/standard/python/ndb/keyclass)\n\n \\*\\*ctx_options\n : [Context options](#context_options)\n\n Returns a list. Each list item is either a\n [Model](/appengine/docs/legacy/standard/python/ndb/modelclass) instance or `None`\n if the key wasn't found.\n\nndb.get_multi_async(keys, \\*\\*ctx_options)\n\n: Asynchronously fetches entities identified by the passed sequence of keys. **Arguments**\n\n keys\n : Sequence of [keys](/appengine/docs/legacy/standard/python/ndb/keyclass)\n\n \\*\\*ctx_options\n : [Context options](#context_options)\n\n Returns a list of [Future](/appengine/docs/legacy/standard/python/ndb/futureclass)\n objects. Each future's result is a\n [Model](/appengine/docs/legacy/standard/python/ndb/modelclass) instance or `None`\n if the key wasn't found.\n\nndb.in_transaction()\n: Returns a Boolean indicating whether a transaction is currently active.\n\n@ndb.non_transactional \n\n@ndb.non_transactional(allow_existing=True)\n: Decorator to ensure that a function runs *outside* a transaction.\n\n **Arguments:**\n\n allow_existing\n : If `True` (the default) and if the decorated function\n is called by code in a transaction, the function runs independent\n of the transaction. If `False` and if the decorated function\n is called by code in a transaction, it raises an exception.\n\nndb.put_multi(entities, \\*\\*ctx_options)\n: Stores a sequence of [Model](/appengine/docs/legacy/standard/python/ndb/modelclass) instances.\n\n **Arguments**\n\n entities\n : Sequence of [Model](/appengine/docs/legacy/standard/python/ndb/modelclass) instances\n\n \\*\\*ctx_options\n : [Context options](#context_options)\n\n Returns a list with the stored [keys](/appengine/docs/legacy/standard/python/ndb/keyclass).\n\nndb.put_multi_async(entities, \\*\\*ctx_options)\n: Asynchronously stores a sequence of\n [Model](/appengine/docs/legacy/standard/python/ndb/modelclass) instances.\n\n **Arguments**\n\n entities\n : Sequence of [Model](/appengine/docs/legacy/standard/python/ndb/modelclass) instances\n\n \\*\\*ctx_options\n : [Context options](#context_options)\n\n Returns a list of [Future](/appengine/docs/legacy/standard/python/ndb/futureclass)\n objects.\n Each future's result will be a stored [key](/appengine/docs/legacy/standard/python/ndb/keyclass).\n\nndb.transaction(callback, \\*\\*ctx_options)\n\n: Run a callback in a transaction. **Arguments**\n\n callback\n : Function or tasklet to be called\n\n \\*\\*ctx_options\n : [Transaction options](#context_options)\n\n Returns whatever callback returns.\n Raises whatever callback raises or a\n `TransactionFailedError` exception if the transaction fails.\n\n To pass arguments to a callback function, use a lambda. For example, \n\n ```python\n def my_callback(key, inc):\n ...\n\n transaction(lambda: my_callback(Key(...), 1))\n ```\n\nndb.transaction_async(callback, \\*\\*ctx_options)\n\n: Asynchronously run a callback in a transaction. **Arguments**\n\n callback\n : Function or tasklet to be called\n\n \\*\\*ctx_options\n : [Transaction options](#context_options)\n\n Returns a [Future](/appengine/docs/legacy/standard/python/ndb/futureclass).\n The future returns whatever callback returns, or\n raises whatever callback raises or a\n `TransactionFailedError` if the\n transaction fails.\n\n To pass arguments to a callback function, use a lambda. For example, \n\n ```python\n def my_callback(key, inc):\n ...\n\n transaction(lambda: my_callback(Key(...), 1))\n ```\n\n@ndb.transactional \n\n@ndb.transactional(\\*\\*ctx_options)\n\n: Decorator to make a function automatically run in a transaction. **Arguments:**\n\n This decorator can have [transaction options](#context_options).\n\nContext Options, Transaction Options\n------------------------------------\n\nContext options allow you to run specific datastore operations with different\nconfigurations. For example, you might want to vary the read policy\nor the RPC deadline for individual requests.\nYou can do this by passing *context options* to almost any operation.\nSome transaction-related functions take *transaction options*, which include additional options\non top of a set of context options.\n\nHere are a few examples using context options. To set the RPC deadline to 1 second when reading an entity,\nyou can use:\n\n```python\nkey.get(deadline=1)\n```\n\nTo set the memcache timeout to 30 seconds when writing an entity,\nyou can use:\n\n```python\nent.put(ndb_memcache_timeout=30)\n```\n\nTo delete an item that has been cached and force its reload, you can use:\n\n```python\nkey.delete(use_datastore=False)\n```\n\nThe special keyword arguments `options` and `config`\n(which have identical meanings for historical reasons) allow one to specify\nseveral options as a Configuration object. This can be an\n`ndb.ContextOptions` object or\n(for the transactional functions and decorator) an\n`ndb.TransactionOptions` object.\nFor example,\n`key.get(options=ndb.ContextOptions(use_cache=True))`\nis equivalent to\n`key.get(use_cache=True)`.\nThe options set in such an options object can be overridden by\nkeyword parameters.\n\nThe following **context options** are available:\n\nIn some cases, options are ignored because of caching.\nFor example, if you specify an RPC deadline for a read\noperation that is satisfied from the in-context cache,\nthe deadline is ignored.\nOn the other hand,\nunrecognized options cause `TypeError` to be raised.\n\nOperations with different options are grouped together when\nauto-batching applies. For example, if you use `put_async()`\nto write some entities with\n`deadline = 5`\nand some without specifying a deadline, and all are eligible for\nauto-batching, the auto-batcher will make two separate RPC\ncalls---one for the group of entities with\n`deadline = 5`\nand one for the other group---even though the default\nRPC deadline is also 5!\nThis applies even if the option specified is irrelevant to\nthe RPC operation (for example, `ndb_should_cache`)."]]