Exemple #1
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    bootstrap.init_app(app)
    socketio.init_app(app)
    db.init_app(app)

    if app.debug:
        from flaskext.lesscss import lesscss
        lesscss(app)

    # init logger
    logger = logging.getLogger('brewctrl')
    logger.setLevel(app.config['LOGGING_LEVEL'])
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    # create console handler and set level to debug
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(formatter)

    # add ch to logger
    logger.addHandler(ch)

    # init control
    from .control import init_control
    init_control(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    return app
def configure_extensions(app):
    "Configure extensions like mail and login here"
    if app.debug: # in other words Development Config
        try:
            from flaskext.lesscss import lesscss
            lesscss(app)
        except: pass

        try:
            from flaskext.coffee import coffee
            coffee(app)
        except: pass
Exemple #3
0
def create_app(config_name='development'):
    app = Flask(__name__)
    app.config.from_object(config[config_name])

    app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) \
        if app.config['ELASTICSEARCH_URL'] else None

    config[config_name].init_app(app)

    db.init_app(app)
    mail.init_app(app)
    login_manager.init_app(app)
    pagedown.init_app(app)
    moment.init_app(app)
    lesscss(app)

    app.add_url_rule('/uploads/<filename>', 'uploads', build_only=True)
    app.wsgi_app = SharedDataMiddleware(
        app.wsgi_app, {'/uploads': app.config['UPLOAD_FOLDER']})
    app.memory = base.Client(('localhost', 11211))

    from .errors import errors
    app.register_blueprint(errors)

    from .main import main
    app.register_blueprint(main)

    from .auth import auth
    app.register_blueprint(auth)

    from .admin import admin
    app.register_blueprint(admin)

    from .moderator import moderator
    app.register_blueprint(moderator)

    from .user import user
    app.register_blueprint(user)

    from .post import post
    app.register_blueprint(post)

    from .comment import comment
    app.register_blueprint(comment)

    from .notice import notice
    app.register_blueprint(notice)

    from .api_1_0 import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api/v1.0')

    return app
Exemple #4
0
def create_app(config_name: str):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.config.from_pyfile('../credentials.py')

    # init extensions
    bootstrap.init_app(app)
    db.init_app(app)
    socketio.init_app(app)
    admin.init_app(app)
    login_manager.init_app(app)
    lesscss(app)

    # mqtt initialisation
    mqtt.init_app(app)
    refresh_subsriptions(app)

    # register blueprints
    from .core import core as core_blueprint
    from .main import main as main_blueprint
    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')
    app.register_blueprint(core_blueprint)
    app.register_blueprint(main_blueprint)

    # register Admin views
    from .models import Switch, Panel, Numeric, RCSwitch, Camera, MQTTMessage
    admin.add_view(NumericControlModelView(Numeric, category='Controls'))
    admin.add_view(
        RCSwitchControlModelView(RCSwitch,
                                 name='RCSwitch',
                                 category='Controls'))
    admin.add_view(
        CameraControlModelView(Camera, name='Camera', category='Controls'))
    admin.add_view(AuthorizedModelView(Panel, name='Panels'))
    admin.add_view(MQTTMessageModelView(MQTTMessage, name='MQTT Messages'))

    return app
Exemple #5
0
from flask import Flask, render_template, abort, send_from_directory,make_response,send_file
from jinja2 import TemplateNotFound

from lib.placeholder import Placeholder

def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as exc: # Python >2.5
        if exc.errno == errno.EEXIST:
            pass
        else: raise

app = Flask(__name__)
from flaskext.lesscss import lesscss
lesscss(app)

app.run

@app.route('/', defaults={'page': 'index'})
@app.route('/<page>')
def flask_geekmeet(page=None):
    try:
        return render_template('%s.html' % page)
    except TemplateNotFound:
        abort(404)

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404
Exemple #6
0
import os
import config

from flask import Flask, abort, g, request, url_for, redirect
from flask import render_template as flask_render_template
from distros_installs import distros_installs

from flask.ext.babel import Babel

app = Flask(__name__)
app._static_folder = os.getcwd() + '/website/static'
app.config['SECRET_KEY'] = os.urandom(64)
if app.debug:
    from flaskext.lesscss import lesscss
    lesscss(app)
