Example #1
0
import requests
import json
from flask import Flask,jsonify,redirect,request
from rauth import OAuth2Service
from flask.ext.pymongo import PyMongo
from bson.json_util import dumps


app = Flask(__name__)
app.config['config_prefix']='MONGO'
app.config['MONGO_HOST'] ='songathon.xyz'
app.config['MONGO_DBNAME'] = 'users'
app.config['MONGO_PORT'] = 27017
mongo = PyMongo(app,config_prefix='MONGO')


@app.route('/api/create',methods=['POST','GET'])
def create():
	#fb_id 
	#save if it doesnt exit and return exits or not
	data = json.loads(request.data)

	blob = {'name':'','friends':[],'fb_id':str(data['fb_id']),'activity': { 'curr_lat':'', 'curr_long':'', 'turnt_level':'', 'activity':'','dest_lat':'' ,'dest_long':'' ,'joined':''} }
	newuser = mongo.db.users.insert_one({'user':blob})
	return jsonify({'result':"done"})

@app.route('/api/post/activities',methods=['POST','GET'])
def act():
    data = json.loads(request.data)
    print data
    mongo.db.users.update_one({'fb_id':data['fb_id']},{'$set':{'activity':{'dest_long':data['long'],'dest_lat':data['lat']}}})
Example #2
0
from flask.ext.pymongo import PyMongo

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(
"""APi-mongo.

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():
def create_app():
    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///flask-admin.db'

    register_blueprints(app)
    register_extensions(app)
    register_jinja_funcs(app)

    # Create modules
    app.register_blueprint(indexModule)
    app.register_blueprint(manageModule)
    app.register_blueprint(attributeModule)
    app.register_blueprint(recommentationModule)
    app.register_blueprint(overviewModule)
    app.register_blueprint(influenceModule)
    app.register_blueprint(loginModule)
    app.register_blueprint(groupModule)
    app.register_blueprint(detectModule)
    app.register_blueprint(tagModule)
    app.register_blueprint(ucenterModule)
 #   app.register_blueprint(weiboModule)
    app.register_blueprint(sensingModule)
    app.register_blueprint(sentimentModule)
    app.register_blueprint(networkModule)
    app.register_blueprint(userrankModule)
    # the debug toolbar is only enabled in debug mode
    app.config['DEBUG'] = True

    app.config['ADMINS'] = frozenset(['youremail@yourdomain.com'])
    app.config['SECRET_KEY'] = 'SecretKeyForSessionSigning'
    app.config["WTF_CSRF_ENABLED"] = False #2016-04-13

    
    '''
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqldb://%s:@%s/%s?charset=utf8' % (MYSQL_USER, MYSQL_HOST, MYSQL_DB)
    app.config['SQLALCHEMY_ECHO'] = False
    '''
    app.config['DATABASE_CONNECT_OPTIONS'] = {}

    app.config['THREADS_PER_PAGE'] = 8

    app.config['CSRF_ENABLED'] = True
    app.config['CSRF_SESSION_KEY'] = 'somethingimpossibletoguess'

    # Enable the toolbar?
    app.config['DEBUG_TB_ENABLED'] = app.debug
    # Should intercept redirects?
    app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = True
    # Enable the profiler on all requests, default to false
    app.config['DEBUG_TB_PROFILER_ENABLED'] = True
    # Enable the template editor, default to false
    app.config['DEBUG_TB_TEMPLATE_EDITOR_ENABLED'] = True

    app.config['MONGO_HOST'] = '10.128.55.83'    
    app.config['MONGO_PORT'] = 27017    
    app.config['MONGO_DBNAME'] = 'mrq'    

    # debug toolbar
    # toolbar = DebugToolbarExtension(app)

    # init database
    db.init_app(app)
    with app.test_request_context():
        db.create_all()

    # init security
    security.init_app(app, datastore=user_datastore)

    # init admin
    admin.init_app(app)
    admin.add_view(AdminAccessView(User, db.session))
    admin.add_view(AdminAccessView(Role, db.session))
    #admin.add_view(sqla.ModelView(User, db.session))
    #admin.add_view(sqla.ModelView(Role, db.session))
    #admin.add_view(Roleadmin(db.session))

    # init mongo
    mongo.init_app(app)    

    '''
    app.config['MONGO_HOST'] = MONGODB_HOST
    app.config['MONGO_PORT'] = MONGODB_PORT

    app.config['MONGODB_SETTINGS'] = {
        'db': MASTER_TIMELINE_54API_WEIBO_DB,
        'host': MONGODB_HOST,
        'port': MONGODB_PORT
    }

    # Create mysql database
    db.init_app(app)
    with app.test_request_context():
        db.create_all()

    # Create mongo_engine
    mongo_engine.init_app(app)

    admin.init_app(app)
    """
    # Create mysql database admin, visit via url: http://HOST:PORT/admin/
    for m in model.__all__:
        m = getattr(model, m)
        n = m._name()
        admin.add_view(SQLModelView(m, db.session, name=n))

    for m in mongodb_model.__all__:
        admin.add_view(MongoDBView(m))
    """

    # init mongo
    mongo.init_app(app)
    '''
    return app
Example #5
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 #6
0
from flask import Flask, render_template, request,session
from flask_pymongo import PyMongo
from bson import json_util
import json
from flask.json import jsonify
from bson.json_util import dumps

app = Flask(__name__)

app.secret_key = 'dfgsdfgsfgdfsg'
app.config['MONGO_HOST'] = '50.84.62.186'
app.config['MONGO_PORT'] = 27017
app.config['MONGO_DBNAME'] = 'sphv'
app.config['MONGO_USERNAME'] = 'sphv'
app.config['MONGO_PASSWORD'] = '2s3WW6ut'
mongo = PyMongo(app)


JSON_RESULT = []


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

@app.route('/search',methods=['POST'])  

def  search():
    '''
    Get the drugname given in the html form.
    '''
Example #7
0
    "LGPL 2.1" : "http://www.gnu.org/licenses/lgpl-2.1",
    "LGPL 2.1+" : "http://www.gnu.org/licenses/lgpl-2.1",
    "LGPL 3.0" : "http://www.gnu.org/licenses/lgpl-3.0",
    "LGPL 3.0+" : "http://www.gnu.org/licenses/lgpl-3.0",
    "GPL 2.0+" : "http://www.gnu.org/licenses/gpl-2.0",
    "GPL 3.0" : "http://www.gnu.org/licenses/gpl-3.0",
    "GPL 3.0+" : "http://www.gnu.org/licenses/gpl-3.0",
}


app = Flask(__name__)
app.config['ENABLE_REGISTRATION'] = True
app.config['SSL'] = True

#mongodb defaults
app.config['MONGO_HOST'] = getenv("OPENSHIFT_MONGODB_DB_HOST",None)
app.config['MONGO_PORT'] = getenv("OPENSHIFT_MONGODB_DB_PORT",None)
app.config['MONGO_USERNAME'] = getenv("OPENSHIFT_MONGODB_DB_USERNAME",None)
app.config['MONGO_PASSWORD'] = getenv("OPENSHIFT_MONGODB_DB_PASSWORD",None)

app.config.from_pyfile(join(environ['OPENSHIFT_DATA_DIR'],'cadinet.cfg'))

mongo = PyMongo(app)

spec_dir = join(app.root_path,'specs')
def validate(instance,filename):
    if not instance:
        return jsonify(reason="There was a problem with the request"),400
    try:
        schema = json.loads(open(join(spec_dir,filename)).read())
        jsonschema.validate(instance,schema)
Example #8
0
from flask.ext.pymongo import PyMongo
from uuid import uuid4

import pprint, json, random, bson.json_util
import Queue as Q
from bson import Binary, Code

app_url = ''
app = Flask(__name__)
app.secret_key = 'FF6XaS84h68MQ36j6LaHw0SQ3r8qY2YG'

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

app.config['MONGO_HOST'] = 'ds047355.mongolab.com'
app.config['MONGO_PORT'] = '47355'
app.config['MONGO_DBNAME'] = 'track-app'
app.config['MONGO_USERNAME'] = 'admin'
app.config['MONGO_PASSWORD'] = 'password'
mongo = PyMongo(app)

@app.route(app_url + '/' , methods = ['GET'])
def index():
	return render_template('index.html')

@app.route(app_url + '/api/cities', methods = ['GET','POST','PUT','DELETE'])
def cities():
	if request.method == 'GET':
		return bson.json_util.dumps(mongo.db.cities.find())
	elif request.method == 'POST':
Example #9
0
from flask import Flask, jsonify, request
from flask_jwt import JWT, jwt_required, current_identity
from werkzeug.security import safe_str_cmp
from flask.ext.pymongo import PyMongo

app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'super-secret'

app.config['MONGO_HOST'] = 'ds029595.mongolab.com'
app.config['MONGO_PORT'] = 29595
app.config['MONGO_DBNAME'] = 'sinau'
app.config['MONGO_USERNAME'] = 'sinaudb'
app.config['MONGO_PASSWORD'] = 'sinaudb'
mongo = PyMongo(app, config_prefix='MONGO')


class User(object):
    def __init__(self, id, username, password):
        self.id = id
	self.username = username
	self.password = password

    def __str__(self):
        return "User(id='%s')" % self.id

users = [
    User(1, 'user1', 'abcxyz'),
    User(2, 'user2', 'abcxyz')
]
Example #10
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

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

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

@app.route('/prototypes', methods=['GET', 'POST'])
def prototypes():
  if request.method == 'POST':
    mongo.db.mycollection.insert({'title': request.form['title'], 'content': request.form['content']})
    return Response('{}', status=200, mimetype='application/json')
  else:
    result = mongo.db.mycollection.find()
    data = dumps(result)
    response = Response(data, status=200, mimetype='application/json')
    return response

if __name__ == "__main__":
  app.run()
Example #11
0
from flask import Flask
from flask.ext.pymongo import PyMongo
from bson.json_util import dumps # http://api.mongodb.org/python/current/api/bson/json_util.html
from flask.ext.cors import CORS  # The typical way to import flask-cors

app = Flask(__name__)
cors = CORS(app)

app.config['MONGO_HOST'] = 'sjc-c9-0.objectrocket.com'
app.config['MONGO_PORT'] = '54075'
app.config['MONGO_DBNAME'] = 'pickaflick_db'
app.config['MONGO_USERNAME'] = 'pickaflick'
app.config['MONGO_PASSWORD'] = 'neoh@ck'

mongo = PyMongo(app)

@app.route('/')
def home_page():
    pickaflick_users = mongo.db.users.find()
    print pickaflick_users
    return dumps(pickaflick_users)

@app.route('/neohackerz')
def group():
	movie_title = mongo.db.movies.find()
	return dumps(movie_title)

# http://flask.pocoo.org/
if __name__ == "__main__":
    app.run()
def create_app():
    app = Flask(__name__)
    #下面这一句新加的
    app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///flask-admin.db'
    register_blueprints(app)
    register_extensions(app)
    register_jinja_funcs(app)

    # Create modules

    # the debug toolbar is only enabled in debug mode
    app.config['DEBUG'] = True

    app.config['ADMINS'] = frozenset(['youremail@yourdomain.com'])
    app.config['SECRET_KEY'] = 'SecretKeyForSessionSigning'
    
    '''
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqldb://%s:@%s/%s?charset=utf8' % (MYSQL_USER, MYSQL_HOST, MYSQL_DB)
    app.config['SQLALCHEMY_ECHO'] = False
    '''
    app.config['DATABASE_CONNECT_OPTIONS'] = {}

    app.config['THREADS_PER_PAGE'] = 8

    app.config['CSRF_ENABLED'] = True
    app.config['CSRF_SESSION_KEY'] = 'somethingimpossibletoguess'

    # Enable the toolbar?
    app.config['DEBUG_TB_ENABLED'] = app.debug
    # Should intercept redirects?
    app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = True
    # Enable the profiler on all requests, default to false
    app.config['DEBUG_TB_PROFILER_ENABLED'] = True
    # Enable the template editor, default to false
    app.config['DEBUG_TB_TEMPLATE_EDITOR_ENABLED'] = True
    
    # debug toolbar
    # toolbar = DebugToolbarExtension(app)
#新加的app.config到return之前
    app.config['MONGO_HOST'] = '219.224.134.211'    
    app.config['MONGO_PORT'] = 27017    
    app.config['MONGO_DBNAME'] = 'mrq'   
     # init database
    db.init_app(app)
    with app.test_request_context():
        db.create_all()

    # init security
    security.init_app(app, datastore=user_datastore)

    # init admin
    admin.init_app(app)
    #admin.add_view(AdminAccessView(User, db.session))
    #admin.add_view(AdminAccessView(Role, db.session))
    #admin.add_view(sqla.ModelView(User, db.session))
    #admin.add_view(sqla.ModelView(Role, db.session))
    #admin.add_view(Roleadmin(db.session))

    # init mongo
    mongo.init_app(app)         

    return app
Example #13
0
import logging

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

from multistack import config
from multistack.api.v1 import app_v1

app = Flask(__name__)
configparser = config.config_parser()
app.config['MONGO_HOST'] = configparser.get('flask', 'MONGO_HOST')
app.config['MONGO_DBNAME'] = configparser.get('flask', 'MONGO_DBNAME')
app.config['DEBUG'] = True

if configparser.has_option('DEFAULT', 'syslog_server_ip'):
	app.syslog_address = (configparser.get('DEFAULT', 'syslog_server_ip'),
						int(configparser.get('DEFAULT', 'syslog_server_port')))
else:
	app.syslog_address = '/dev/log'

app.register_blueprint(app_v1)

mongo = PyMongo(app)

handler = logging.handlers.SysLogHandler(address = app.syslog_address)
app.logger.addHandler(handler)

@app.route('/')
def default():
    return app.name + " running and Current API is v1 accessible on url prefix /v1/"
Example #14
0
from flask import Flask
from flask.ext.pymongo import PyMongo
import settings


app = Flask(__name__)
app.config['MONGO_DBNAME'] = settings.mongo_dbname
app.config['MONGO_HOST'] = settings.mongo_host
app.config['MONGO_PORT'] = settings.mongo_port
app.config['SECRET_KEY'] = settings.secret_key
mongo = PyMongo(app)
import views
Example #15
0
import os
from flask import Flask
from flask import request, render_template, redirect, url_for, flash
from flask.ext.pymongo import PyMongo
import pymongo
from datetime import datetime

app = Flask(__name__)

app.config['MONGO_HOST'] = '[HOST]'
app.config['MONGO_PORT'] = 0
app.config['MONGO_DBNAME'] = 'thehotspot'
app.config['MONGO_USERNAME'] = '[USERNAME]'
app.config['MONGO_PASSWORD'] = '[PASSWORD]'

app.secret_key="1062511ff23a05a8a5eec866c84fc4cd" # $ md5 -s thehotspot

mongo = PyMongo(app)


@app.route('/', methods=['GET'])
def tops():
    topusers = mongo.db.users.find({}).sort('checkins', pymongo.DESCENDING).limit(5)
    topplaces = mongo.db.places1.find({}).sort('checkins', pymongo.DESCENDING).limit(5)
    return render_template('top.html', topusers=topusers, topplaces=topplaces)


@app.route('/users/<int:userid>', methods=['GET'])
def user(userid):
    user = mongo.db.users.find_one_or_404({'_id': userid})
    checkins_skip = int(request.args.get('skip', 0))
Example #16
0
from flask import Flask, jsonify, url_for, redirect, request
from flask.ext.pymongo import PyMongo
from flask_restful import Resource, Api
import json

app = Flask(__name__)
#mongo = PyMongo(app)

# connect to another MongoDB server altogether
app.config['MONGO_HOST'] = 'ds021701.mlab.com'
app.config['MONGO_PORT'] = 21701
app.config['MONGO_DBNAME'] = 'wishapp'
app.config['MONGO_USERNAME'] = 'admin'
app.config['MONGO_PASSWORD'] = 'password'

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

APP_URL = "http://127.0.0.1:5000"

class Users(Resource):
    def get(self, username=None):
        data = []
        
        if username:
            user_info = mongo.db.user_details.find_one({"user_name": username}, {"_id": 0, "update_time": 0})

            if user_info:
                return {"status": "ok", "data": user_info}
            else:
                return {"response": "no user found for {}".format(username)}
Example #17
0
from flask import Flask, request
from flask.ext.pymongo import PyMongo


app = Flask(__name__)

#config
app.config['MONGO_HOST'] = "40.78.151.253"
app.config['MONGO_DBNAME'] = "stocks"
mongo = PyMongo(app)


import FlaskWebProject.views
Example #18
0
import gevent
import uwsgi

from flask import Flask
from os import environ
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure
from uwsgidecorators import spoolraw

# uWSGI spooling retry interval when idle
uwsgi.set_spooler_frequency(15)

# Flask app declaration
app = Flask(__name__)
app.config['MONGO_HOST'] = environ.get('MONGO_HOST', 'localhost')
app.config['MONGO_DBNAME'] = environ.get('MONGO_DBNAME', 'test')
app.last_count = 0
app.mongo = None


def get_mongo():
    """
    Simply connect the app to mongoDB.
    """
    try:
        app.mongo = MongoClient(
            host=app.config['MONGO_HOST'],
            connectTimeoutMS=500,
            socketTimeoutMS=1000
        )[app.config['MONGO_DBNAME']]
Example #19
0
	app_instance = Flask('tenk',
		template_folder=template_folder,
		static_folder='/var/www/glossify/web/static')

# CORS
CORS(app_instance, resources=r'/api/*', allow_headers='Content-Type')

# API
api = restful.Api(app_instance)

# Config the app
app_instance.config['DEBUG'] = True
app_instance.config['SECRET_KEY'] = 'super-secret'

if not os.environ.get('LOCALDB') or not int(os.environ.get('LOCALDB')):
	app_instance.config['MONGO_HOST'] = 'glossify.io'
	app_instance.config['MONGO_PORT'] = '27017'
	app_instance.config['MONGO_USERNAME'] = 'tlemberg'
	app_instance.config['MONGO_PASSWORD'] = 'tlemberg'
	app_instance.config['MONGO_NAME'] = 'tenk'
else:
	app_instance.config['MONGO_HOST'] = 'localhost'
	app_instance.config['MONGO_PORT'] = '27017'
	app_instance.config['MONGO_NAME'] = 'tenk'


# Mongo DB
mongo = PyMongo(app_instance)

# Mail
mail = Mail(app_instance)
Example #20
0
import flask
from flask import request, Flask, render_template, make_response, redirect
from flask.ext.pymongo import PyMongo  # @UnresolvedImport

import sys
import os
import datetime
from babel.dates import format_timedelta
import pymongo

app = Flask(__name__)
app.config['DEBUG']= os.environ.get('FLASK_DEBUG')


app.config['MONGO_HOST'] = os.environ.get('OPENSHIFT_MONGODB_DB_HOST', 'localhost')
app.config['MONGO_DBNAME'] = os.environ.get('OPENSHIFT_APP_NAME', 'testpy')
app.config['MONGO_USERNAME'] = os.environ.get('OPENSHIFT_MONGODB_DB_USERNAME')
app.config['MONGO_PASSWORD'] = os.environ.get('OPENSHIFT_MONGODB_DB_PASSWORD')

mongo=PyMongo(app)

with app.app_context():
    mongo.db.thoughts.ensure_index([('text', pymongo.TEXT)])
    mongo.db.thoughts.ensure_index([('created', pymongo.DESCENDING)])

def format_datetime(value):
    if isinstance(value, datetime.datetime):
        return value.strftime('%d-%b-%Y %H:%M')
    return  value
Example #21
0
REDIS_DB = os.environ['REDIS_DB']

# Flask webserver for incoming traffic from Slack
app = Flask(__name__)
app.config.from_object(__name__)
app.config['DEBUG'] = True
# session data
app.config['SESSION_TYPE'] = 'redis'
rdb = redis.Redis(host=REDIS_DB, port=6379, db=0)
app.config['SESSION_REDIS'] = rdb
app.config['SESSION_EXPIRY_MINUTES'] = 60
app.config['SESSION_COOKIE_NAME'] = "session"
Session(app)

# MONGO DB VALUES
app.config['MONGO_HOST'] = os.environ["MONGO_HOST"]
app.config['MONGO_PORT'] = os.environ["MONGO_PORT"]
app.config['MONGO_USERNAME'] = os.environ["MONGO_USERNAME"]
app.config['MONGO_PASSWORD'] = os.environ["MONGO_PASSWORD"]
app.config['MONGO_DBNAME'] = os.environ["MONGO_DBNAME"]
app.config["MONGO_URI"] = "mongodb://{}:{}@{}:{}/{}".format(os.environ["MONGO_USERNAME"], os.environ["MONGO_PASSWORD"], os.environ["MONGO_HOST"], os.environ["MONGO_PORT"], os.environ["MONGO_DBNAME"])

mongo = PyMongo(app, connect=False)

# global regex
date_regex_start = "([0-9]{4}-[0-9]{2}-[0-9]{2}|today)"
date_regex_end = ":([0-9]{4}-[0-9]{2}-[0-9]{2})?"
hour_regex = " ([0-9]) "
type_regex = "(vab|betald_sjukdag|obetald_sjukdag|ledig|semester|foraldrar_ledigt)"

# hostname ip
Example #22
0
import os, json
from flask import Flask, request
from bson import json_util
from bson.objectid import ObjectId
from flask.ext.pymongo import PyMongo

app = Flask(__name__)

app.config['SECRET_KEY'] = os.environ['SECRET_KEY'] if 'SECRET_KEY' in os.environ else 'this_should_be_configured'


#define MongoDB server configuration
app.config['MONGO_HOST'] = os.environ['MONGO_HOST'] if 'MONGO_HOST' in os.environ else 'localhost'
app.config['MONGO_PORT'] = os.environ['MONGO_PORT'] if 'MONGO_PORT' in os.environ else 27017
app.config['MONGO_DBNAME'] = os.environ['MONGO_DBNAME'] if 'MONGO_DBNAME' in os.environ else 'listit'
app.config['MONGO_USERNAME'] = os.environ['MONGO_USERNAME'] if 'MONGO_USERNAME' in os.environ else ''
app.config['MONGO_PASSWORD'] = os.environ['MONGO_PASSWORD'] if 'MONGO_PASSWORD' in os.environ else ''


# connect to MongoDB server
connection = PyMongo(app, config_prefix='MONGO')


#Convert Mongo object(s) to JSON
def toJson(data):
    return json.dumps(data, default=json_util.default)


@app.route('/employees/', methods=['GET'])
def employees():
  if request.method == 'GET':
Example #23
0
__author__ = 'rduboveckij'

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 #24
0
from flask.ext.pymongo import PyMongo
from flask.ext.wtf import Form
from flask.ext.wtf.html5 import URLField
from flask.ext.markdown import Markdown
from wtforms import TextField, SelectMultipleField
import os
import json
import requests
from urlparse import urljoin
from risk.game import Game as RiskGame
from app.forms import UserForm, StartGameForm

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL') or ('sqlite:///' + os.path.join(app.root_path, '../app.db'))
app.secret_key = 'f520d319-8b73-45c1-9982-07e57c0ddaa6'
app.config['MONGO_HOST'] = os.environ.get('MONGO_HOST') or 'localhost'
db = SQLAlchemy(app)
mongo = PyMongo(app)
Markdown(app)

from app.models import User, Game
from player_helper import Player
from players_helper import Players
from start_game import start_risk_game

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

@app.route("/signup", methods=("GET", "POST"))
def signup():
Example #25
0
config.read('./virtrest.cfg')

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:
Example #26
0

BASE_DIR = os.path.dirname(__file__)
UPLOAD_FOLDER = os.path.join(BASE_DIR, 'images')

#UMAA_URL = '127.0.0.1:9000'
UMAA_URL = 'umaa.docker:8000'

with open('/keys/.shared_key', 'r') as content_file:
    SECRET_KEY = content_file.read()

app = Flask(__name__)
app.debug = True

app.config['MONGO_DBNAME'] = 'vnfd_db'
app.config['MONGO_HOST'] = 'mongodb'
#app.config['MONGO_HOST'] = '127.0.0.1'
app.config['MONGO_PORT'] = 27017

mongo = PyMongo(app)

def jwt_required():
    """View decorator that requires a valid JWT token to be present in the request"""
    def wrapper(fn):
        @wraps(fn)
        def decorator(*args, **kwargs):

            auth = request.headers.get('Authorization', None)

            if auth is None:
                response = jsonify(detail="Authentication credentials were not provided.")
Example #27
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", "*")
Example #28
0
from flask import Flask, render_template, json
from flask_restful import Resource, Api
from flask_pymongo import PyMongo
from bson import json_util

def mongo_json(data):
    return json.dumps(data, default=json_util.default)


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


app.config['MONGO_DBNAME'] = "team-cal"
app.config['MONGO_HOST'] = "192.168.99.100"
app.config['MONGO_PORT'] = 27017

mongo = PyMongo(app)

class Event(Resource):
    def get(self, event_id):
        event = mongo.db.event.find_one_or_404({'_id': event_id})
        print(event)
        return mongo_json({'event': event})

api.add_resource(Event, '/event/<ObjectId:event_id>')

@app.route("/")
def index():
    return render_template('index.html')
Example #29
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 #30
0
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.



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


app = Flask(__name__)


# connect to another MongoDB server altogether
app.config['MONGO_HOST'] = 'aws-us-east-1-portal.16.dblayer.com'
app.config['MONGO_PORT'] = 10304
app.config['MONGO_DBNAME'] = 'IDFish'
app.config['MONGO_USERNAME'] = 'vanprz'
app.config['MONGO_PASSWORD'] = 'IBM311342233'
mongo = PyMongo(app, config_prefix='MONGO')



@app.route('/', methods=['GET', 'POST'])
def login():
    error = None

    if request.method == 'POST':
        m = u+"'"+request.form['phone']+"'"
        r = mongo.db.user.find_one({'phone':m})