Google App Engine에서 모든 데이터 스토어를 삭제하는 방법은 무엇입니까?
누구나 Google App Engine 에서 모든 데이터 저장소를 삭제하는 방법을 알고 있습니까?
라이브 데이터 저장소 에 대해 이야기하는 경우 앱의 대시 보드 (appengine에 로그인)를 연 다음 datastore-> dataviewer를 열고 삭제하려는 테이블의 모든 행을 선택하고 삭제 버튼을 누르십시오. 모든 테이블에 대해이 작업을 수행하십시오). remote_api를 통해 프로그래밍 방식으로 동일한 작업을 수행 할 수 있지만 사용하지는 않았습니다.
개발 데이터 저장소 에 대해 이야기하는 경우 "./WEB-INF/appengine-generated/local_db.bin" 파일을 삭제하면됩니다 . 다음에 개발 서버를 실행할 때 파일이 다시 생성되고 명확한 db가 생성됩니다.
나중에 프로젝트를 청소하십시오.
이것은 Google Application Engine으로 게임을 시작할 때 유용한 작은 문제 중 하나입니다. 데이터 스토어에 객체를 유지 한 다음 지속 가능한 엔터티에 대한 JDO 객체 모델을 변경하여 더 이상 사용하지 않는 데이터로 끝나는 곳에서 앱을 중단시킬 수 있습니다.
가장 좋은 방법은 Nick이 제안한 원격 API 방법 입니다. Google 의 App Engine 엔지니어 이므로 그를 신뢰하십시오.
그렇게 어렵지는 않으며 최신 1.2.5 SDK는 remote_shell_api.py를 제공합니다. 새 SDK를 다운로드하십시오. 그런 다음 단계를 따르십시오.
명령 행에서 원격 서버 연결 :
remote_shell_api.py yourapp /remote_api
쉘은 로그인 정보를 요청하고, 권한이있는 경우 Python 쉘을 작성합니다. app.yaml에서 / remote_api에 대한 설정 URL 핸들러가 필요합니다.삭제하려는 엔티티를 가져 오면 코드는 다음과 같습니다.
from models import Entry query = Entry.all(keys_only=True) entries =query.fetch(1000) db.delete(entries) \# This could bulk delete 1000 entities a time
2013-10-28 업데이트 :
remote_shell_api.py
로 교체되었으므로 설명서 에 따라에remote_api_shell.py
연결해야합니다 .remote_api_shell.py -s your_app_id.appspot.com
새로운 실험 기능인 Datastore Admin 이 있습니다. 앱 설정에서이를 활성화 한 후에는 웹 UI를 통해 데이터 스토어를 백업하고 대량 삭제할 수 있습니다.
Datastore에서 대량 삭제를 처리하는 가장 빠르고 효율적인 방법 은 최신 Google I / O 에 발표 된 새로운 매퍼 API 를 사용하는 것 입니다.
선택한 언어가 Python 인 경우 mapreduce.yaml 파일에 매퍼를 등록 하고 다음과 같은 함수를 정의하면됩니다.
from mapreduce import operation as op
def process(entity):
yield op.db.Delete(entity)
에 자바 당신은에보고해야한다 이 문서 같은 기능을 제안한다 :
@Override
public void map(Key key, Entity value, Context context) {
log.info("Adding key to deletion pool: " + key);
DatastoreMutationPool mutationPool = this.getAppEngineContext(context)
.getMutationPool();
mutationPool.delete(value.getKey());
}
편집 :
SDK 1.3.8 부터이 목적을 위해 Datastore 관리자 기능 이 있습니다
서버 를 실행할 때 개발 서버 데이터 저장소를 지울 수 있습니다 .
/path/to/dev_appserver.py --clear_datastore=yes myapp
로 약어 --clear_datastore
를 사용할 수도 있습니다 -c
.
많은 양의 데이터가있는 경우 스크립트를 사용하여 삭제해야합니다. remote_api를 사용하면 클라이언트 측에서 데이터 저장소를 간단하게 지울 수 있습니다.
여기로 이동하십시오. Datastore Admin으로 이동 한 후 삭제할 엔티티 유형을 선택하고 삭제를 클릭하십시오. Mapreduce가 삭제를 처리합니다!
App Engine의 Datastore에서 항목을 제거하는 데 사용할 수있는 몇 가지 방법이 있습니다.
먼저 항목을 제거해야하는지 생각하십시오. 비용이 많이 들고 제거하지 않는 것이 더 저렴할 수 있습니다.
Datastore Admin을 사용하여 모든 항목을 직접 삭제할 수 있습니다.
원격 API를 사용하고 대화식으로 항목을 제거 할 수 있습니다.
몇 줄의 코드를 사용하여 프로그래밍 방식으로 항목을 제거 할 수 있습니다.
작업 대기열 및 커서를 사용하여 대량으로 제거 할 수 있습니다.
또는 Mapreduce를 사용하여보다 강력하고 멋진 것을 얻을 수 있습니다.
이러한 방법 각각은 다음 블로그 게시물에 설명되어 있습니다. http://www.shiftedup.com/2015/03/28/how-to-bulk-delete-entries-in-app-engine-datastore
그것이 도움이되기를 바랍니다!
이를 수행하는 제로 설정 방법은 실행중인 앱이 이미 자동으로 가지고있는 실행 임의 코드 HTTP 요청을 관리 서비스에 보내는 것입니다.
import urllib
import urllib2
urllib2.urlopen('http://localhost:8080/_ah/admin/interactive/execute',
data = urllib.urlencode({'code' : 'from google.appengine.ext import db\n' +
'db.delete(db.Query())'}))
출처
나는 이것을 얻었다 http://code.google.com/appengine/articles/remote_api.html .
대화식 콘솔 만들기
먼저 대화식 appenginge 콘솔을 정의해야합니다. 따라서 appengine_console.py라는 파일을 만들고 다음을 입력하십시오.
#!/usr/bin/python
import code
import getpass
import sys
# These are for my OSX installation. Change it to match your google_appengine paths. sys.path.append("/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine")
sys.path.append("/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/yaml/lib")
from google.appengine.ext.remote_api import remote_api_stub
from google.appengine.ext import db
def auth_func():
return raw_input('Username:'), getpass.getpass('Password:')
if len(sys.argv) < 2:
print "Usage: %s app_id [host]" % (sys.argv[0],)
app_id = sys.argv[1]
if len(sys.argv) > 2:
host = sys.argv[2]
else:
host = '%s.appspot.com' % app_id
remote_api_stub.ConfigureRemoteDatastore(app_id, '/remote_api', auth_func, host)
code.interact('App Engine interactive console for %s' % (app_id,), None, locals())
매퍼 기본 클래스 만들기
그런 다음이 매퍼 클래스를 만듭니다. 방금 utils.py라는 새 파일을 만들고 이것을 던졌습니다.
class Mapper(object):
# Subclasses should replace this with a model class (eg, model.Person).
KIND = None
# Subclasses can replace this with a list of (property, value) tuples to filter by.
FILTERS = []
def map(self, entity):
"""Updates a single entity.
Implementers should return a tuple containing two iterables (to_update, to_delete).
"""
return ([], [])
def get_query(self):
"""Returns a query over the specified kind, with any appropriate filters applied."""
q = self.KIND.all()
for prop, value in self.FILTERS:
q.filter("%s =" % prop, value)
q.order("__key__")
return q
def run(self, batch_size=100):
"""Executes the map procedure over all matching entities."""
q = self.get_query()
entities = q.fetch(batch_size)
while entities:
to_put = []
to_delete = []
for entity in entities:
map_updates, map_deletes = self.map(entity)
to_put.extend(map_updates)
to_delete.extend(map_deletes)
if to_put:
db.put(to_put)
if to_delete:
db.delete(to_delete)
q = self.get_query()
q.filter("__key__ >", entities[-1].key())
entities = q.fetch(batch_size)
매퍼는 주어진 종류의 모든 엔터티를 반복하거나, 데이터를 추출하거나, 수정하고 업데이트 된 엔터티를 다시 데이터 저장소에 저장할 수있는 추상 클래스 일뿐입니다.
그것으로 실행!
이제 appengine 대화식 콘솔을 시작하십시오.
$python appengine_console.py <app_id_here>
대화식 콘솔이 시작됩니다. Model의 서브 클래스를 생성합니다 :
from utils import Mapper
# import your model class here
class MyModelDeleter(Mapper):
KIND = <model_name_here>
def map(self, entity):
return ([], [entity])
마지막으로 대화 형 콘솔에서 실행하십시오 : mapper = MyModelDeleter () mapper.run ()
그게 다야!
웹 인터페이스를 사용하여 수행 할 수 있습니다. 계정에 로그인하고 왼쪽의 링크를 탐색하십시오. 데이터 저장소 관리에는 데이터를 수정하고 삭제할 수있는 옵션이 있습니다. 각각의 옵션을 사용하십시오.
배포 된 App Engine 앱과 함께 사용할 수있는 추가 기능 패널을 만들었습니다. 여기에는 데이터 스토어에있는 종류가 드롭 다운으로 나열되며 버튼을 클릭하여 특정 종류의 모든 항목 또는 단순히 모든 항목을 삭제하는 "작업"을 예약 할 수 있습니다. http://code.google.com/p/jobfeed/wiki/Nuke에서 다운로드 할 수 있습니다
.
Python의 경우 1.3.8에는이를위한 실험적인 관리자가 포함되어 있습니다. 그들은 말한다 : "당신의 애플리케이션 제목을 파일에서 다음 내장 가능"
builtins:
- datastore_admin: on
"데이터 저장소 삭제는 현재 Python 런타임에서만 사용할 수 있습니다. 그러나 Java 응용 프로그램은 app.yaml에서 Datastore Admin을 활성화하는 기본이 아닌 Python 응용 프로그램 버전을 만들어이 기능을 계속 이용할 수 있습니다. Java에 대한 기본 지원이 포함됩니다. 곧 출시 될 예정입니다. "
애플리케이션의 "데이터 저장소 관리자"를 열고 관리자를 활성화하십시오. 그러면 모든 엔티티가 확인란과 함께 나열됩니다. 원하지 않는 엔터티를 선택하고 삭제할 수 있습니다.
이것은 당신이 찾고있는 것입니다 ...
db.delete(Entry.all(keys_only=True))
키 전용 쿼리를 실행하면 전체 가져 오기보다 훨씬 빠르며 키 전용 쿼리는 작은 작업으로 간주되므로 할당량이 적습니다.
다음 은 Nick Johnson 의 답변에 대한 링크 입니다.
아래는 테이블을 자르는 엔드 투 엔드 REST API 솔루션입니다.
라우트가 적절한 모델 / 액션에 직접 매핑되는 데이터베이스 트랜잭션을 처리하기 위해 REST API를 설정했습니다. 올바른 URL (example.com/inventory/truncate)을 입력하고 로그인하여 호출 할 수 있습니다.
경로는 다음과 같습니다.
Route('/inventory/truncate', DataHandler, defaults={'_model':'Inventory', '_action':'truncate'})
핸들러는 다음과 같습니다.
class DataHandler(webapp2.RequestHandler):
@basic_auth
def delete(self, **defaults):
model = defaults.get('_model')
action = defaults.get('_action')
module = __import__('api.models', fromlist=[model])
model_instance = getattr(module, model)()
result = getattr(model_instance, action)()
모델을 동적으로로드하여 시작합니다 (예 : api.models에서 찾은 Inventory). 그런 다음 action 매개 변수에 지정된 올바른 메소드 (Inventory.truncate ())를 호출합니다.
@basic_auth는 민감한 작업 (예 : POST / DELETE)에 대한 인증을 제공하는 데코레이터 / 래퍼입니다. 도 있습니다 장식의 OAuth 보안에 대해 우려하는 경우 가능합니다.
마지막으로 조치를 다음과 같이 호출합니다.
def truncate(self):
db.delete(Inventory.all(keys_only=True))
마술처럼 보이지만 실제로는 매우 간단합니다. 가장 중요한 부분은 모델에 다른 조치를 추가하여 하나 이상의 결과 삭제를 처리하기 위해 delete ()를 재사용 할 수 있다는 것입니다.
모든 종류를 하나씩 삭제하여 모든 데이터 스토어를 삭제할 수 있습니다. 구글 appengine 대시 보드와 함께. 다음 단계를 따르십시오.
- https://console.cloud.google.com/datastore/settings에 로그인
- 데이터 스토어 관리자 열기를 클릭하십시오 . (활성화하지 않은 경우 활성화하십시오.)
- 모든 엔티티를 선택하고 Delete 키를 누릅니다 (이 단계에서는 선택한 모든 종류를 삭제하기위한 맵 축소 작업을 실행합니다).
자세한 내용은이 이미지를 참조하십시오 http://storage.googleapis.com/bnifsc/Screenshot%20from%202015-01-31%2023%3A58%3A41.png
데이터가 많은 경우 웹 인터페이스를 사용하는 데 시간이 오래 걸릴 수 있습니다. 앱 엔진 런처 유틸리티는 당신에게 체크 박스 '출시에 대한 명확한 데이터 스토어'와 한 번에 삭제 모든 것을 할 수 있습니다. 이 유틸리티는 이제 Windows 및 Mac (Python 프레임 워크) 모두에서 사용할 수 있습니다.
개발 서버의 경우 Google 앱 엔진 실행기를 통해 서버를 실행하는 대신 터미널에서 다음과 같이 서버를 실행할 수 있습니다.
dev_appserver.py --port = [portnumber] --clear_datastore = yes [nameofapplication]
예 : 내 응용 프로그램 "reader"는 포트 15080에서 실행됩니다. 코드를 수정하고 서버를 다시 시작한 후 "dev_appserver.py --port = 15080 --clear_datastore = yes reader"를 실행하십시오.
나에게 좋습니다.
최근 개발에 대한 답변 추가.
Google은 최근 데이터 스토어 관리 기능을 추가했습니다. 이 콘솔을 사용하여 엔티티를 다른 앱으로 백업, 삭제 또는 복사 할 수 있습니다.
https://developers.google.com/appengine/docs/adminconsole/datastoreadmin#Deleting_Entities_in_Bulk
나는 종종 모든 데이터 저장소를 삭제하고 싶지 않기 때문에 소스 컨트롤에서 /war/WEB-INF/local_db.bin의 깨끗한 복사본을 가져옵니다. 그것은 단지 나 일 수도 있지만 Dev 모드가 중지 된 경우에도 파일을 가져 오기 전에 실제로 파일을 제거해야합니다. Eclipse 용 Subversion 플러그인을 사용하는 Windows에 있습니다.
PHP 변형 :
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
define('DATASTORE_SERVICE', DatastoreServiceFactory::getDatastoreService());
function get_all($kind) {
$query = new Query($kind);
$prepared = DATASTORE_SERVICE->prepare($query);
return $prepared->asIterable();
}
function delete_all($kind, $amount = 0) {
if ($entities = get_all($kind)) {
$r = $t = 0;
$delete = array();
foreach ($entities as $entity) {
if ($r < 500) {
$delete[] = $entity->getKey();
} else {
DATASTORE_SERVICE->delete($delete);
$delete = array();
$r = -1;
}
$r++; $t++;
if ($amount && $amount < $t) break;
}
if ($delete) {
DATASTORE_SERVICE->delete($delete);
}
}
}
예, 시간과 30 초가 걸립니다. 한계입니다. 30 초 이상 자동화 할 수 있도록 ajax 앱 샘플을 넣고 싶습니다.
for amodel in db.Model.__subclasses__():
dela=[]
print amodel
try:
m = amodel()
mq = m.all()
print mq.count()
for mw in mq:
dela.append(mw)
db.delete(dela)
#~ print len(dela)
except:
pass
ndb를 사용하는 경우 데이터 저장소를 지우는 데 도움이 된 방법은 다음과 같습니다.
ndb.delete_multi(ndb.Query(default_options=ndb.QueryOptions(keys_only=True)))
For any datastore that's on app engine, rather than local, you can use the new Datastore API. Here's a primer for how to get started.
I wrote a script that deletes all non-built in entities. The API is changing pretty rapidly, so for reference, I cloned it at commit 990ab5c7f2063e8147bcc56ee222836fd3d6e15b
from gcloud import datastore
from gcloud.datastore import SCOPE
from gcloud.datastore.connection import Connection
from gcloud.datastore import query
from oauth2client import client
def get_connection():
client_email = 'XXXXXXXX@developer.gserviceaccount.com'
private_key_string = open('/path/to/yourfile.p12', 'rb').read()
svc_account_credentials = client.SignedJwtAssertionCredentials(
service_account_name=client_email,
private_key=private_key_string,
scope=SCOPE)
return Connection(credentials=svc_account_credentials)
def connect_to_dataset(dataset_id):
connection = get_connection()
datastore.set_default_connection(connection)
datastore.set_default_dataset_id(dataset_id)
if __name__ == "__main__":
connect_to_dataset(DATASET_NAME)
gae_entity_query = query.Query()
gae_entity_query.keys_only()
for entity in gae_entity_query.fetch():
if entity.kind[0] != '_':
print entity.kind
entity.key.delete()
continuing the idea of svpino it is wisdom to reuse records marked as delete. (his idea was not to remove, but mark as "deleted" unused records). little bit of cache/memcache to handle working copy and write only difference of states (before and after desired task) to datastore will make it better. for big tasks it is possible to write itermediate difference chunks to datastore to avoid data loss if memcache disappeared. to make it loss-proof it is possible to check integrity/existence of memcached results and restart task (or required part) to repeat missing computations. when data difference is written to datastore, required computations are discarded in queue.
other idea similar to map reduced is to shard entity kind to several different entity kinds, so it will be collected together and visible as single entity kind to final user. entries are only marked as "deleted". when "deleted" entries amount per shard overcomes some limit, "alive" entries are distributed between other shards, and this shard is closed forever and then deleted manually from dev console (guess at less cost)upd: seems no drop table at console, only delete record-by-record at regular price.it is possible to delete by query by chunks large set of records without gae failing (at least works locally) with possibility to continue in next attempt when time is over:
qdelete.getFetchPlan().setFetchSize(100);
while (true)
{
long result = qdelete.deletePersistentAll(candidates);
LOG.log(Level.INFO, String.format("deleted: %d", result));
if (result <= 0)
break;
}
- also sometimes it useful to make additional field in primary table instead of putting candidates (related records) into separate table. and yes, field may be unindexed/serialized array with little computation cost.
For all people that need a quick solution for the dev server (as time of writing in Feb. 2016):
- Stop the dev server.
- Delete the target directory.
- Rebuild the project.
This will wipe all data from the datastore.
I was so frustrated about existing solutions for deleting all data in the live datastore that I created a small GAE app that can delete quite some amount of data within its 30 seconds.
How to install etc: https://github.com/xamde/xydra
For java
DatastoreService db = DatastoreServiceFactory.getDatastoreService();
List<Key> keys = new ArrayList<Key>();
for(Entity e : db.prepare(new Query().setKeysOnly()).asIterable())
keys.add(e.getKey());
db.delete(keys);
Works well in Development Server
참고 URL : https://stackoverflow.com/questions/1062540/how-to-delete-all-datastore-in-google-app-engine
'Programing' 카테고리의 다른 글
최대 신장이있는 어린이 : 부모를 100 % 오버플로 (0) | 2020.07.11 |
---|---|
Windows에서 박쥐 파일을 사용하여 모든 내용이 들어있는 폴더를 삭제하는 방법은 무엇입니까? (0) | 2020.07.11 |
PHP에서 대문자 부울 대 소문자 (0) | 2020.07.11 |
자식은 모든 변경 사항을 버리고 업스트림에서 가져옵니다. (0) | 2020.07.11 |
문서가 준비 될 때까지 셀레늄 대기 (0) | 2020.07.11 |