Example #1
0
def create_app(dbname='damnmummies'):
    app = Flask(__name__)

    app.config['MONGO_DBNAME'] = dbname
    mongo.init_app(app)

    app.register_blueprint(game_blueprint)

    return app
Example #2
0
def create_app(dbname='whose_turn'):
    app = Flask('whose_turn')

    app.config['MONGO_DBNAME'] = dbname
    mongo.init_app(app)

    app.register_blueprint(api_blueprint, url_prefix='/api')

    return app
def create_app(db_interface, app_name='testapp', db_name='__test-db__'):
    app = Flask(app_name)
    app.config['SERVER_NAME'] = 'localhost:5000'

    if db_interface == 'pymongo':
        app.config['MONGO_DBNAME'] = db_name
        mongo = PyMongo(app)
        with app.app_context():
            app.session_interface = MongoDBSessionInterface(
                app, mongo.db, 'sessions')
    elif db_interface == 'mongoengine':
        app.config['MONGODB_DB'] = db_name
        mongo = MongoEngine(app)
        app.session_interface = MongoDBSessionInterface(
            app, mongo.connection[app.config['MONGODB_DB']], 'sessions')

    @app.route("/set")
    def set_session():
        session['data'] = request.args['d']
        return 'data'

    @app.route("/setpermanent")
    def set_permanent_session():
        session.permanent = True
        session['data'] = request.args['d']
        return 'data'

    @app.route("/get")
    def get_session():
        return session.get('data', '')

    @app.route("/unicode/set")
    def unicode_set():
        session['foo'] = u'Alpenerstra\xdfe'
        return 'done'

    @app.route("/unicode/get")
    def unicode_get():
        return session['foo']

    return app
Example #4
0
    def setUp(self):
        app = Flask(__name__)
        app.config.from_object(settings)
        app.testing = True
        app.config['MONGO_DBNAME'] = 'bergenholmtest'
        database.init_db(app)

        app.register_blueprint(frontend, url_prefix='')
        app.register_blueprint(ipxe, url_prefix='/ipxe')
        app.register_blueprint(hosts, url_prefix='/api/1.0/hosts')
        app.register_blueprint(groups, url_prefix='/api/1.0/groups')
        app.register_blueprint(templates, url_prefix='/api/1.0/templates')
        app.register_blueprint(power, url_prefix='/api/1.0/power')

        self.app = app
        self.client = app.test_client()
        self.mongo = database.mongo

        with self.app.test_request_context('/'):
            self.mongo.db.hosts.remove()
            self.mongo.db.groups.remove()
            self.mongo.db.templates.remove()

            params = {u"_id": self.host_id}
            params.update(self.host_params)
            self.mongo.db.hosts.insert(params)

            self.mongo.db.groups.insert({
                u"_id": u"default",
                u"base_url": u"http://127.0.0.1"})

            params = {u"_id": self.group_id}
            params.update(self.group_params)
            self.mongo.db.groups.insert(params)

            self.mongo.db.templates.insert({
                u"_id": self.template_id,
                u"content": self.template})
Example #5
0
from flask import Flask, render_template, jsonify, request
from flask.ext.pymongo import PyMongo
import datetime
from calendar import Calendar

app = Flask(__name__)

app.config['MONGO_DBNAME'] = 'assignment-calendar'

mongo = PyMongo(app)


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