#app.config.from_pyfile('translations.cfg')
babel = Babel(app, default_locale="en_US.ISO8859-1")

from events import get_rss


def render_template(template, *args, **kwargs):
    lang_path = config.LANG_MAP.get(g.current_lang, 'en_US.ISO8859-1')
    kwargs['include_template'] = "%s/htdocs/%s" % (lang_path, template)
    return flask_render_template(template, *args, **kwargs)


@app.before_request
def before():
    if request.view_args and 'lang_code' in request.view_args:
        if request.view_args['lang_code'] not in config.LANG_CODES:
Exemple #7
0
def create_app(env='debug'):

    """ TODO:
    if config is None:
        config = os.path.join(app.root_path, 'production.cfg')

    app.config.from_pyfile(config)
    """
    app = Flask(__name__)
    app.config.from_object(__name__)

    app.config.update(
        SECRET_KEY=os.urandom(20)
                )
    if (env == 'debug'):
        app.debug=True
    if (env == 'prod'):
        app.debug=False

    if app.debug:
        from flaskext.lesscss import lesscss
        lesscss(app)
    app.static_path = '/static'


    # connect to the database
    connection = Connection('mongodb://*****:*****@alex.mongohq.com:10013/app8222672')
    jobs_collection =  connection.app8222672.jobs
    users_collection =  connection.app8222672.users
    url = urlparse.urlparse('redis://:[email protected]:6777')
    autocomplete_engine = RedisEngine(host=url.hostname, port=url.port, password=url.password)

    @app.route('/index/')
    @app.route('/home/')
    @app.route('/')
    def home():
        return render_template('home.html')

    @app.route('/settings/')
    def settings():
        return render_template('settings.html')

    @app.route('/list')
    def list():
        jobs = []
        for job in jobs_collection.find():
            job['id'] = str(job['_id'])
            jobs.append(job)
        return render_template('list.html', jobs=jobs)

    @app.route('/delete/<jobid>')
    def delete(jobid):
        response = jobs_collection.remove({'_id':bson.ObjectId(jobid)});
        if (response == None):
            flash('Job erased')
        else:
            flash('Error occured')
        return redirect(url_for('list'))

    @app.route('/jobs/<jobid>')
    def inside(jobid):
        found_job = jobs_collection.find_one({'_id':bson.ObjectId(oid=str(jobid))});
        found_job['id'] = str(found_job['_id'])
        found_job['objectid'] = str(found_job['_id'])
        found_job['_id'] = str(found_job['_id'])
        return render_template('inside.html', job=found_job)


    @app.route('/edit/<jobid>')
    def edit(jobid):
        return render_template('add.html', job=jobid)
    
    @app.errorhandler(404)
    def page_not_found(e):
            return render_template('404.html'), 404
 
    # ==================== REGISTRATION ==================

    @app.route('/logout')
    def logout():
        # remove the username from the session if it's there
        session.pop('logged_in', None)
        return redirect(url_for('home'))

    @app.route('/registration')
    def registration():
        return render_template('registration.html')

    def get_user_id(email):
        return users_collection.find_one({ 'email' : email })

    @app.route('/login', methods=['GET','POST'])
    @app.route('/register', methods=['GET', 'POST'])
    def register():
        """Registers the user."""
        error = None
        if request.method == 'POST':
            logged_user = get_user_id(request.form['email'])
            if (logged_user):
                if (request.form['password'] == logged_user['password']):
                    flash('Logged in as ' + logged_user['email'])
                    session['logged_in'] = logged_user['email']
                    return redirect(url_for('home', session=session))
                else:
                    flash('Wrong password!')
                    return redirect(url_for('register'))
            if not request.form['email'] or \
                     '@' not in request.form['email']:
                error = 'You have to enter a valid email address'
            elif not request.form['password']:
                error = 'You have to enter a password'
            elif get_user_id(request.form['email']) is not None:
                error = 'The username is already taken'
            else:
                new_user_id = users_collection.save({ 'email' : request.form['email'], 'password' : request.form['password'], 'status' : 'awaiting confirm' })
                payload = {'from': 'Excited User <*****@*****.**>', 'to': request.form['email'], 'subject': 'Quick Hunt account confirmation', 'text': 'http://quickhunt.herokuapp.com/activate_user/' + str(new_user_id) }
                r = requests.post("https://api.mailgun.net/v2/app8222672.mailgun.org/messages", auth=HTTPBasicAuth('api', 'key-9m9vuzkafbyjqhm9ieq71n0lu9dgf9b9'), data=payload)
                flash('You were successfully registered. Confirm registration and login.')
                session['logged_in'] = request.form['email']
                flash('logged in successfuly')
                return redirect(url_for('home'))
        #flash('no luck ((' + request.method + error)
        flash('error:' + str(error))
        return render_template('login.html', error=error)


    @app.route('/activate_user/<user_id>')
    def activate_user(user_id):
        """
        Activate user function.
        """
        found_user = users_collection.find_one({'_id':bson.ObjectId(oid=str(user_id))});
        if not found_user:
            return abort(404)
        else:
            if found_user['status'] == 'awaiting_confirm':
                ### Setting the user status active here ###*
                confirm_mail = {'from': 'Quick Hunt <*****@*****.**>', 'to': found_user['email'], 'subject': 'Quick Hunt account confirmation', 'text': 'Subscription confirmed.' }
                r = requests.post("https://api.mailgun.net/v2/app8222672.mailgun.org/messages", auth=HTTPBasicAuth('api', 'key-9m9vuzkafbyjqhm9ieq71n0lu9dgf9b9'), data=confirm_mail)
                flash('user has been activated', 'info')
            elif found_user['status'] == 'active':
                flash('user already activated', 'info')
            return redirect(url_for('content'))


    """ This is the API part of the equation """
    """
    @app.errorhandler(404)
    def not_found(error=None):
        message = {
                'status': 404,
                'message': 'Not Found: ' + request.url,
        }
        resp = jsonify(message)
        resp.status_code = 404

        return resp
    """
    @app.route('/api/search/', methods = ['GET'])
    @app.route('/api/search/<query>', methods = ['GET'])
    def search(query=None):
        jobs = []
        for job in jobs_collection.find():
            job['_id'] = str(job['_id'])
            jobs.append(job)
        return jsonify({'result':jobs})



    @app.route('/api/jobs/<jobid>', methods = ['GET'])
    def get_job(jobid):
        found_job = jobs_collection.find_one({'_id':bson.ObjectId(oid=str(jobid))});
        found_job['id'] = str(found_job['_id'])
        found_job['objectid'] = str(found_job['_id'])
        found_job['_id'] = str(found_job['_id'])
        #if userid in users:
        return jsonify(found_job)
        #else:
        #    return not_found()
        #return undef

    @app.route('/api/jobs/new', methods = ['POST'])
    def create_job():
        js = json.dumps(request.data)
        json_data = json.loads(request.data)
        jobs_collection.save(json_data)
        resp = Response(js, status=200, mimetype='application/json')
        return resp

    @app.route('/api/jobs/<jobid>', methods = ['PUT'])
    def update_job(jobid):
        js = json.dumps(request.data)
        print 'js:' + str(js)
        json_data = json.loads(request.data)
        json_data['_id'] = bson.ObjectId(json_data['objectid'])
        jobs_collection.save(json_data)
        resp = Response(js, status=200, mimetype='application/json')
        return resp

    @app.route('/api/jobs/<jobid>', methods = ['DELETE'])
    def delete_job(jobid):
        response = jobs_collection.remove({'_id':bson.ObjectId(jobid)});
        if (response == None):
            return jsonify({success:'Success'})
        else:
            return jsonify({error:'Error'})

    @app.route('/api/autocomplete/', methods = ['GET'])
    def autocomplete():
        js = {}
        searchword = request.args.get('q', '')
        if searchword:
            js = json.dumps({'result': autocomplete_engine.search(searchword)})
        else:
            js = {'error':'invalid argument'}
        return Response(js, status=200, mimetype='application/json')

    @app.route('/api/favorites/add/<jobid>', methods = ['GET'])  # FIX IT (i mean get)
    def add_to_favorites(jobid):
        me = users_collection.find_one({ 'email' : session['logged_in'] })
        if 'favorites' in me:
            me['favorites'].append(jobid)
        else:
           me['favorites'] = [jobid]
        js = users_collection.save(me)
        print js
        resp = Response({ 'reply' : js }, status=200, mimetype='application/json')
        return resp
 
    @app.route('/api/favorites/delete/<jobid>', methods = ['DELETE'])  # FIX IT (i mean get)
    def remove_from_favorites(jobid):
        me = users_collection.find_one({ 'email' : session['logged_in'] })
        if 'favorites' in me:
            favorites = me['favorites']
            favoretes.remove(jobid)
            me['favorites'] = favorites
        js = users_collection.save(me)    
        print js
        resp = Response({ 'reply' : js }, status=200, mimetype='application/json')
        return resp
 

    return app
