def count(self): url = os.getenv( 'MONGOLAB_URI', 'mongodb://*****:*****@ds031741.mongolab.com:31741/heroku_app29441400' ) parsed = urlsplit(url) db_name = parsed.path[1:] # Get your DB db = Connection(url)[db_name] # Authenticate if '@' in url: user, password = parsed.netloc.split('@')[0].split(':') db.authenticate(user, password) count_dict = db.Counters.find_one('visitors') if not count_dict: count = 0 db.Counters.insert({'_id': 'visitors', 'count': count}) else: count = count_dict['count'] count += 1 # insert updated count into database db.Counters.save({'_id': 'visitors', 'count': count}) if count % 10 == 1: return str(count) + 'st' elif count % 10 == 2: return str(count) + 'nd' elif count % 10 == 3: return str(count) + 'rd' else: return str(count) + 'th'
def __init__(self, host, db, port=27017, user=None, password=None, bucket='fs', collection=None, **kwargs): """ Establish the connection with the mongo backend and connect to the collections :param collection: ignores but provided for consistency w/ other doc_store_config patterns """ logging.debug( 'Using MongoDB for static content serving at host={0} db={1}'. format(host, db)) _db = Connection(host=host, port=port, **kwargs)[db] if user is not None and password is not None: _db.authenticate(user, password) self.fs = gridfs.GridFS(_db, bucket) self.fs_files = _db[bucket + ".files"] # the underlying collection GridFS uses
def counts_collection(address='localhost:29000'): from psage.lmfdb.auth import userpass user, password = userpass() from pymongo import Connection from pymongo.connection import DuplicateKeyError C = Connection(address).research C.authenticate(user, password) return C.ellcurves
def __init__(self, host, db, port=27017, user=None, password=None, bucket="fs", **kwargs): # logging.debug('Using MongoDB for static content serving at host={0} db={1}'.format(host, db)) _db = Connection(host=host, port=port, **kwargs)[db] self.db = _db if user is not None and password is not None: _db.authenticate(user, password) self.fs = gridfs.GridFS(_db, bucket) self.fs_files = _db[bucket + ".files"] # the underlying collection GridFS uses
def f(l_min, l_max): from pymongo import Connection C = Connection(address).research C.authenticate(user, password) C = C.ellcurves for v in C.find({'level':{'$gte':level_min, '$lt':level_max}, 'sel2':{'$exists':False}}): sel2 = selmer2(eval(v['weq']), max_time) C.update({'_id':v['_id']}, {'$set':{'sel2':sel2}})
def __init__(self, host, db, port=27017, user=None, password=None, **kwargs): logging.debug('Using MongoDB for static content serving at host={0} db={1}'.format(host, db)) _db = Connection(host=host, port=port, **kwargs)[db] if user is not None and password is not None: _db.authenticate(user, password) self.fs = gridfs.GridFS(_db) self.fs_files = _db["fs.files"] # the underlying collection GridFS uses
def f(l_min, l_max): from pymongo import Connection C = Connection(address).research C.authenticate(user, password) C = C.ellcurves for v in C.find({'level':{'$gte':level_min, '$lt':level_max}, 'number':1, 'ap':{'$exists':False}}): E = pari('ellinit(%s,1)'%v['weq']) ap = dict([(str(p),int(E.ellap(p))) for p in P]) C.update({'_id':v['_id']}, {'$set':{'ap':ap}})
def f(l_min, l_max): from pymongo import Connection C = Connection(address).research C.authenticate(user, password) C = C.ellcurves for v in C.find({'level':{'$gte':level_min, '$lt':level_max}, 'number':1, 'L0s':{'$exists':False}}): L = Lfunction_from_elliptic_curve(EllipticCurve(eval(v['weq'])), 10**5) z = L.find_zeros_via_N(num_zeros) L0s = dict([(str(i),float(z[i])) for i in range(len(z))]) C.update({'_id':v['_id']}, {'$set':{'L0s':L0s}})
def setup_admin_user(self, port=mongod_port): db = Connection( "localhost" , int(port) ).admin try: db.authenticate("admin","password") except OperationFailure, e: try: db.add_user("admin","password") except OperationFailure, e: if e.message == 'need to login': pass # SERVER-4225 else: raise e
def setup_admin_user(self, port=mongod_port): db = Connection("localhost", int(port)).admin try: db.authenticate("admin", "password") except OperationFailure, e: try: db.add_user("admin", "password") except OperationFailure, e: if e.message == 'need to login': pass # SERVER-4225 else: raise e
def import_table(address, aplists_txt_filename, max_level=None): """ Import a text table of eigenvalues, using upsert to avoid replication of data. """ from psage.lmfdb.auth import userpass user, password = userpass() from sage.databases.cremona import cremona_letter_code from psage.modform.hilbert.sqrt5.sqrt5 import F labels, primes = labeled_primes_of_bounded_norm(F, 100) from pymongo import Connection C = Connection(address).research if not C.authenticate(user, password): raise RuntimeError, "failed to authenticate" e = C.ellcurves_sqrt5 for X in open(aplists_txt_filename).read().splitlines(): if X.startswith('#'): continue Nlevel, level, iso_class, ap = X.split('\t') ap = str_to_apdict(ap, labels) Nlevel = int(Nlevel) iso_class = cremona_letter_code(int(iso_class)) v = {'level':level, 'iso_class':iso_class, 'number':1, 'Nlevel':Nlevel, 'ap':ap} if max_level and Nlevel > max_level: break print v spec = dict(v) del spec['ap'] e.update(spec, v, upsert=True, safe=True) return e
def __init__(self, host, db, port=27017, user=None, password=None, bucket="fs", collection=None, **kwargs): """ Establish the connection with the mongo backend and connect to the collections :param collection: ignores but provided for consistency w/ other doc_store_config patterns """ logging.debug("Using MongoDB for static content serving at host={0} db={1}".format(host, db)) _db = Connection(host=host, port=port, **kwargs)[db] if user is not None and password is not None: _db.authenticate(user, password) self.fs = gridfs.GridFS(_db, bucket) self.fs_files = _db[bucket + ".files"] # the underlying collection GridFS uses
def connectToDatabase(): """ Get a handle on the mongo db object """ if connectToDatabase.LOCAL: try: connection = pymongo.Connection() except: print "connectToDatabase() - Failed to open connect to MongoDB" raise try: db = connection['i_got_beef'] except: print "connectToDatabase() - Failed to connect to summer_of_george db" raise return db else: ''' try: url = os.getenv('MONGOLAB_URI', 'mongodb://localhost:27017/testdb') parsed = urlsplit(url) db_name = parsed.path[1:] except: print "MONGOLAB_URI not properly encoded" raise ''' try: # Get your DB db = Connection(url)[db_name] except: print "Failed to connect to MONGOLAB database" raise try: db.authenticate(user_pass[0], user_pass[1]) except: print "Failed to authenticate MONGOLAB" raise return db
def f(l_min, l_max): from pymongo import Connection C = Connection(address).research C.authenticate(user, password) C = C.ellcurves for v in C.find({ 'level': { '$gte': level_min, '$lt': level_max }, 'number': 1, 'L0s': { '$exists': False } }): L = Lfunction_from_elliptic_curve(EllipticCurve(eval(v['weq'])), 10**5) z = L.find_zeros_via_N(num_zeros) L0s = dict([(str(i), float(z[i])) for i in range(len(z))]) C.update({'_id': v['_id']}, {'$set': {'L0s': L0s}})
def make_conn(host, port, database, username=None, password=None, slave_okay=False): try: conn = Connection(host, port, slave_okay=slave_okay) except ConnectionFailure: raise Exception('Unable to connect to MongoDB') if username and password: auth = conn.authenticate(username, password) if not auth: raise Exception('Authentication to MongoDB failed') return conn
def import_table(address, table_filename, max_level=None): """ Import a text table of weq's, using upsert to avoid replication of data. Format is like this: :: 31 5*a-2 0 -3 2 -2 2 4 -4 4 -4 -2 -2 ? ? -6 -6 12 -4 6 -2 -8 0 0 16 10 -6 [1,a+1,a,a,0] 31 5*a-3 0 -3 2 -2 2 -4 4 -4 4 -2 -2 ? ? -6 -6 -4 12 -2 6 0 -8 16 0 -6 10 [1,-a-1,a,0,0] 36 6 0 ? ? -4 10 2 2 0 0 0 0 -8 -8 2 2 -10 -10 2 2 12 12 0 0 10 10 [a,a-1,a,-1,-a+1] """ from psage.modform.hilbert.sqrt5.sqrt5 import F from sage.databases.cremona import cremona_letter_code from aplists import labeled_primes_of_bounded_norm, str_to_apdict labels, primes = labeled_primes_of_bounded_norm(F, 100) from psage.lmfdb.auth import userpass user, password = userpass() from pymongo import Connection C = Connection(address).research if not C.authenticate(user, password): raise RuntimeError, "failed to authenticate" e = C.ellcurves_sqrt5 for X in open(table_filename).read().splitlines(): if X.startswith('#'): continue z = X.split() Nlevel = z[0] level = z[1] iso_class = z[2] weq = z[-1] ap = ' '.join(z[3:-1]) ap = str_to_apdict(ap, labels) Nlevel = int(Nlevel) iso_class = cremona_letter_code(int(iso_class)) v = { 'level': level, 'iso_class': iso_class, 'number': 1, 'Nlevel': Nlevel, 'ap': ap, 'weq': weq } if max_level and Nlevel > max_level: break print v spec = dict(v) del spec['weq'] e.update(spec, v, upsert=True, safe=True)
def __init__(self): try: conn = Connection('127.0.0.1', 27017).ukrgadget conn.authenticate('skl1f', 'ukr') self.database = conn['Articles'] except errors.AutoReconnect as er: print('Error database connection:', er) try: self.loader = Loader( "/home/skl1f/code/ukrgadget.com/templates") except: pass handlers = [ # (r'/data.json', LongRequestHandler), # (r'/page/', PaginateRequestHandler), # (r'/page/([0-9]+)', PaginateRequestHandler), (r'/admin/edit/(.*)', EditHandler), (r'/', MainHandler), (r'/admin/list/', ListHandler), (r'/admin/list/([0-9]+)', ListHandler), (r'/admin/new/', NewHandler), (r'/admin/delete/(.*)', DeleteHandler), (r'/admin/post/(.*)', PostHandler), (r'/admin/twit/(.*)', TwitHandler), ] settings = dict( cookie_secret='43oETzKXQAGaYdk6fd8fG1kJFuYh7EQnp2XdTP1o/Vo=', template_path=os.path.join(os.path.dirname(__file__), 'templates'), static_path=os.path.join(os.path.dirname(__file__), 'static'), xsrf_cookies=True, autoescape=False, login_url='/admin/new/', # debug=True, ) tornado.web.Application.__init__(self, handlers, **settings)
def ellcurves_sqrt5(address='localhost:29000', username=None, password=None): from sage.databases.cremona import cremona_letter_code from psage.modform.hilbert.sqrt5.sqrt5 import F from aplists import labeled_primes_of_bounded_norm labels, primes = labeled_primes_of_bounded_norm(F, 100) from pymongo import Connection C = Connection(address).research if username is None or password is None: from psage.lmfdb.auth import userpass username, password = userpass() if not C.authenticate(username, password): raise RuntimeError, "failed to authenticate" return C.ellcurves_sqrt5
def import_table(address, table_filename, max_level=None): """ Import a text table of weq's, using upsert to avoid replication of data. Format is like this: :: 31 5*a-2 0 -3 2 -2 2 4 -4 4 -4 -2 -2 ? ? -6 -6 12 -4 6 -2 -8 0 0 16 10 -6 [1,a+1,a,a,0] 31 5*a-3 0 -3 2 -2 2 -4 4 -4 4 -2 -2 ? ? -6 -6 -4 12 -2 6 0 -8 16 0 -6 10 [1,-a-1,a,0,0] 36 6 0 ? ? -4 10 2 2 0 0 0 0 -8 -8 2 2 -10 -10 2 2 12 12 0 0 10 10 [a,a-1,a,-1,-a+1] """ from psage.modform.hilbert.sqrt5.sqrt5 import F from sage.databases.cremona import cremona_letter_code from aplists import labeled_primes_of_bounded_norm, str_to_apdict labels, primes = labeled_primes_of_bounded_norm(F, 100) from psage.lmfdb.auth import userpass user, password = userpass() from pymongo import Connection C = Connection(address).research if not C.authenticate(user, password): raise RuntimeError, "failed to authenticate" e = C.ellcurves_sqrt5 for X in open(table_filename).read().splitlines(): if X.startswith('#'): continue z = X.split() Nlevel = z[0]; level = z[1]; iso_class = z[2]; weq = z[-1] ap = ' '.join(z[3:-1]) ap = str_to_apdict(ap, labels) Nlevel = int(Nlevel) iso_class = cremona_letter_code(int(iso_class)) v = {'level':level, 'iso_class':iso_class, 'number':1, 'Nlevel':Nlevel, 'ap':ap, 'weq':weq} if max_level and Nlevel > max_level: break print v spec = dict(v) del spec['weq'] e.update(spec, v, upsert=True, safe=True)
# coding=utf-8 from django.shortcuts import render_to_response from django.template import RequestContext from pymongo import Connection import gridfs from query_json.db import province_list from mongo_models import db_name, db_username, db_password db = Connection()[db_name] db.authenticate(db_username, db_password) fs = gridfs.GridFS(db) def place_details(request): plist = [(p["name"], p["region-code"]) for p in province_list] return render_to_response("place/details.html", {"province_list": plist}, context_instance=RequestContext(request))
from pymongo import Connection from wisewolf.config import DB_HOST, MONGO_AUTHENTICATE, PSQL_AUTHENTICATE, REDIS_INDEX from redis import Redis, ConnectionPool import psycopg2 #redis_RoomSession= Redis(db= REDIS_INDEX['chatting_rooms']) #redis_UserSession= Redis(db= REDIS_INDEX['user_sessions']) redis_UserSession= Redis(connection_pool= ConnectionPool(host=DB_HOST, db=REDIS_INDEX['user_sessions'])) redis_RoomSession= Redis(connection_pool= ConnectionPool(host=DB_HOST, db=REDIS_INDEX['chatting_rooms'])) Mongo_Wisewolf= Connection(['165.194.104.192','165.194.104.192:40001','165.194.104.192:40002'], w=2, wtimeout= 200, use_greenlets= True).wisewolf #Mongo_Wisewolf= Connection(['165.194.104.192','165.194.104.192:40001','165.194.104.192:40002'], w='majority', wtimeout= 200).wisewolf Mongo_Wisewolf.authenticate(MONGO_AUTHENTICATE["id"],MONGO_AUTHENTICATE["passwd"]) con= psycopg2.connect(database='wisewolf', user=PSQL_AUTHENTICATE["user"], password=PSQL_AUTHENTICATE["passwd"], host=DB_HOST) Psql_Cursor= con.cursor()
from django.conf import settings from bson import ObjectId import pymongo as pymongo from pymongo import Connection from datetime import datetime import requests from django.contrib.auth import logout as auth_logout from django.core.mail import send_mail db = Connection(host=getattr(settings, "MONGODB_HOST", None), port=getattr(settings, "MONGODB_PORT", None))[settings.MONGODB_DATABASE] if getattr(settings, "MONGODB_USERNAME", None): db.authenticate(getattr(settings, "MONGODB_USERNAME", None), getattr(settings, "MONGODB_PASSWORD", None)) def get_user_pic(uid): url = "http://graph.facebook.com/%s/picture?type=large" % uid pic = requests.get(url) return pic.url def get_user_gender(first_name): url = "http://api.genderize.io?name=%s" % first_name r = requests.get(url) return r.json()['gender'] # Create your views here.
from pymongo import Connection from wisewolf.common.MongoDao import MongoDao db= Connection(['165.194.104.192','165.194.104.192:40001','165.194.104.192:40002']).test_wisewolf db.authenticate("test_wisewolf","test_wisewolf") MongoDao= MongoDao(db)
from pymongo import Connection from wisewolf.common.MongoDao import MongoDao db = Connection( ['165.194.104.192', '165.194.104.192:40001', '165.194.104.192:40002']).test_wisewolf db.authenticate("test_wisewolf", "test_wisewolf") MongoDao = MongoDao(db)
app.secret_key = 'not really a secret' app.debug = True if 'MONGOLAB_URI' in os.environ: url = urlparse(os.environ['MONGOLAB_URI']) conn = Connection(host=url.hostname, port=url.port) db_name = url.path[1:] db = conn[db_name] db.authenticate(url.username, url.password) elif os.environ['_'] == './tests.py': db = Connection().numbers_game_test elif 'remote_prod' in os.environ: url = urlparse('mongodb://*****:*****@ds037627-a.mongolab.com:37627/heroku_app7269959') conn = Connection(host=url.hostname, port=url.port) db_name = url.path[1:] db = conn[db_name] db.authenticate(url.username, url.password) else: db = Connection().numbers_game_dev @app.route('/<lp_slug>/') def make_iframe(lp_slug): ap_id = request.args['ap_id'] product = db.products.find_one({'lp_slug': lp_slug}) landing_url = product.landing_url(ap_id) return render_template('iframe_template.html', landing_url=landing_url) if __name__ == '__main__': app['Development'] = True app.run(debug=True)
from bson.code import Code from bson.objectid import ObjectId # from flask.ext.olinauth import OlinAuth, auth_required, current_user, get_current_user from flask.ext.jsonpify import jsonify import requests MONGO_URL = os.getenv('MONGOLAB_URI', "mongodb://*****:*****@' in MONGO_URL: user_pass = parsed_mongo.netloc.split('@')[0].split(':') db.authenticate(user_pass[0], user_pass[1]) # Shortcuts for collections. users = db.users binds = db.binds places = db.places positions = db.positions """ binds.drop() users.drop() places.drop() positions.drop() users.create_index("username", unique=True) """
# coding=utf-8 from pymongo import Connection from myway.mongo_models import * from myway.query_json.db import city_by_name, children_of origin = Connection(host='204.62.14.55').dianping origin.authenticate('dianping','crawler') site_name = '无锡站'.decode('utf-8') cname = '无锡'.decode('utf-8') districts = [d.decode('utf-8') for d in ['惠山区','锡山区','滨湖区','崇安区','南长区','北塘区', '江阴市','宜兴市','新区']] def null_handler(record): pass def hotel_handler(record): pass def restraunt_handler(record): if Restraunt.objects(name=record['name']) \ or record.get('rating',0) < 2 \ or record.get('n_rating',0) < 2: return r = Restraunt(name = record['name']) # transport every attribute that has same name for key in dict(record).keys(): if key in r.__dict__['_data'].keys() and key not in ['category']: r.__dict__['_data'][key] = record[key] city = record['city']
from open_facebook import OpenFacebook import json from bson import ObjectId import pymongo as pymongo from pymongo import Connection from datetime import datetime from ncog.predictor import calculate_scores db = Connection( host=getattr(settings, "MONGODB_HOST", None), port=getattr(settings, "MONGODB_PORT", None) )[settings.MONGODB_DATABASE] if getattr(settings, "MONGODB_USERNAME", None): db.authenticate(getattr(settings, "MONGODB_USERNAME", None), getattr(settings, "MONGODB_PASSWORD", None)) @shared_task def getUserInbox(user): access_token = user.access_token facebook = OpenFacebook(access_token) inbox = facebook.get('/me/inbox') inbox2 = facebook.get(inbox['paging']['next'].split("v2.0")[1]) return breadthlooper(inbox,user, facebook) def breadthlooper( inbox, user, facebook): combined_list = [] list_to = []
from pymongo import Connection from wisewolf.config import DB_HOST, MONGO_AUTHENTICATE, PSQL_AUTHENTICATE, REDIS_INDEX from redis import Redis, ConnectionPool import psycopg2 #redis_RoomSession= Redis(db= REDIS_INDEX['chatting_rooms']) #redis_UserSession= Redis(db= REDIS_INDEX['user_sessions']) redis_UserSession = Redis(connection_pool=ConnectionPool( host=DB_HOST, db=REDIS_INDEX['user_sessions'])) redis_RoomSession = Redis(connection_pool=ConnectionPool( host=DB_HOST, db=REDIS_INDEX['chatting_rooms'])) Mongo_Wisewolf = Connection( ['165.194.104.192', '165.194.104.192:40001', '165.194.104.192:40002'], w=2, wtimeout=200, use_greenlets=True).wisewolf #Mongo_Wisewolf= Connection(['165.194.104.192','165.194.104.192:40001','165.194.104.192:40002'], w='majority', wtimeout= 200).wisewolf Mongo_Wisewolf.authenticate(MONGO_AUTHENTICATE["id"], MONGO_AUTHENTICATE["passwd"]) con = psycopg2.connect(database='wisewolf', user=PSQL_AUTHENTICATE["user"], password=PSQL_AUTHENTICATE["passwd"], host=DB_HOST) Psql_Cursor = con.cursor()
def mongo_conn(host='localhost', db='xmodule', port=27017, user=None, password=None, **kwargs): db = Connection(host=host, port=port, **kwargs)[db] if user is not None and password is not None: db.authenticate(user, password) return db