@app.route('/month')
def month():
    t = datetime.date.today()
    year = request.args.get('year', t.year, type=int)
    month = request.args.get('month', t.month, type=int)
    weeks = Calendar().monthdatescalendar(year, month)

    result = []
    for i, week in enumerate(weeks):
        result.append([])
        for d in week:
            assignment_data = mongo.db.assignments.find_one({
                'year': d.year,
                'month': d.month,
Example #6
0
from flask import Flask, render_template, request, redirect, jsonify, json, session, url_for
from flask_pymongo import PyMongo
from bson import json_util
from bson.json_util import dumps
import json
from bson import ObjectId

app = Flask(__name__)

app.config['MONGO_DBNAME'] = 'unyx-tms-db'
app.config['MONGO_URI'] = 'mongodb://robertunyx:Xr5a8u2323@ds119070.mlab.com:19070/unyx-tms-db'

# INSTANTIATE DATABASE CONNECTION
mongo = PyMongo(app)


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

# Create task
@app.route('/create', methods=['POST'])
def create():

	# To insert into a collection, you must first get that collection (or create one), below 'mongo' is the object created by PyMongo(app), 'db' is the default database, which is 'unyx-tms-db' and tasks is a new collection created on the fly (if the collection exists, it finds it, if not, it creates it and it will be called 'tasks' like below in 'mongo.db.tasks')
	tasks = mongo.db.tasks
	task = request.form['task']
	print("Task: ", task)

	tasks.insert({'task' : task})
Example #7
0
from flask import Flask, Response, jsonify
from flask.ext.pymongo import PyMongo
from bson import json_util
import json

app = Flask(__name__)
app.debug = True
app.config['MONGO_DBNAME'] = 'fantasywatch'
mongo = PyMongo(app)

@app.route('/players')
def index():
	players = list(mongo.db.players.find({}, { 'season_history': 0, 'fixture_history': 0, 'event_eplain': 0, 'fixtures': 0}).limit(100))

	resp = Response(json_util.dumps( players ), status=200, mimetype="application/json")

	return resp

@app.route('/players/<int:id>', methods=['GET'])
def player(id):
	player = list(mongo.db.players.find( { "id": id } ))

	resp = Response(json_util.dumps(player), status=200, mimetype="application/json")

	return resp

@app.route('/teams', methods=['GET'])
def teams():
	teams = mongo.db.players.aggregate({ "$group": { "_id": { "team_name": "$team_name", "team_id": "$team_id" } } })

	resp = Response(json_util.dumps(teams['result']), status=200, mimetype="application/json")
Example #8
0
#! /usr/bin/env python
# coding:utf-8

import os
import configparser
import subprocess

from flask import Flask
from flask.ext.pymongo import PyMongo
from flask.ext.cors import CORS

app = Flask(__name__)
CORS(app)

app.config['MONGO_DBNAME'] = 'manara'

mongo_client = PyMongo(app)

class Config:
    # FIXME
    HOST = "http://localhost:3000"
    GIT_ROOT = subprocess.Popen(['git', 'rev-parse', '--show-toplevel'], stdout=subprocess.PIPE).communicate()[0] \
        .rstrip().decode('utf-8')

    config = configparser.ConfigParser()
    config.read(
        os.path.join(GIT_ROOT, 'config.ini')
    )

    CONSUMER_KEY = config['TWITTER']['CONSUMER_KEY']
    CONSUMER_SECRET = config['TWITTER']['CONSUMER_SECRET']
Example #9
0
from flask import Flask
from flask.ext.pymongo import PyMongo
from flask.ext.cors import CORS
from pymongo import MongoClient
from bson.objectid import ObjectId
import bson.json_util
import datetime
import json

client = MongoClient()
app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'assets'
mongo = PyMongo(app)
cors = CORS(app)


@app.route('/')
def hello_world():
    return 'Hello world'


@app.route('/currency/<currency_code>')
def currency(currency_code):

    doc = mongo.db.currencies.find_one_or_404({'currency_code': currency_code.upper()})

    return bson.json_util.dumps(doc)


@app.route('/user/<_id>', methods=['GET'])
def user(_id):
Example #10
0
Infracoders meetup example
"""

from flask import Flask, request
from flask.ext.pymongo import PyMongo
from bson.json_util import dumps
from bson.objectid import ObjectId
import os


app = Flask(__name__)

# connect to another MongoDB server altogether
app.config['MONGO_HOST'] = os.getenv('MONGO_HOST')
app.config['MONGO_PORT'] = int(os.getenv('MONGO_PORT',))
app.config['MONGO_DBNAME'] = os.getenv('MONGO_DBNAME', 'infratest')


mongo = PyMongo(app, config_prefix='MONGO')


@app.route('/')
def hello_infra():
    """Hello function."""
    return 'Hello Infracoders!'


@app.route('/entries', methods=['POST'])
def save_entry():
    """Save entry."""
    app.logger.debug(request.get_json())
Example #11
0
#!/usr/bin/python

from flask import Flask, render_template, url_for
from flask import Response
from flask.ext.pymongo import PyMongo
import json, os, datetime

app = Flask(__name__)

##alternate db config settings
app.config['MONGO_DBNAME'] = 'app_db'
#app.config['MONGO_HOST'] = 'localhost'
#app.config['MONGO_PORT'] = 27017
#app.config['MONGO_USERNAME'] = 'flask'
#app.config['MONGO_PASSWORD'] = 'flask123'
mongo = PyMongo(app, config_prefix='MONGO')

@app.route("/")
def home():
    links = []
    links.append({'title':'Show city data on a js map', 'url':url_for('city_by_zip',zipcode='47586')})
    links.append({'title':'Insert values into db and print collection.',
'url':url_for('db_insert', val=42)})
    #return Response(str(url_for(city_by_zip))
    return render_template('home.html', links=links)

#example javascript interaction with mongodb
@app.route("/city_by_zip/<zipcode>")
def city_by_zip(zipcode):
    #cursor = mongo.db.zips.find({ '_id' : '47586' })
    #cursor = mongo.db.zips.find({ 'state' : 'WY' })
Example #12
0


EMOTION_SAD = 'sad'
EMOTION_FRUSTRATED = 'frustrated'
EMOTION_ANGRY = 'angry'
EMOTION_ANXIOUS = 'anxious'
EMOTION_KEYS = [ \
    EMOTION_SAD, \
    EMOTION_FRUSTRATED, \
    EMOTION_ANGRY, \
    EMOTION_ANXIOUS \
]

app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'primer'
mongo = PyMongo(app,config_prefix='MONGO')
api = Api(app)


'''
User:
    login[post: user_id, name]

Scenario:
    pass scenario collection to the frontend[get: scenario_list]

Suggestion: 
    see suggestion[get: message, content]
    make suggestion[post to suggestion table: 
        user_id, emotion, scenario_id, message, content
Example #13
0
from flask import Flask, render_template
from flask.ext.pymongo import PyMongo
from flask.ext.restful import Resource, Api

app = Flask(__name__)

app.config['MONGO_DBNAME'] = 'test_database'
mongo = PyMongo(app)
api = Api(app)

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

#API to access list of locations associated with movie name
class MovieTitleLocation(Resource):
    def get(self, movie_title):
        locations = []
        for movie in mongo.db.movies.find({'title': movie_title}):
            if 'locations' in movie:
                locations.append(movie['locations'])

        return locations

#API to access list of movie titles
class MovieTitles(Resource):
    def get(self):
        movies = mongo.db.movies.find({'locations':{'$exists':True}}).distinct('title')
        return movies

api.add_resource(MovieTitleLocation, '/<string:movie_title>')
Example #14
0
from flask import Flask, render_template, request, url_for, redirect, abort
from tools import jsonify, diasatras
from flask.ext.pymongo import PyMongo

app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'monitorlegislativo'
#app.config["SECRET_KEY"] = "KeepThisS3cr3t"
app.jinja_env.filters['diasatras'] = diasatras

mongo = PyMongo(app)

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

@app.route("/busca")
def busca():
	termo = request.args.get('termo', '')
	try:
		t = termo.split()
		numero = str(int(t[0].strip())).zfill(4) #transforma em int e depois em str de novo com 4 casas
		ano = str(int(t[1].strip()))
		return redirect(url_for("projeto", tipo='pl',numero=numero, ano=ano))
	except:
		return termo #todo


@app.route('/legis/<tipo>/<numero>/<ano>')
@app.route('/legis/<tipo>/<numero>/<ano>/<json>')
def projeto(tipo, numero, ano, json=False):
	pid = tipo + '-' + numero + '-' + ano
Example #15
0
from flask import Flask
from flask.ext.pymongo import PyMongo
import os

app = Flask(__name__)

# mongodb configuration
MONGO_URI = os.environ.get('MONGO_URI')

if MONGO_URI:
    app.config['MONGO_URI'] = MONGO_URI
else:
    app.config['MONGO_DBNAME'] = 'reddit' #when working at local

mongo = PyMongo(app)

from app import views
Example #16
0
            if headers.get('Last-Event-ID', False):
                # Enviar todos los mensajes que no ha recibido el usuario
                def previous_messages():
                    last_msg_received = headers.get('Last-Event-ID')
                    messages = mongo.db.messages.find({'_id': {'$gt': ObjectId(last_msg_received)}})
                    return '\n'.join(map(lambda m: msg_to_sse_msg(m), messages))

                yield previous_messages()

        queue = Queue()
        subscriptions.append(queue)
        try:
            while True:
                message = queue.get()
                yield msg_to_sse_msg(message)
        except:
            subscriptions.remove(queue)

    return Response(events(request.headers), mimetype='text/event-stream')


# Iniciar la configuracion
app.config['MONGO_HOST']    = 'localhost'
app.config['MONGO_DBNAME']  = 'sse'

if __name__ == '__main__':
    app.debug = True
    server = WSGIServer(('', 5000), app)
    server.serve_forever()

Example #17
0
import re

from flask import Flask, render_template, request
from flask.ext.pymongo import PyMongo


app = Flask(__name__, template_folder=".")
app.config['MONGO_DBNAME'] = 'douban-group-database'
mongo = PyMongo(app)


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


@app.route("/search")
def search():
    include = request.args.get('include')
    exclude = request.args.get('exclude')
    if None in (include, exclude):
        return "include or exclude is empty"
    include = str2list(include)
    exclude = str2list(exclude)
    include_cond = [re.compile(s) for s in include]
    exclude_cond = [{'title' : {'$not' : re.compile("^.*%s.*" % s)}} for s in exclude]

    i, e = len(include) != 0, len(exclude) != 0
    if not (i or e):
        data = mongo.db.group_topics.find()
    elif i and not e:
Example #18
0
import csv
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

#path_wkthmltopdf = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'
#config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)

app = Flask(__name__)

APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLDER = ''
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

app.config['MONGO_DBNAME'] = 'mongologinexample'
app.config['MONGO_URI'] = 'mongodb://Aakanksha:lms123@ds111618.mlab.com:11618/mysite'

APP_ROOT = os.path.dirname(os.path.abspath(__file__))

mongo = PyMongo(app)

@app.route('/')
def index():
    #if 'username' in session:
    return render_template('index.html')
    #return render_template('login.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
Example #19
0
#!/usr/bin/python
from flask import Flask, jsonify
from flask import request

from flask_pymongo import PyMongo
import json
from bson import json_util


app = Flask(__name__, static_url_path='')

# configuration
app.config['MONGO_HOST'] = 'localhost'
app.config['MONGO_PORT'] = 27017
app.config['MONGO_DBNAME'] = 'items'

mongo = PyMongo(app)

@app.route('/')
def root():
    return app.send_static_file('index.html')

@app.route('/search', methods=['GET'])
def search():
    query = request.args.get('query', '')
    data = mongo.db.article_items.find({'$text': {'$search': query}} , {'_id': 0, 'text': 0, 'hash': 0, 'score': {'$meta': "textScore"}}).sort([('score', {'$meta': "textScore"})])
    #res = json.dumps(data, default=json_util.default)
    res = [r for r in data]
    for r in res:
        del r['score']
    return jsonify(res)
Example #20
0
from flask import Flask, request, abort
from bson.objectid import ObjectId
from bson import DBRef
from flask.ext.pymongo import PyMongo
from utils import crossdomain
from random import randint
from datetime import datetime
from os import environ

app = Flask(__name__)
app.config['MONGO_HOST'] = 'ds063287.mongolab.com'
app.config['MONGO_PORT'] = 63287
app.config['MONGO_USERNAME'] = "rduboveckij"
app.config['MONGO_PASSWORD'] = "65538vy140"
app.config['MONGO_DBNAME'] = "cam"

mongo = PyMongo(app)
REST_GPO = ['GET', 'POST', 'OPTIONS']
REST_GDO = ['GET', 'DELETE', 'OPTIONS']


def checkRule(min, max, i, r1, r2, r3):
    if i <= min:
        return r1
    elif i > min and i < max:
        return r2
    elif i >= max:
        return r3
    return 0
Example #21
0
# SMTP email config #
app.config['MAIL_SERVER'] = cfg.get('SMTP', 'server')
app.config['MAIL_PORT'] = cfg.get('SMTP', 'port')
app.config['MAIL_USE_TLS'] = cfg.get('SMTP', 'tls')
app.config['DEFAULT_MAIL_SENDER'] = cfg.get('SMTP', 'sender')

# Super Admin #
app.config['PORTAL_ADMIN'] = cfg.get('ADMIN', 'mail')

#  REDIS CONNECTION  #
r = redis.StrictRedis(host=cfg.get('REDIS', 'host'),
                      port=cfg.get('REDIS', 'port'),
                      db=cfg.get('REDIS', 'db'))

#  MONGO  #
app.config['MONGO_DBNAME'] = cfg.get('MONGO', 'dbname')
m = PyMongo(app)

# GPG #
gpg = gnupg.GPG(homedir=cfg.get('GPG', 'directory'))

# SYSLOG #
syslog.openlog(cfg.get('SYSLOG', 'ident'), logoption=syslog.LOG_PID, facility=syslog.LOG_USER)


# Logging stderr output
@app.before_first_request
def setup_logging():
    if not app.debug:
        app.logger.addHandler(logging.StreamHandler())
        app.logger.setLevel(logging.INFO)
Example #22
0
from flask import Flask
from flask import Response, request
from flask.ext.cors import CORS
from flask.ext.pymongo import PyMongo
from bson.json_util import dumps
from bson.json_util import loads

#import uuid
#id = uuid.uuid4()

app = Flask(__name__)
cors = CORS(app)
app.config['MONGO_HOST'] = 'mongodb://database'
app.config['MONGO_DBNAME'] = 'main'

# connect to the mongo db
mongo = PyMongo(app)

@app.route('/products', methods=['GET'])
def products():
  result = mongo.db.products.find()
  data = dumps(result)
  response = Response(data, status=200, mimetype='application/json')
  return response

@app.route('/product', methods=['GET'])
def product():
  result = mongo.db.products.find({"productId": request.args.get('id')})
  data = dumps(result)
  response = Response(data, status=200, mimetype='application/json')
  return response
Example #23
0
import requests
from bson.json_util import dumps
from flask import Flask, json, request
from flask_pymongo import PyMongo
app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'world'
mongoDB = PyMongo(app)


@app.route('/',methods=['GET', 'POST'])
def index():
    if request.method == 'GET':
        return json.jsonify(message='hello world')
    if request.method == 'POST':
        return json.jsonify(request.json)


@app.route('/forward')
def forward():
    response = requests.post('http://requestb.in/xp45khxp')
    return json.jsonify(message=response.text)

@app.route('/db',methods=['GET', 'POST'])
def db():
    if request.method == 'GET':
        return json.jsonify(dumps(mongoDB.db.fruits.find()))
    if request.method == 'POST':
        return 'todo'

if __name__ == '__main__':
    app.debug = True
Example #24
0
from flask import Flask, render_template
from flask.ext.pymongo import PyMongo
from flask_debugtoolbar import DebugToolbarExtension


app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'tweets'
mongo = PyMongo(app)


@app.route('/')
def home():
    return "hello"


@app.route('/tweets')
def show_tweets():
    tweets = mongo.db.tweets.find().sort('id', direction=-1).limit(100)
    return render_template('index.html', tweets=tweets)


@app.route('/tweets/user/<int:user_id>')
def show_user_tweets(user_id):
    tweets = mongo.db.tweets.find({'user.id': user_id}).sort('id', direction=-1).limit(100)
    return render_template('index.html', tweets=tweets)


@app.route('/tweets/hashtag/<hashtag>')
def show_hashtag_tweets(hashtag):
    tweets = mongo.db.tweets.find({'entities.hashtags.text': hashtag}).sort('id', direction=-1).limit(100)
    return render_template('index.html', tweets=tweets)
Example #25
0
__author__ = 'jay'

from flask import Flask

app = Flask(__name__)
app.config['MONGO_DBNAME'] = '99movies'
app.config["SECRET_KEY"] = "this_is_my_secret_key_which_should_be_secret!"

VERSION = 'v1'

# def register_blueprints(app):
#     # Prevents circular imports
#     from app.views import movies
#     app.register_blueprint(movies)

# register_blueprints(app)

if __name__ == '__main__':
    app.run()
Example #26
0
virtualrest = Flask(__name__)

MONGO_HOST = config.get('MONGODB', 'host')
MONGO_PORT = int(config.get('MONGODB', 'port'))
MONGO_DBNAME = config.get('MONGODB', 'dbname')
MONGO_USER = config.get('MONGODB', 'user')
MONGO_PASSWD = config.get('MONGODB', 'passwd')
MONGO_REPLICA_SET = config.get('MONGODB', 'replicaset')
GRIDFS_HOST = config.get('GRIDFS', 'host')
GRIDFS_PORT = int(config.get('GRIDFS', 'port'))

virtualrest.config['SECRET_KEY'] = urandom(64)

virtualrest.config['MONGO_HOST'] = MONGO_HOST
virtualrest.config['MONGO_PORT'] = MONGO_PORT
virtualrest.config['MONGO_DBNAME'] = MONGO_DBNAME
virtualrest.config['MONGO_USERNAME'] = MONGO_USER
virtualrest.config['MONGO_PASSWORD'] = MONGO_PASSWD
virtualrest.config['MONGO_REPLICA_SET'] = MONGO_REPLICA_SET

mongodb = PyMongo(virtualrest)

def lang_parse(isocode):
    lang_regex = search('^([A-Za-z]{2}(-|_)[A-Za-z]{2}|[a-z]{2})$',isocode)
    if (lang_regex is not None):
        lang = lang_regex.group(0).lower().replace('_','-')
    elif ('*' in fallback.keys()):
        return fallback['*']
    else:
        return None
    search_result = mongodb.db.translations.find_one({'isocode': lang},{'_id':0,'isocode':1})
Example #27
0
from lib.User import User
from lib.Config import Configuration
from lib.Toolkit import toStringFormattedCPE, toOldCPE, currentTime, isURL, vFeedName, convertDateToDBFormat
import lib.CVEs as cves
import lib.DatabaseLayer as dbLayer
from sbin.db_whitelist import *
from sbin.db_blacklist import *

# parse command line arguments
argparser = argparse.ArgumentParser(description='Start CVE-Search web component')
argparser.add_argument('-v', action='store_true', help='verbose output')
args = argparser.parse_args()

# variables
app = Flask(__name__, static_folder='static', static_url_path='/static')
app.config['MONGO_DBNAME'] = Configuration.getMongoDB()
app.config['SECRET_KEY'] = str(random.getrandbits(256))
pageLength = Configuration.getPageLength()

# login manager
login_manager = LoginManager()
login_manager.init_app(app)
# db connectors
redisdb = Configuration.getRedisVendorConnection()

# functions
def getBrowseList(vendor):
    result = {}
    if (vendor is None) or type(vendor) == list:
        v1 = redisdb.smembers("t:/o")
        v2 = redisdb.smembers("t:/a")
Example #28
0
SHIELDS_IO_URL = "http://img.shields.io/badge/uptodator-{0}-{1}.svg"

COLOR_OK = 'green'
MSG_OK = 'deps up to date'

COLOR_WARNING = 'red'
MSG_WARNING = '{0} outdated'

app = Flask(__name__)
api = Api(app)

app.config['PROPAGATE_EXCEPTIONS'] = True

app.config['MONGO_HOST'] = os.getenv('OPENSHIFT_MONGODB_DB_HOST')
app.config['MONGO_PORT'] = os.getenv('OPENSHIFT_MONGODB_DB_PORT')
app.config['MONGO_DBNAME'] = 'python'
app.config['MONGO_USERNAME'] = os.getenv('OPENSHIFT_MONGODB_DB_USERNAME')
app.config['MONGO_PASSWORD'] = os.getenv('OPENSHIFT_MONGODB_DB_PASSWORD')
app.config['MONGO_DBNAME'] = 'python'

mongo = PyMongo(app)


class Badge(Resource):

    def get(self, project_id):
        project = mongo.db.deps.find_one_or_404({'appId': project_id})
        if not project['numberOfUpdates'] > 0:
            badge_url = SHIELDS_IO_URL.format(
                MSG_OK.replace(' ', '_'),
                COLOR_OK)
Example #29
0
#log = logging.getLogger()
count = 0

# Create application
app = Flask(__name__)

# Create dummy secrey key so we can use sessions
app.config['SECRET_KEY'] = '123456790'

# MongoDB settings
app.config['MONGODB_SETTINGS'] = {'DB': 'am2v'}
db = MongoEngine()
db.init_app(app)

# Hum~~ MongoDB another tools
app.config['MONGO_DBNAME'] = 'am2v'
mongo = PyMongo(app)


# Create user model. For simplicity, it will store passwords in plain text.
# Obviously that's not right thing to do in real world application.
class User(db.Document):
  # duplicate error for Mongoengine... 
  '''
  meta = { 
    'abstract' : True, 
  }
  '''
  #login = db.StringField(max_length=80, unique=True)
  # email login 
  email = db.StringField(max_length=120, unique=True)
Example #30
0
import json
from datetime import datetime

from flask import Flask, Response
from flask.ext.pymongo import PyMongo
from werkzeug.contrib.cache import MemcachedCache
from flask_restful import Resource, Api

cache = MemcachedCache(['127.0.0.1:11211'])

app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'relevant_church'
app.config['MONGO_HOST'] = '127.0.0.1'
app.config['MONGO_USERNAME'] = 'cjemison'
app.config['MONGO_PASSWORD'] = 'cjemison'
mongo = PyMongo(app)
api = Api(app)


class addHeader(object):
    def __init__(self, d=dict()):
        self.arg1 = d

    def __call__(self, original_func):
        def wrappee(*args, **kwargs):
            d = original_func(*args, **kwargs)
            data = json.dumps(d, indent=4)
            r = Response(json.dumps(d), content_type='application/json; charset=utf-8')
            for key, value in self.arg1.iteritems():
                r.headers.add(key, value)
            r.headers.add("Access-Control-Allow-Origin", "*")