class TestCaseContextIndependent(unittest.TestCase): def setUp(self): self.app = create_app() self.db = MongoKit(self.app) def tearDown(self): pass def test_register_document(self): self.db.register([BlogPost]) assert len(self.db.registered_documents) > 0 assert self.db.registered_documents[0] == BlogPost def test_bson_object_id_converter(self): converter = BSONObjectIdConverter("/") self.assertRaises(BadRequest, converter.to_python, ("132")) assert converter.to_python("4e4ac5cfffc84958fa1f45fb") == \ ObjectId("4e4ac5cfffc84958fa1f45fb") assert converter.to_url(ObjectId("4e4ac5cfffc84958fa1f45fb")) == \ "4e4ac5cfffc84958fa1f45fb" def test_is_extension_registerd(self): assert hasattr(self.app, 'extensions') assert 'mongokit' in self.app.extensions assert self.app.extensions['mongokit'] == self.db
def initDB(drinkService): global db global app # global connection app = drinkService db = MongoKit(drinkService) #connection = Connection() db.register([Drink])
name = request.form.get("name") if name == None: return owner = db.Owner.query.filter(Owner.name == name).first() if owner == None: return user = User() user.id = name user.is_authenticated = bcrypt.check_password_hash(owner["password"], request.form["password"]) return user login_manager.login_view = "owners.login" db = MongoKit(app) db.register([Owner]) db.register([Expense]) db.register([Category]) app.register_blueprint(owners_blueprint, url_prefix="") app.register_blueprint(expenses_blueprint) app.register_blueprint(categories_blueprint) app.register_blueprint(graphs_blueprint) if __name__ == "__main__": # configuration app.run()
# Flask-MongoKit. from flask.ext.mongokit import MongoKit # Flask. from flask import Flask, request, session, redirect, url_for, abort from flask import render_template, flash # Flaskm. from models import Entry app = Flask(__name__) app.config.from_object('settings.DevelopmentConfig') db = MongoKit(app) db.register([Entry]) @app.route('/') def show_entries(): entries = db.Entry.find().sort('_id', -1) return render_template('show_entries.html', entries=entries) @app.route('/add') def add_entry(): entry = db.Entry() if not session.get('logged_in'): abort(401)
from flask.ext.mongokit import MongoKit from .data import Data # Register models to the database db = MongoKit() db.register([Data])
use_dot_notation = True class Activities(Document): __collection__ = 'activities' structure = { 'name': unicode, 'currentActivity': unicode, 'MemberID': unicode, 'location': unicode, 'loggedIn': datetime, } default_values = {'loggedIn': datetime.utcnow} use_dot_notation = True db = MongoKit(app) db.register([Members]) db.register([Activities]) @app.route('/getSignIn', methods=['GET','POST']) def getSignIn(): global checkCheck global member_name global member_ID global isIn print isIn if(checkCheck == True): print "Sending confirmation for check in"; list = {'newCheckin': checkCheck, 'isMember' : isMember,'member_ID' : member_ID, 'name' : member_name, 'isIn' : isIn} checkCheck = False return jsonify(list)
#-------------------------------------- # setup for celery #-------------------------------------- celery = make_celery(app) #-------------------------------------- # setup for mongokit #-------------------------------------- db = MongoKit(app) from app.apis.models import CaptureObj, User #register to db db.register([CaptureObj, User]) #-------------------------------------- # setup for blueprints #-------------------------------------- from app.apis import apis app.register_blueprint(apis) #-------------------------------------- # default controler #-------------------------------------- @app.route('/favicon.ico') def favicon():
#-*- coding: utf-8 -*- from flask import Flask,request,session,abort,redirect, jsonify,Response from bson.objectid import ObjectId from flask.ext.mongokit import MongoKit,BSONObjectIdConverter from functools import wraps from hashlib import md5 import time,json,models,urllib2 from bson.objectid import ObjectId app = Flask(__name__) app.secret_key="8E9852FD04BA946D51DE36DFB08E1DB6" db = MongoKit(app) db.register([models.UserModel,models.ResourceModel,models.VisualModel]) INFLUXDB_BASE="http://112.74.85.237:8086" INFLUXDB_AUTH="u=root&p=root" def json_wrapper(r,direct=False): if direct: return Response('{"ok":true,"data":'+(r.to_json())+'}', mimetype='application/json') else: results = [item.to_json() for item in r] return Response('{"ok":true,"data":['+(','.join(results))+']}', mimetype='application/json') ''' def updateDBPermission(email): user=db.UserModel.find_one({"Email",email}) if(user==None): return owned=db.ResourceModel.find({"Owner":user["Email"]})
'created_at':datetime.datetime } required_fields = ['title', 'tagline', 'created_at', 'unique_url'] default_values = {'created_at':datetime.datetime.utcnow, 'title':u'*', 'tagline':u''} use_dot_notation = True indexes = [ { 'fields':['unique_url'], 'unique':True } ] db = MongoKit(app) db.register([Project]) def length(max=-1, words = True): if words: message = 'must be %d words or less.' % max else: message = 'must be %d characters long or less.' % max def _length(form, field): if words: l = field.data and len(field.data.split()) or 0 else: l = field.data and len(field.data) or 0 if max != -1 and l > max: raise ValidationError(field.label.text + " " + message)
app = Flask(__name__) class Task(Document): __collection__ = 'tasks' structure = { 'title': unicode, 'text': unicode, 'creation': datetime, } required_fields = ['title', 'creation'] default_values = {'creation': datetime.utcnow()} use_dot_notation = True db = MongoKit(app) db.register([Task]) @app.route('/') def show_all(): tasks = db.Task.find() return render_template('list.html', tasks=tasks) @app.route('/<ObjectId:task_id>') def show_task(task_id): task = db.Task.get_from_id(task_id) return render_template('task.html', task=task) @app.route('/new', methods=["GET", "POST"])
from bson.objectid import ObjectId from flask import Flask, request, abort, jsonify from flask.ext.mongokit import MongoKit from mongokit import ValidationError from combat.conf import QUERY_LIMIT, OUTPUT_ROUND from combat.deck import DeckReco, FakeDeckRule from combat.models import Duel, Deck, User from combat.utils import crossdomain, json_response from combat.ranking import elo_add, rank app = Flask(__name__) app.config.from_object('combat.conf') db = MongoKit(app) db.register([Duel, Deck, User]) update_ranking = """ var rank = 0; var prev = 0; db.%(c)s.find().sort({rating: -1}).forEach(function(s){ if (prev != s.rating){ rank++; } db.%(c)s.update({_id:s._id}, {$set: {ranking: NumberInt(rank)}}); prev = s.rating; }) """ def get_user(username):
class Activities(Document): __collection__ = 'activities' structure = { 'name': unicode, 'currentActivity': unicode, 'MemberID': unicode, 'location': unicode, 'loggedIn': datetime, } default_values = {'loggedIn': datetime.utcnow} use_dot_notation = True db = MongoKit(app) db.register([Members]) db.register([Activities]) # @app.route('/checkin', methods=['GET', 'POST']) # def checkin(): # global location # global member_ID # member_ID = request.form['cardID'] # if db.Members.find({'MemberID': {"$eq": member_ID}}): # flash('Account already exists for ' +member_name +' memberID: ' +member_ID) # return redirect(url_for('activity')) # return @app.route('/', methods=["GET", "POST"]) def sign_in():
'project_type': basestring, 'module_list': [basestring], 'svn_list': [basestring], 'status': basestring, 'desc': basestring, 'creation': datetime, } required_fields = ['project_name'] default_values = {'creation': datetime.utcnow} use_dot_notation = True # indexes = [{'fields': 'project_name', 'unique': True}] class Script(Document): __collection__ = 'script' structure = { 'script_name': basestring, 'script_argument': basestring, 'script_content': basestring, 'script_type': basestring, 'desc': basestring, 'creation': datetime, 'modify': datetime, } required_fields = ['script_name'] default_values = {'creation': datetime.utcnow, 'modify': datetime.utcnow} use_dot_notation = True # indexes = [{'fields': 'script_name', 'unique': True}] db = MongoKit(app) db.register([Device, Idc, Module, Script, Project])
# create the application object app = make_json_app("AABackend") # setup basedir if AABACKEND_BASEDIR_ENV_KEY in os.environ: AABACKEND_BASEDIR = os.environ[AABACKEND_BASEDIR_ENV_KEY] if AABACKEND_SETTINGS_ENV_KEY in os.environ: app.config.from_envvar(AABACKEND_SETTINGS_ENV_KEY) else: app.config.from_pyfile('backend.cfg') # connect to the database #db = Connection(Model.config.get('backend', 'dburi')) db = MongoKit(app) db.register( [Worker, Job, App, AppStoreApp, CydiaApp, Run, Result, Account, Device]) # This will prevent errors due to missing dbref info # just instantiate each document once # especially: this will prevent getandsetworker to fail once with app.app_context(): for doc in db.registered_documents: db[doc.__name__]() ### ### REST API ### # serve the frontend @app.route('/')
from flask.ext.mongokit import MongoKit from models import Entry, Feed, User, GoodToken, BadToken db = MongoKit() db.register([Entry, Feed, User, GoodToken, BadToken])
FB_APP_NAME = json.loads(requests.get(app_url).content).get('name') FB_APP_SECRET = os.environ.get('FACEBOOK_SECRET') current_user = None app = Flask(__name__) app.config.from_object(__name__) app.config.from_object('conf.Config') app.secret_key = '\x92\xaa\x81l\x10m\x8c\x97\xc1\xd7\x93\x95\xb9\xfbrC\xf9\xff:~D\xbf\x97\x86' # app.config["MONGODB_DATABASE"] = DB_NAME # app.config["MONGODB_HOST"] = MONGODB_URI db = MongoKit(app) db.register([User, Game, PlayRequest, Challenge]) # db.users.drop() # try: # connection = pymongo.Connection(MONGODB_URI) # db = connection[DB_NAME] # except: # print('Error: Unable to connect to database') # connection = None # if connection is not None: # db.pokemon.insert({"name": "Pika"}) # app.config['MONGO_URI'] = "mongodb://*****:*****@ds061777.mongolab.com:61777/heroku_app15232410" # mongo = PyMongo(app # mongo.db.pokemon.insert({name: "Pika"})
# create the application object app = make_json_app("AABackend") # setup basedir if AABACKEND_BASEDIR_ENV_KEY in os.environ: AABACKEND_BASEDIR = os.environ[AABACKEND_BASEDIR_ENV_KEY] if AABACKEND_SETTINGS_ENV_KEY in os.environ: app.config.from_envvar(AABACKEND_SETTINGS_ENV_KEY) else: app.config.from_pyfile('backend.cfg') # connect to the database #db = Connection(Model.config.get('backend', 'dburi')) db = MongoKit(app) db.register([Worker, Job, App, AppStoreApp, CydiaApp, Run, Result, Account, Device]) # This will prevent errors due to missing dbref info # just instantiate each document once # especially: this will prevent getandsetworker to fail once with app.app_context(): for doc in db.registered_documents: db[doc.__name__]() ### ### REST API ### # serve the frontend @app.route('/')
name = request.form.get('name') if name == None: return owner = db.Owner.query.filter(Owner.name == name).first() if owner == None: return user = User() user.id = name user.is_authenticated = bcrypt.check_password_hash( owner["password"], request.form['password']) return user login_manager.login_view = "owners.login" db = MongoKit(app) db.register([Owner]) db.register([Expense]) db.register([Category]) app.register_blueprint(owners_blueprint, url_prefix='') app.register_blueprint(expenses_blueprint) app.register_blueprint(categories_blueprint) app.register_blueprint(graphs_blueprint) if __name__ == '__main__': # configuration app.run()
from flask import Flask, request, render_template, redirect, url_for from flask.ext.mongokit import MongoKit from bson.objectid import ObjectId from models import Task app = Flask(__name__) db = MongoKit(app) db.register([Task]) @app.route('/') def show_all(): tasks = db.Task.find() return render_template('index.html', tasks=tasks) @app.route('/create', methods=['POST']) def add_task(): body = request.form['body'] title = request.form['title'] task = db.Task() task.title = title task.body = body task.save() tasks = db.Task.find() return redirect(url_for('show_all'))
#-------------------------------------- # setup for celery #-------------------------------------- celery = make_celery(app) #-------------------------------------- # setup for mongokit #-------------------------------------- db = MongoKit(app) from app.apis.models import CaptureObj, User #register to db db.register([CaptureObj, User]) #-------------------------------------- # setup for blueprints #-------------------------------------- from app.apis import apis app.register_blueprint(apis) #-------------------------------------- # default controler #-------------------------------------- @app.route('/favicon.ico') def favicon(): return send_from_directory(os.path.join(app.root_path, 'static'), 'ico/favicon.ico')
#DB Structure structure = { 'id': int, 'title': unicode, 'text': unicode, 'creation': datetime, } default_values = {'creation': datetime.utcnow} #dont know why required, dont remove use_dot_notation = True #connection of database, requires mongod first in terminal running on port. # brew install mongodb db = MongoKit(app) #registers Post class in DB db.register([Post]) #generates id def generate(): u = int(random.random()*100000) return u @app.route('/add', methods=["GET", "POST"]) #declaring request methods #new post def new_post(): #POST request if request.method == 'POST': #declaring new post
from models import Event, User, Comment from flask import Flask, render_template, request, redirect, url_for from flask.ext.mongokit import MongoKit, BSONObjectIdConverter from flask.ext.socketio import SocketIo, emit import os app = Flask(__name__) app.debug = True #Setup Mongo app.config['MONGODB_HOST'] = 'localhost' app.config['MONGODB_PORT'] = 27017 app.config['MONGODB_DATABASE'] = 'test' db = MongoKit(app) db.register([Event, User, Comment]) app.url_map.converters['objectid'] = BSONObjectIdConverter #Setup SocketIO @app.context_processor def override_url_for(): return dict(url_for=dated_url_for) def dated_url_for(endpoint, **values): if endpoint == 'static': filename = values.get('filename', None) if filename: file_path = os.path.join(app.root_path, endpoint, filename) values['q'] = int(os.stat(file_path).st_mtime)