Exemple #8
0
    def on_running_signal(self, daemon):
        log.trace("Got running signal")
        self.config.root_path = daemon.working_directory
        custom_config_file_name = "ilogwebconfig.py"
        try:
            custom_config_file = os.path.join(
                os.path.abspath(self.config.root_path), custom_config_file_name
            )

            if os.path.isfile(custom_config_file):
                self.config.from_pyfile(custom_config_file)
                log.info("Loaded custom configuration from %r",
                         custom_config_file)
            else:
                log.info("%s not found", custom_config_file)
        except IOError:
            log.info("No %r found. Using default configuration.",
                     custom_config_file_name)
        self.logger_name = '.'.join([__name__, 'SERVER'])

        theme_name = self.config.get("THEME_NAME", None)
        if theme_name not in ("redmond", "smoothness"):
            raise RuntimeError("Theme \"%s\" not supported" % theme_name)

        dbm.native_unicode = self.config.get('SQLALCHEMY_NATIVE_UNICODE', True)
        dbm.record_queries = self.config.get('SQLALCHEMY_RECORD_QUERIES', False)
        dbm.pool_size = self.config.get('SQLALCHEMY_POLL_SIZE', 5)
        dbm.pool_timeout = self.config.get('SQLALCHEMY_POLL_TIMEOUT', 10)
        dbm.pool_recycle = self.config.get('SQLALCHEMY_POLL_RECYCLE', 3600)
        dbm.set_database_uri(self.config['SQLALCHEMY_DATABASE_URI'])

        cache.init_app(self)

        if self.debug:
            # LessCSS Support
            from flaskext.lesscss import lesscss
            lesscss(self, self.config['LESSC_BIN_PATH'])
            sass = Sass(self)

            from werkzeug.debug import DebuggedApplication
            self.wsgi_app = DebuggedApplication(self.wsgi_app, True)

