本文整理汇总了Python中couchdbkit.Server类的典型用法代码示例。如果您正苦于以下问题:Python Server类的具体用法?Python Server怎么用?Python Server使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Server类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, settings, crm, client_doc, invoice_cycle):
self.invoice_template_dir = settings.invoice_template_dir
self.output_dir = settings.invoice_output_dir
self.tax = float(settings.invoice_tax)
self.home_country = settings.invoice_home_country if hasattr(settings, 'invoice_home_country', ) else None
self.jinja_env = Environment(
loader=FileSystemLoader(self.invoice_template_dir)
)
self.jinja_env.filters['nl2br'] = filters.nl2br
self.jinja_env.filters['format_date'] = filters.format_date
self.crm = crm
self.client_id = client_doc['_id']
try:
self.extcrm_id = client_doc['extcrm_id']
except KeyError:
extcrm_id = client_doc['extcrm_id'] if 'extcrm_id' in client_doc else "None"
print('\nNOT creating invoice missing extcrm_id:%s, %s' % (extcrm_id, client_doc['name']), client_doc)
self.client_doc = None
return
self.client_doc = client_doc
self.settings = settings
self.invoice_cycle = invoice_cycle
self.invoice_nr = invoice_cycle.current_nr
server = Server(self.settings.couchdb_uri)
self.db = server.get_db(self.settings.couchdb_db)
if not Invoice.service_definitons:
Invoice.load_service_definitions(self.db)
self.setup_invoice()
示例2: run
def run(self):
crm = get_crm_module(self.settings)
server = Server(self.settings.couchdb_uri)
db = server.get_db(self.settings.couchdb_db)
invoice_cycle = InvoiceCycle(self.settings.invoice_nr)
clients = db.view(
self._cmd("client_is_billable"), include_docs=True
)
counter = 0
for client in clients:
if not self.settings.limit_client_id or client['id'] == self.settings.limit_client_id:
# print(client['doc']['name'])
invoice = Invoice(
self.settings, crm=crm,
client_doc=client['doc'],
invoice_cycle=invoice_cycle
)
invoice_start_date = min(
[d['start_date'] for d in invoice.doc['services'].itervalues()]
)
if invoice_start_date < invoice_cycle.doc['end_date']:
invoice.render_pdf()
invoice_cycle.add_invoice(invoice)
counter += 1
print(".", end="")
if self.settings.max != 0 and counter >= self.settings.max:
break
print("\n", "total", invoice_cycle.get_total())
示例3: CouchDBServer
class CouchDBServer(object):
def __init__(self):
self.__get_server_uri()
self.__authenticate()
self.__connect()
def __get_server_uri(self):
couchdb_port = config.couchdb.port if config.couchdb.protocol == 'http' else config.couchdb.ssl_port
self.__couchdb_uri = "%s://%s:%s" % (config.couchdb.protocol, config.couchdb.host, couchdb_port)
def __authenticate(self):
user, passwd = config.couchdb.user, config.couchdb.password
if all((user, passwd)):
auth = restkit.BasicAuth(user, passwd)
self.__auth_resource = CouchdbResource(filters=[auth])
else:
self.__auth_resource = None
def __connect(self):
self.__server = Server(uri=self.__couchdb_uri, resource_instance=self.__auth_resource)
def list_workspaces(self):
return filter(is_usable_workspace, self.__server.all_dbs())
def get_workspace_handler(self, ws_name):
return self.__server.get_db(ws_name)
def get_or_create_db(self, ws_name):
return self.__server.get_or_create_db(ws_name)
示例4: uploadFile
def uploadFile(fname, uri, dbname):
print 'Upload contents of %s to %s/%s' % (fname, uri, dbname)
# Connect to the database
theServer = Server(uri)
db = theServer.get_or_create_db(dbname)
# Loop on file for upload
reader = DictReader(open(fname, 'rU'), dialect = 'excel')
# For bulk upload
docs = list()
checkpoint = 100
for doc in reader:
# Convert strings that are really numbers into ints and floats
newdoc = parseDoc(doc)
# Check if doc already exists in the DB
# If it already exists, update it
#if db.doc_exist(newdoc.get('_id')):
# newdoc['_rev'] = db.get_rev(newdoc.get('_id'))
docs.append(newdoc)
if len(docs) % checkpoint == 0:
docs = upload(db, docs)
# Upload the lasr batch
docs = upload(db, docs)
示例5: handle
def handle(self, *args, **options):
quiet = options.get('quiet', False)
prod_indexes = options.get('prod-indexes', False)
docs_root = os.path.normpath(settings.DOCUMENT_ROOT)
if not quiet:
self.stdout.write('Cleaning UP stored files in DOCUMENT_ROOT: %s \n' % docs_root)
shutil.rmtree(docs_root)
os.makedirs(docs_root)
if not quiet:
self.stdout.write('done\n')
if not quiet:
self.stdout.write('Deleting CouchDB debug mode databases.\n')
databases = settings.COUCHDB_DATABASES
server = Server()
try:
for database in databases:
dbname = database[0] + '_test'
if not quiet:
self.stdout.write('Deleting DB: %s\n' % dbname)
server.delete_db(dbname)
if not quiet:
self.stdout.write('done\n')
except Exception, e:
if not quiet:
self.stdout.write('Failed to delete debug databases in CouchDB: %s ' % e)
pass
示例6: __init__
def __init__(self, uri):
self._last_seq_ack = 0
getLogger(self).debug("Initializing CouchDBManager for url [%s]" % uri)
self._lostConnection = False
self.__uri = uri
self.__dbs = {}
self.__seq_nums = {}
self.__serv = NoConectionServer()
self.mutex = threading.Lock()
self._available = False
#setting the doc types to load from couch
def get_types(subclasses):
if len(subclasses):
head = subclasses[0]
tail = []
if len(subclasses[1:]):
tail = subclasses[1:]
return get_types(head.__subclasses__()) + [head.class_signature] + get_types(tail)
return []
self._model_object_types = get_types([ModelObject])
try:
if uri is not None:
self.testCouchUrl(uri)
url = urlparse(uri)
getLogger(self).debug("Setting user,pass %s %s" % (url.username, url.password))
self.__serv = Server(uri=uri)
#print dir(self.__serv)
self.__serv.resource_class.credentials = (url.username, url.password)
self._available = True
except:
getLogger(self).warn("No route to couchdb server on: %s" % uri)
getLogger(self).debug(traceback.format_exc())
示例7: main
def main():
#arguments parser
parser = argparse.ArgumentParser(prog='pushCwe', epilog="Example: ./%(prog)s.py")
parser.add_argument('-c', '--couchdburi', action='store', type=str,
dest='couchdb',default="http://127.0.0.1:5984",
help='Couchdb URL (default http://127.0.0.1:5984)')
#arguments put in variables
args = parser.parse_args()
#default value from ENV COUCHDB
couchdb = os.environ.get('COUCHDB')
#Else from argument
if not couchdb:
couchdb = args.couchdb
__serv = Server(uri = couchdb)
# reports = os.path.join(os.getcwd(), "views", "reports")
workspace = __serv.get_or_create_db("cwe")
# designer.push(reports, workspace, atomic = False)
with open('data/cwe.csv', 'r') as csvfile:
cwereader = csv.reader(csvfile, delimiter=',')
header = cwereader.next()
for cwe in cwereader:
cwe_doc = dict(zip(header, cwe))
workspace.save_doc(cwe_doc)
示例8: main
def main(views_directory, server_uri):
directory = os.path.abspath(views_directory)
server = Server(server_uri)
db = server.get_or_create_db("v1")
loader = FileSystemDocsLoader(directory)
loader.sync(db, debug=True, verbose=True)
示例9: __init__
def __init__(self, databases):
""" initialize couchdbkit handler with COUCHDB_DATABASES
settings """
self.__dict__ = self.__shared_state__
# create databases sessions
for app_name, uri in databases:
try:
if isinstance(uri, tuple):
# case when you want to specify server uri
# and database name specifically. usefull
# when you proxy couchdb on some path
server_uri, dbname = uri
else:
server_uri, dbname = uri.rsplit("/", 1)
except ValueError:
raise ValueError("couchdb uri [%s:%s] invalid" % (
app_name, uri))
res = CouchdbResource(server_uri, timeout=COUCHDB_TIMEOUT)
server = Server(server_uri, resource_instance=res)
app_label = app_name.split('.')[-1]
self._databases[app_label] = server.get_or_create_db(dbname)
示例10: get_prod_db
def get_prod_db(source_uri):
"""
Get the production database object since we need to get some doc_ids from the prod database
"""
prod_db_name = source_uri.split('/')[-1]
prod_server = Server(uri=source_uri[:-len(prod_db_name)])
prod_db = prod_server.get_db(prod_db_name)
return prod_db
示例11: create_db
def create_db():
"""create the db if it don't exist"""
from couchdbkit import Server
server = Server(settings.SERVER_URI)
try:
db = server.create_db(settings.DATABASE_NAME)
except:
pass
示例12: __init__
def __init__(self, server_uri):
server_uri, db_name, docid = parse_uri(server_uri)
if "@" in server_uri:
username, password, server_uri = parse_auth(server_uri)
self.server = Server(server_uri)
self.server.res.add_authorization(httpc.BasicAuth((uri.username, uri.password)))
else:
self.server = Server(server_uri)
self.db = self.server.get_or_create_db("couchdbproxy")
示例13: _list_couch_docs
def _list_couch_docs(self, db_name="dmscouch_test"):
"""Downloads all the documents that are currently in CouchDB now"""
docs = {}
server = Server()
db = server.get_or_create_db(db_name)
r = db.view("dmscouch/all", include_docs=True)
for row in r:
docs[row["doc"]["_id"]] = row["doc"]
return docs
示例14: setUp
def setUp(self):
self.settings = {
"couchdb_uri": "http://admin:[email protected]:5984",
"couchdb_db": "desk_tester",
}
s = Server(self.settings["couchdb_uri"])
self.s = s
s.create_db(self.settings['couchdb_db'])
self.up = CouchdbUploader(path=os.path.dirname(__file__), auth=('admin', 'admin'), **self.settings)
示例15: init_db
def init_db(uri, dbname, main_db=True):
"""Returns a db object and syncs the design documents on demand.
If main_db is set to true then all models will use that one by default.
"""
server = Server(uri)
db = server.get_or_create_db(dbname)
if main_db:
Document.set_db(db)
return db