from flask_script import Manager from logging import FileHandler, WARNING from config import MongoDB from pymongo import MongoClient from bson.json_util import dumps from app import app # Manager for app manager = Manager(app) @manager.command def log(task): """Enable and disable logging in flask.""" if task == 'Enable': if not app.debug: file_handler = FileHandler('errorlog.txt') file_handler.setLevel(WARNING) app.logger.addHandler(file_handler) if task == 'disable': # TODO pass # Mongo Commands @manager.command def rmcollection(dbname, collection): """Remove a collection from a database in MongoDB.""" url = MongoDB.url client = MongoClient(url) client[dbname][collection].drop() print "Removed {} in {} database".format(dbname, collection) @manager.command def mongotocsv(collection, OutputFile): """Store Mongo data to csv file.""" if not OutputFile.endswith('.csv'): print "Please mention a csv file in OutputFile!" print "Storing the result in result.csv" OutputFile = "result.csv" import subprocess from config import MongoDB dbnameORuri = MongoDB.url.split('/')[-1] subprocess.call( ['python', './Helpers/mongoexportcsv.py', dbnameORuri, collection, OutputFile]) print "Importing {1} collection data from {0} to the file path {2}".format(dbnameORuri, collection, OutputFile) @manager.command def mongotojson(collection, OutputFile): """Stores Mongo data as json file.""" if not OutputFile.endswith('.json'): print "Please mention a json file in OutputFile!" print "Storing the result in result.json" OutputFile = "result.json" url = MongoDB.url client = MongoClient(url) dbname = MongoDB.url.split('/')[-1] bsons = client[dbname][collection].find({}) # find all with open(OutputFile, "w+") as f: for i in bsons: json_string = dumps(i) + "\n" f.write(json_string) print "Importing {1} collection data from {0} to the file path {2}".format(url, collection, OutputFile) if __name__ == "__main__": manager.run()