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 #2
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/
Example #3
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("/")
Example #4
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.places2.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 #5
0
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":
Example #6
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")]

username_table = {u.username: u for u in users}
userid_table = {u.id: u for u in users}
Example #7
0
from flask import Flask

# from flask.ext.pymongo import PyMongo
app = Flask(__name__)


from views import *

"""
from pymongo import MongoClient



client = MongoClient("colab-sbx-280.oit.duke.edu", "27017")
db = client.hackmit
"""


app.config["MONGO_HOST"] = "mongodb://colab-sbx-280.oit.duke.edu:27107"
app.config["MONGO_PORT"] = 27017
app.config["MONGO_DBNAME"] = "hackmit"
mongo = PyMongo(app)


# not sure what this line does, will ignore for now.. O:)
# app.config.from_object(__name__)

app.run()
Example #8
0
import config
from flask import Flask
from flask.ext.pymongo import PyMongo

myapp = Flask(__name__, static_folder="../public/static")
myapp.config["MONGO_HOST"] = config.MONGO_HOST
myapp.config["MONGO_PORT"] = config.MONGO_PORT
myapp.config["MONGO_DBNAME"] = config.MONGO_DBNAME
myapp.config["MONGO_USERNAME"] = config.MONGO_USERNAME
myapp.config["MONGO_PASSWORD"] = config.MONGO_PASSWORD
mongo = PyMongo(myapp)

import views
Example #9
0
# 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)

# Domains
if os.environ.get("ISDEV"):
Example #10
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>")

Example #11
0
console_format = logging.Formatter(" %(asctime)s %(levelname)s: %(message)s [in %(module)s:%(lineno)d]")
console_logger.setFormatter(console_format)
console_logger.setLevel(logging.WARNING)
app.logger.addHandler(console_logger)


if os.environ.get("EXTERNAL"):
    app.config["MONGO_URI"] = os.environ["MONGO_URI"]
    app.config["MONGO_CONNECT"] = False
    app.secret_key = os.environ["random_key"]
    app.config["BROKER_URL"] = os.environ["REDIS_URL"]  # Celery
    app.config["CELERY_RESULT_BACKEND"] = os.environ["REDIS_URL"]
else:
    with open("../Other-Secrets/TITDev.json") as secrets_file:
        secrets = json.load(secrets_file)
    app.config["MONGO_HOST"] = secrets["mongo-host"]
    app.config["MONGO_DBNAME"] = secrets["mongo-db"]
    app.config["MONGO_USERNAME"] = secrets["mongo-user"]
    app.config["MONGO_PASSWORD"] = secrets["mongo-password"]
    app.config["MONGO_PORT"] = secrets["mongo-port"]
    app.config["BROKER_URL"] = secrets["redis-host"]  # Celery
    app.config["CELERY_RESULT_BACKEND"] = secrets["redis-host"]
    app.config["MONGO_CONNECT"] = False
    app.secret_key = secrets["random_key"]

Bootstrap(app)
cdn_theme_url = "https://maxcdn.bootstrapcdn.com/bootswatch/3.3.5/slate/"
app.extensions["bootstrap"]["cdns"]["theme"] = WebCDN(cdn_theme_url)  # CDN Theme
app_mongo = PyMongo(app)

# Redis
# Init file

from flask import Flask
from flask.ext.pymongo import PyMongo
from flask.ext.mongokit import MongoKit, Document, Connection
from flask.ext.login import LoginManager

app = Flask(__name__)

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"

app.config.from_object("config")

# Mongo Connection
app.config["MONGO_DATABASE"] = "couponext"
app.config["MONGO_HOST"] = "127.0.0.1"
app.config["MONGO_PORT"] = 27017

mongo = MongoKit(app)

from app import views
Example #13
0
with open("/keys/.shared_key", "r") as content_file:
    SECRET_KEY = content_file.read()

app = Flask(__name__)
app.debug = True

# VNFS_URL = 'http://127.0.0.1:9000'
# UMAA_URL = 'http://127.0.0.1:9000'

VNFS_URL = "http://vnfs.docker:5000"  # vnfs.docker:5000
UMAA_URL = "http://umaa.docker:8000"  # umaa.docker:8000


app.config["MONGO_DBNAME"] = "broker_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)
Example #14
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": "",
Example #15
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 #16
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 #17
0
from flask import Flask, render_template, request, redirect, abort
from flask.ext.pymongo import PyMongo

# from Flask-PyMongo import PyMongo
import pymongo
from bson.objectid import ObjectId
from pymongo import ASCENDING, DESCENDING

