def setUp(self): app = Flask(__name__) mongo = mongomock.MongoClient() crud.crud(app, mongo, 'tests') self.app = app.test_client() self.objects = [dict(foo='bar'), dict(foo='rab')] self.objects = [ dict(current=obj.copy(), base=obj.copy(), patch=[]) for obj in self.objects ] obj = self.objects[0]['current'].copy() obj['bat'] = 'br' obj['foo'] = 'br' patch = jsonpatch.make_patch(self.objects[0]['current'], obj).patch patch[0]['time'] = utils.unix_time( utils.date_to_datetime('2016-01-01')) patch[1]['time'] = utils.unix_time( utils.date_to_datetime('2017-01-01')) self.objects[0]['patch'] = patch self.objects[0]['current'] = obj for obj in self.objects: obj['_id'] = mongo.db.tests.insert(obj)
def interact(w=None): if w: crud_helper = crud.crud("/Users/john/python_workspace/words/kb") r = rule.rule() m = dict.match(crud_helper,w["form"]["spelling"]) f = dict.filter(r,w) list(w) else: crud_helper = crud.crud("/Users/john/python_workspace/words/kb") is_edit = False is_review = False while(True): if (not w): is_edit = False is_review = True if (is_edit): print "#edit> ", elif(is_review): print "#review> ", else: print "#query> ", c = raw_input() if (is_edit): if (c == "q"): is_edit = False elif (c == "h"): usage2() elif (is_review): if (c == "q"): if (not w): break is_review = False if (c == "l"): crud_helper.list() else: if (c == "q"): break elif (c == "h"): usage() elif (c == "l"): list(w) elif (c == "a"): crud_helper.create(w) crud_helper.export("/Users/john/python_workspace/words/kb") break elif (c == "e"): is_edit = True elif (c == "r"): is_review = True elif (c == "c"): crud_helper.create(w) elif (c == "x"): crud_helper.export("/Users/john/python_workspace/words/kb") return ""
def crud(): blue = Blueprint('analytics', __name__, template_folder='templates') from crud import crud crud(blue, analytics) jump_back = 5 - 1 @blue.route('/live/', methods=['GET', 'POST']) @blue.route('/live/<int:limit>', methods=['GET', 'POST']) @blue.route('/live/<int:limit>/<int:skip>', methods=['GET', 'POST']) def live(limit=5, skip=None): if not skip: skip = analytics.count() - jump_back skip = 5 documents = analytics.find( {'order': { "$gte": skip, "$lt": skip + limit }}) documents = [obj2str(document) for document in documents] _documents = {} for document in documents: if document['collection'] not in _documents: _documents[document['collection']] = [] _documents[document['collection']].append( ObjectId(document['document'])) for _collection, _ids in _documents.items(): from importlib import import_module mod = import_module('config') collection = getattr(mod, _collection) _documents[_collection] = collection.find({'_id': {"$in": _ids}}) _documents[_collection] = [ obj2str(document) for document in _documents[_collection] ] _list = [] for collection_name, collection_set in _documents.items(): _list.extend(collection_set) _list = {'list': _list, 'analytic_order': skip + limit} return jsonify(_list) trending = {} @blue.route('/trending/*') def clear_trending(): trending.clear() return "['success', 200]", 200 @blue.route('/trending/<_id>+') def insert_trending(_id): trending[_id] = True return "['success', 200]", 200 @blue.route('/trending/-') def get_trending(): return jsonify(show_trending()) return blue
def requestHandler(fun, parameters="/"): crudObj = crud() if fun == "insert" and request.method == "POST": return crudObj.insert(request.form.to_dict()) elif fun == "list" and request.method == "GET": return crudObj.list(parameters) elif fun == "update" and request.method == "POST": return crudObj.update(request.form.to_dict(), parameters) elif fun == "delete" and request.method == "GET": return crudObj.delete(parameters) else: return "Invalid Operation or Method!"
from config import categories from crud import crud from utility import request_attributes from pymongo import DESCENDING blue = Blueprint('categories', __name__) """ ancestors: [ { title: _id: } ] """ crud(blue, categories, skeleton={ 'title': '', 'ancestors': [], }) @blue.route('/sug/') def suggest_categories(query, size): query = query if query else request_attributes(request, query=str)['query'] size = size if size else request_attributes(request, size=int)['size'] __categories = categories.find( {'$or': [ {'$text': {'$search': query}}, {'title': {'$regex': query}}, ] }, {"score": {
wish_list = user['wish_list'] _pr = wish_list['products'] _pr = products.find({"_id": {"$in": _pr}}) _hows = wish_list['hows'] _hows = hows.find({'_id': {"$in": _hows}}) context = { 'products': [obj2str(_home) for _home in _pr], 'hows': [obj2str(_home) for _home in _hows], 'messages': messages } return {'user': user}, context blue = Blueprint('users', __name__, template_folder='templates') crud(blue, users, template='user/index', load_document=load_user) @blue.route('/me') @login_required def get_profile(): return render_template('user/profile.html') @blue.route('/me$', methods=['GET', 'POST']) @login_required def update_profile(): from pymongo import ReturnDocument try: node = request.values['node'] _json = request_json(request, specific_type=None)
from flask import Blueprint, request, jsonify, render_template from config import pages from crud import crud skeleton = { 'name': "", 'html': '', } blue = Blueprint('page', __name__, template_folder='templates') crud(blue, pages, template='page/index', skeleton=skeleton) html = ''' <div class="ui container"> <h3 class="ui top attached header"> Top Attached </h3> <div class="ui attached segment"> <p></p> </div> <h3 class="ui attached header"> Attached </h3> <div class="ui attached segment"> <p></p> </div> <h3 class="ui bottom attached header"> Bottom Attached </h3> </div>
from flask import Blueprint, request, render_template from config import hows from crud import crud from crud.how.instance import how from bson import ObjectId from media import insert_img blue = Blueprint('how', __name__, template_folder='templates') crud(blue, hows, template='how/index', load_document=lambda x: (x, {}), skeleton=how) @blue.route('/<_id>/<level_1>/<level_2>/media/+', methods=['POST']) def add_image(_id, level_1, level_2): (l1, l2) = (int(level_1) - 1, int(level_2) - 1) article = hows.find_one({'_id': ObjectId(_id)}) level_1 = article['level_1'][l1] level_2 = level_1['level_2'][l2] raw_img = request.files['image'] o = ObjectId() o = insert_img(raw_img.read(), o, sizes=()) level_2['i'] = str(o[0]) hows.update({"_id": article['_id']}, article, upsert=True) return o @blue.route('/') def hows_homepage(): return render_template('how/homepage/index.html')
from flask import Blueprint, request from config import keywords from crud import crud from utility import request_attributes from pymongo import DESCENDING from utility import obj2str blue = Blueprint('keywords', __name__) crud(blue, keywords) _keywords = {} _max_length = 2 def add_keyword(key): if key not in _keywords: _keywords[key] = 1 else: _keywords[key] += 1 if len(_keywords) == _max_length: for key, hit in _keywords.items(): try: result = keywords.find_and_modify( {"title": key}, {"$inc": { "hit": hit }}, ) if not result: raise except:
skeleton = { 'location': { 'place': '', 'lat': 0, 'lng': 0, }, 'title': '', 'about': { 'summary': '', 'specifications': {} }, 'specifications': {} } crud(blueprint=blue, collection=collection, skeleton=skeleton, template='home/index') @blue.route('/<_id>/reviews/', methods=['GET', 'POST']) @login_required def reviews(_id): home_id = ObjectId(_id) user_id = current_user.json['_id'] from utility import request_json json = request_json(request) if 'score' in json: review(home_id, message(json), json['score']) elif 'reply' in json: reply_id = ObjectId(json['reply']) reply(home_id, reply_id, message(json))
collection.save(document) def on_update_redundancy(_review): collection = _review['coolie']['type'] collection = importlib.import_module('config.' + collection) document = _review['coolie']['_id'] document = collection.find_one({'_id': document}) document['reviews'] = update_structure(document['reviews']) collection.save(document) crud(blue, reviews, skeleton=review, redundancies={ 'update': on_update_redundancy, 'insert': on_insert_redundancy, 'delete': on_delete_redundancy }) def bring_reviews(document, size): _reviews = document['reviews']['reviews'] _reviews = _reviews[:size] _top_review = document['reviews']['top_review'] document['reviews']['reviews'] = reviews.find({'_id': {'$in': _reviews}}) document['reviews']['top_review'] = reviews.find_one({'_id': _top_review}) return document def init_structure():
from flask import Blueprint, render_template from config import orders from crud import crud blue = Blueprint('orders', __name__) crud(blue, orders) @blue.route('/', methods=['GET', 'POST']) def order_now(): return 'yusof', 200
# `id` int(11) NOT NULL AUTO_INCREMENT, # `name` varchar(255) DEFAULT NULL, # `address` varchar(255) DEFAULT NULL, # PRIMARY KEY (`id`) # ) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8; ################################################33 import genops as gen #import the crud class from crud import crud choice = "" # loop while choice not equal to 999 while choice.lower() != "q": gen.printoptions() choice = str(raw_input('Selection:')).lower() crudobj = crud() if choice == 'c': crudobj.create() elif choice == 'r': crudobj.read() elif choice == 'u': crudobj.update() elif choice == 'd': crudobj.delete() elif choice == 'q': print 'program ended!' break else: print('Error in selection')
from flask import Blueprint, request, jsonify from config import places from crud import crud from utility import request_attributes blue = Blueprint('places', __name__) crud(blue, places) @blue.route('/', methods=['GET', 'POST']) def filtrate(): _json = request_attributes(request, query=str) query = _json['query'] '''places.find({ '$text': { '$search': query, '$language': '', # what should i do '$caseSensitive': False, '$diacriticSensitive': False, # wtf } })''' _places = places.find( {'$or': [ {'$text': {'$search': query}}, {'description': {'$regex': query}} ] } ) list = [] for _place in _places[:5]: _place['_id'] = str(_place['_id'])
from flask import Blueprint, request, jsonify from config import brands from crud import crud from utility import request_attributes from pymongo import DESCENDING blue = Blueprint('brands', __name__) crud(blue, brands) @blue.route('/sug/') def suggest_brands(query, size): query = query if query else request_attributes(request, query=str)['query'] size = size if size else request_attributes(request, size=int)['size'] __brands = brands.find( { '$or': [ { '$text': { '$search': query } }, { 'title': { '$regex': query } }, ] }, { "score": {
from flask import Blueprint, request, jsonify from config import products from crud import crud from utility import request_attributes from crud.pr.instance import ctx, pr, projection from crud.review import bring_reviews blue = Blueprint('pr', __name__, template_folder='templates') crud(blue, products, template='pr/index', load_document=lambda x: ({ 'pr': bring_reviews(x, 5) }, ctx), skeleton=pr, projection=projection)
def setUpClass(cls): cls.obj = crud() # cls.book_id = cls.obj.book_id cls.url = cls.obj.base_url
import config import crud import parser import utils app = Flask(__name__) app.config['MONGO_DBNAME'] = config.db.name app.config['MONGO_URI'] = config.db.uri flask_cors.CORS(app) mongo = PyMongo(app) crud.crud(app, mongo, 'courses') crud.crud(app, mongo, 'benchmarks') @app.route('/export/<_id>') def export(_id): collection = mongo.db.courses _id = bson.ObjectId(_id) course = collection.find_one(_id) with utils.export(course) as path: return flask.send_file(path, mimetype='application/vnd.ms-excel', as_attachment=True) @app.route('/login', methods=['POST']) def login(): username = flask.request.json.get('username')