#            from flaskext.debugtoolbar import DebugToolbarExtension
#            self.debug_toolbar = DebugToolbarExtension(self)


            if 'SHOW_ILOG_CONFIG' in os.environ:
                from cStringIO import StringIO
                from pprint import pprint
                log_output = StringIO()
                current_config = self.config.copy()
                for key, val in current_config.iteritems():
                    if 'password' in key.lower() or 'secret' in key.lower():
                        current_config[key] = (val[0] + ('*'*(len(val)-2)) +
                                               val[-1])
                pprint(current_config, stream=log_output, indent=2)
                log_output.seek(0)
                log.trace("Current configuration:\n%s",
                          log_output.read().strip())
                del log_output, StringIO, pprint, current_config


        # Setup views
        from .views.main import main
        from .views.account import account
        from .views.admin import admin
        from .views.admin.accounts import accounts
        from .views.admin.channels import channels
        from .views.admin.networks import networks
        self.register_blueprint(main)
        self.register_blueprint(account)
        self.register_blueprint(admin)
        self.register_blueprint(accounts)
        self.register_blueprint(channels)
        self.register_blueprint(networks)

        from ilog.web.utils.jinjafilters import format_irc_message
        self.jinja_env.filters['ircformat'] = format_irc_message
Exemple #9
0
def create_app(env='debug'):
    """ TODO:
    if config is None:
        config = os.path.join(app.root_path, 'production.cfg')

    app.config.from_pyfile(config)
    """
    app = Flask(__name__)
    app.config.from_object(__name__)

    app.config.update(SECRET_KEY=os.urandom(20))
    if (env == 'debug'):
        app.debug = True
    if (env == 'prod'):
        app.debug = False

    if app.debug:
        from flaskext.lesscss import lesscss
        lesscss(app)
    app.static_path = '/static'

    # connect to the database
    connection = Connection(
        'mongodb://*****:*****@alex.mongohq.com:10013/app8222672')
    jobs_collection = connection.app8222672.jobs
    users_collection = connection.app8222672.users
    url = urlparse.urlparse(
        'redis://:[email protected]:6777')
    autocomplete_engine = RedisEngine(host=url.hostname,
                                      port=url.port,
                                      password=url.password)

    @app.route('/index/')
    @app.route('/home/')
    @app.route('/')
    def home():
        return render_template('home.html')

    @app.route('/settings/')
    def settings():
        return render_template('settings.html')

    @app.route('/list')
    def list():
        jobs = []
        for job in jobs_collection.find():
            job['id'] = str(job['_id'])
            jobs.append(job)
        return render_template('list.html', jobs=jobs)

    @app.route('/delete/<jobid>')
    def delete(jobid):
        response = jobs_collection.remove({'_id': bson.ObjectId(jobid)})
        if (response == None):
            flash('Job erased')
        else:
            flash('Error occured')
        return redirect(url_for('list'))

    @app.route('/jobs/<jobid>')
    def inside(jobid):
        found_job = jobs_collection.find_one(
            {'_id': bson.ObjectId(oid=str(jobid))})
        found_job['id'] = str(found_job['_id'])
        found_job['objectid'] = str(found_job['_id'])
        found_job['_id'] = str(found_job['_id'])
        return render_template('inside.html', job=found_job)

    @app.route('/edit/<jobid>')
    def edit(jobid):
        return render_template('add.html', job=jobid)

    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('404.html'), 404

    # ==================== REGISTRATION ==================

    @app.route('/logout')
    def logout():
        # remove the username from the session if it's there
        session.pop('logged_in', None)
        return redirect(url_for('home'))

    @app.route('/registration')
    def registration():
        return render_template('registration.html')

    def get_user_id(email):
        return users_collection.find_one({'email': email})

    @app.route('/login', methods=['GET', 'POST'])
    @app.route('/register', methods=['GET', 'POST'])
    def register():
        """Registers the user."""
        error = None
        if request.method == 'POST':
            logged_user = get_user_id(request.form['email'])
            if (logged_user):
                if (request.form['password'] == logged_user['password']):
                    flash('Logged in as ' + logged_user['email'])
                    session['logged_in'] = logged_user['email']
                    return redirect(url_for('home', session=session))
                else:
                    flash('Wrong password!')
                    return redirect(url_for('register'))
            if not request.form['email'] or \
                     '@' not in request.form['email']:
                error = 'You have to enter a valid email address'
            elif not request.form['password']:
                error = 'You have to enter a password'
            elif get_user_id(request.form['email']) is not None:
                error = 'The username is already taken'
            else:
                new_user_id = users_collection.save({
                    'email':
                    request.form['email'],
                    'password':
                    request.form['password'],
                    'status':
                    'awaiting confirm'
                })
                payload = {
                    'from':
                    'Excited User <*****@*****.**>',
                    'to':
                    request.form['email'],
                    'subject':
                    'Quick Hunt account confirmation',
                    'text':
                    'http://quickhunt.herokuapp.com/activate_user/' +
                    str(new_user_id)
                }
                r = requests.post(
                    "https://api.mailgun.net/v2/app8222672.mailgun.org/messages",
                    auth=HTTPBasicAuth('api',
                                       'key-9m9vuzkafbyjqhm9ieq71n0lu9dgf9b9'),
                    data=payload)
                flash(
                    'You were successfully registered. Confirm registration and login.'
                )
                session['logged_in'] = request.form['email']
                flash('logged in successfuly')
                return redirect(url_for('home'))
        #flash('no luck ((' + request.method + error)
        flash('error:' + str(error))
        return render_template('login.html', error=error)

    @app.route('/activate_user/<user_id>')
    def activate_user(user_id):
        """
        Activate user function.
        """
        found_user = users_collection.find_one(
            {'_id': bson.ObjectId(oid=str(user_id))})
        if not found_user:
            return abort(404)
        else:
            if found_user['status'] == 'awaiting_confirm':
                ### Setting the user status active here ###*
                confirm_mail = {
                    'from': 'Quick Hunt <*****@*****.**>',
                    'to': found_user['email'],
                    'subject': 'Quick Hunt account confirmation',
                    'text': 'Subscription confirmed.'
                }
                r = requests.post(
                    "https://api.mailgun.net/v2/app8222672.mailgun.org/messages",
                    auth=HTTPBasicAuth('api',
                                       'key-9m9vuzkafbyjqhm9ieq71n0lu9dgf9b9'),
                    data=confirm_mail)
                flash('user has been activated', 'info')
            elif found_user['status'] == 'active':
                flash('user already activated', 'info')
            return redirect(url_for('content'))

    """ This is the API part of the equation """
    """
    @app.errorhandler(404)
    def not_found(error=None):
        message = {
                'status': 404,
                'message': 'Not Found: ' + request.url,
        }
        resp = jsonify(message)
        resp.status_code = 404

        return resp
    """

    @app.route('/api/search/', methods=['GET'])
    @app.route('/api/search/<query>', methods=['GET'])
    def search(query=None):
        jobs = []
        for job in jobs_collection.find():
            job['_id'] = str(job['_id'])
            jobs.append(job)
        return jsonify({'result': jobs})

    @app.route('/api/jobs/<jobid>', methods=['GET'])
    def get_job(jobid):
        found_job = jobs_collection.find_one(
            {'_id': bson.ObjectId(oid=str(jobid))})
        found_job['id'] = str(found_job['_id'])
        found_job['objectid'] = str(found_job['_id'])
        found_job['_id'] = str(found_job['_id'])
        #if userid in users:
        return jsonify(found_job)
        #else:
        #    return not_found()
        #return undef

    @app.route('/api/jobs/new', methods=['POST'])
    def create_job():
        js = json.dumps(request.data)
        json_data = json.loads(request.data)
        jobs_collection.save(json_data)
        resp = Response(js, status=200, mimetype='application/json')
        return resp

    @app.route('/api/jobs/<jobid>', methods=['PUT'])
    def update_job(jobid):
        js = json.dumps(request.data)
        print 'js:' + str(js)
        json_data = json.loads(request.data)
        json_data['_id'] = bson.ObjectId(json_data['objectid'])
        jobs_collection.save(json_data)
        resp = Response(js, status=200, mimetype='application/json')
        return resp

    @app.route('/api/jobs/<jobid>', methods=['DELETE'])
    def delete_job(jobid):
        response = jobs_collection.remove({'_id': bson.ObjectId(jobid)})
        if (response == None):
            return jsonify({success: 'Success'})
        else:
            return jsonify({error: 'Error'})

    @app.route('/api/autocomplete/', methods=['GET'])
    def autocomplete():
        js = {}
        searchword = request.args.get('q', '')
        if searchword:
            js = json.dumps({'result': autocomplete_engine.search(searchword)})
        else:
            js = {'error': 'invalid argument'}
        return Response(js, status=200, mimetype='application/json')

    @app.route('/api/favorites/add/<jobid>',
               methods=['GET'])  # FIX IT (i mean get)
    def add_to_favorites(jobid):
        me = users_collection.find_one({'email': session['logged_in']})
        if 'favorites' in me:
            me['favorites'].append(jobid)
        else:
            me['favorites'] = [jobid]
        js = users_collection.save(me)
        print js
        resp = Response({'reply': js}, status=200, mimetype='application/json')
        return resp

    @app.route('/api/favorites/delete/<jobid>',
               methods=['DELETE'])  # FIX IT (i mean get)
    def remove_from_favorites(jobid):
        me = users_collection.find_one({'email': session['logged_in']})
        if 'favorites' in me:
            favorites = me['favorites']
            favoretes.remove(jobid)
            me['favorites'] = favorites
        js = users_collection.save(me)
        print js
        resp = Response({'reply': js}, status=200, mimetype='application/json')
        return resp

    return app