app = Flask(__name__)
app.config["MONGO_DBNAME"] = "cats"
app.config["MONGO_HOST"] = "linus.mongohq.com"
app.config["MONGO_PORT"] = 10042
app.config["MONGO_USERNAME"] = "hello"
app.config["MONGO_PASSWORD"] = "world"
app.config["SECRET_KEY"] = "KeepThisS3cr3t"
app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 0
mongo = PyMongo(app)


@app.route("/")
def index():
    posts = mongo.db.posts.find().sort("views", DESCENDING)
    return render_template("index.html", posts=posts)


@app.route("/submit", methods=["GET", "POST"])
def submit():
    if request.method == "POST":
        post = {
            "author": request.form["author"],
            "title": request.form["title"],
Example #18
0
from flask.ext.pymongo import PyMongo
from flask import Flask, jsonify, make_response, render_template, request
from werkzeug.datastructures import ImmutableMultiDict
import json
import bson
import requests
import collections
from ipwhois import IPWhois
import whois
import re

#################
# Configuration #
#################
app = Flask(__name__)
app.config["MONGO_HOST"] = "localhost"
app.config["MONGO_PORT"] = 27017
app.config["MONGO_DBNAME"] = "threatnote"

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

###################
# Creating routes #
###################


@app.route("/", methods=["GET"])
def home():
    try:
        network = mongo.db.network.find()
        return render_template("home.html", network=network)
Example #19
0
from flask import jsonify
from flask import request
from flask.ext.cors import CORS
from flask.ext.pymongo import PyMongo

from localsettings import DBNAME
from localsettings import HOST
from localsettings import PORT
from localsettings import USERNAME
from localsettings import PASSWORD


app = Flask(__name__)

app.config["MONGO_DBNAME"] = DBNAME
app.config["MONGO_HOST"] = HOST
app.config["MONGO_PORT"] = PORT
app.config["MONGO_USERNAME"] = USERNAME
app.config["MONGO_PASSWORD"] = PASSWORD
mongo = PyMongo(app, config_prefix="MONGO")

CORS(
    app,
    resources={
        r"/contact/*": {"origins": [r".*aomercado\.github\.io", r".*aomercado\.com"]},
        r"/market/*": {"origins": [r".*aomercado\.github\.io", r".*aomercado\.com"]},
    },
)


@app.route("/contact", methods=["POST"])
Example #20
0
def create_app():
    app = Flask(__name__)

    # Create modules
    app.register_blueprint(rootModule)
    app.register_blueprint(moodlensModule)
    app.register_blueprint(opinionModule)
    app.register_blueprint(propagateModule)
    app.register_blueprint(indexModule)
    app.register_blueprint(evolutionModule)
    app.register_blueprint(identifyModule)
    app.register_blueprint(quota_systemModule)
    app.register_blueprint(dataoutModule)

    # 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["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
from flask import Flask, Response
from flask.ext.pymongo import PyMongo
import json
from settings import *

app = Flask(__name__)
app.config["MONGO_HOST"] = CONFIG["mongo"]["host"]
app.config["MONGO_DBNAME"] = CONFIG["mongo"]["db"]
if CONFIG["mongo"].has_key("uri"):
    app.config["MONGO_URI"] = CONFIG["mongo"]["uri"]

mongo = PyMongo(app)


@app.route("/palavra/<palavra>")
def define(palavra):
    dicionario = mongo.db[CONFIG["mongo"]["collection"]]
    resultado = dicionario.find_one_or_404({"palavra": palavra})
    resultado.pop("_id")
    resp = Response(json.dumps(resultado), status=200, mimetype="application/json")
    resp.headers["Access-Control-Allow-Origin"] = "*"
    return resp


if __name__ == "__main__":
    app.run(debug=True)
Example #22
0
from flask import Flask, render_template, request, redirect, url_for, session
from flask.ext.pymongo import PyMongo
from flask_pymongo import ObjectId
import settings as s, md5
import json
import sys

sys.path.insert(0, "wrappers/")

from Users import Users as u
from Sessions import Sessions as se
from Jokes import Jokes as j

app = Flask("Crackpot")

app.config["MONGO_HOST"] = s.MONGO_HOST
app.config["MONGO_PORT"] = s.MONGO_PORT
app.config["MONGO_USERNAME"] = s.MONGO_USERNAME
app.config["MONGO_PASSWORD"] = s.MONGO_PASSWORD
app.config["MONGO_DBNAME"] = s.MONGO_DBNAME

mongo = PyMongo(app)


@app.route("/")
def index():
    try:
        if session["loggedin"] == True:
            return render_template(
                "user.html", title="Crackpot", username=session["username"], avatar_hash=get_userinfo("email_hash")
            )
Example #23
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