Example #1
0
def create_app(**config):
    """Application Factory

    You can create a new He-Man application with::

        from heman.config import create_app

        app = create_app() # app can be uses as WSGI application
        app.run() # Or you can run as a simple web server
    """
    app = Flask(__name__, static_folder=None)

    if "MONGO_URI" in os.environ:
        app.config["MONGO_URI"] = os.environ["MONGO_URI"]

    app.config["LOG_LEVEL"] = "DEBUG"
    app.config["SECRET_KEY"] = "2205552d13b5431bb537732bbb051f1214414f5ab34d47"

    configure_logging(app)
    configure_sentry(app)
    configure_api(app)
    configure_mongodb(app)
    configure_login(app)

    return app
Example #2
0
# -*- coding: utf-8 -*-
from flask import Flask
from flask.ext.pymongo import PyMongo
from secrets import MONGO_URI

app = Flask(__name__)

# Store pics temporarily on api server
app.config["UPLOAD_FOLDER"] = "uploads/"
app.config["ALLOWED_FILES"] = ["png", "jpg", "jpeg", "gif"]

# Setup MongoDB connection
app.config["MONGO_URI"] = MONGO_URI

mongo = PyMongo(app)

# Load app modules

from modules import serve_static

app.register_blueprint(serve_static.mod, url_prefix="/")

from modules import authentication

app.register_blueprint(authentication.mod)

from modules import uploads

app.register_blueprint(uploads.mod)

from modules import receipts
app.config["BOOTSTRAP_GOOGLE_ANALYTICS_ACCOUNT"] = conf("BOOTSTRAP_GOOGLE_ANALYTICS_ACCOUNT")
Bootstrap(app)

oauth = OAuth()
meetup = oauth.remote_app(
    "meetup",
    base_url="https://api.meetup.com/",
    request_token_url="https://api.meetup.com/oauth/request/",
    access_token_url="https://api.meetup.com/oauth/access/",
    authorize_url="http://www.meetup.com/authorize/",
    consumer_key=conf("MEETUP_OAUTH_CONSUMER_KEY"),
    consumer_secret=conf("MEETUP_OAUTH_CONSUMER_SECRET"),
)

app.config["MONGO_URI"] = conf("MONGOHQ_URL", None)
mongo = PyMongo(app)

sendgrid_api = sendgrid.Sendgrid(username=conf("SENDGRID_USERNAME"), password=conf("SENDGRID_PASSWORD"), secure=True)

if conf("BUGSNAG_API_KEY"):
    bugsnag.configure(
        api_key=conf("BUGSNAG_API_KEY"),
        release_stage=conf("BUGSNAG_RELEASE_STAGE", "development"),
        notify_release_stages=["production"],
        auto_notify=False,
        use_ssl=True,
        project_root=os.path.dirname(os.path.dirname(__file__)),
        # project_version=
    )
Example #4
0
from flask import Flask, request, session, redirect, render_template, url_for
from flask.ext.pymongo import PyMongo
from models import User, List, Item
from helpers import authorized, ObjectIDConverter, parse_amz
from bs4 import BeautifulSoup
from base64 import b64encode
import json
import urllib2

app = Flask(__name__)
app.url_map.converters["ObjectID"] = ObjectIDConverter
app.secret_key = "\x93Y\xc3 o^$\x03\xfa\x9c\xbe\xa9x\x9dR\x94\xcd\xd9k\x9e\x9e#\x94\xca"
# mongodb connections
app.debug = True
app.config[
    "MONGO_URI"
] = "mongodb://heroku_app14582889:s69s9ag2v3qrbe0grhvfoem3mg@ds037387.mongolab.com:37387/heroku_app14582889"
mongo = PyMongo(app, config_prefix="MONGO")
# functions needed


@app.route("/product_parse", methods=["POST"])
@authorized
def parse_amazon_item():
    url = request.form["amazon_url"]
    page = urllib2.urlopen(url).read()
    soup = BeautifulSoup(page)
    image_url = soup.select("#main-image")[0]["src"]
    name = soup.select("#btAsinTitle")[0].text
    descript = soup.select(".productDescriptionWrapper")[0].text[:160] + "..."
    obj = {"name": name, "image_url": image_url, "description": descript}
Example #5
0
    Response,
)
from datetime import timedelta, datetime
from functools import update_wrapper

from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager, UserMixin, logout_user, current_user, login_user
from oauth import OAuthSignIn
import ast
from functools import wraps

# flask app
current_version = "08"
app = Flask(__name__)
app.config["SECRET_KEY"] = "F!12Z@r47j\3yXm J xu&R~>X@H!j<<mM]Lwf/,?KXTxQ!"
app.config["MONGO_URI"] = "127.0.0.1:27017"
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///db.sqlite"
app.config["OAUTH_CREDENTIALS"] = {"facebook": {"id": "940836925972002", "secret": "4c954cbadb8c15ea65c49585f2c794c5"}}

db = SQLAlchemy(app)
lm = LoginManager(app)
lm.login_view = "index"


# Facebook login stuff
class User(UserMixin, db.Model):
    __tablename__ = "users"
    id = db.Column(db.Integer, primary_key=True)
    social_id = db.Column(db.String(64), nullable=False, unique=True)
    nickname = db.Column(db.String(64), nullable=False)
    data = db.Column(db.String(64), nullable=False)
Example #6
0
import os
import requests
from bs4 import BeautifulSoup
import re
import time
from flask import Flask
from flask.ext.pymongo import PyMongo

# import operator

app = Flask(__name__)
if os.environ.get("MONGOHQ_URL"):
    app.config["MONGO_URI"] = "mongodb://surfemups:surf3mup5@linus.mongohq.com:10045/app10640790"
mongo = PyMongo(app)

FAME_THRESHOLD = 10000
CRAWL_PAGES = 3
DELAY = 0.5


def calculateF(followers, following):
    return float(following) / (int(followers) + 1)


def crawl_page(url, profile={}):

    webstagram_base = "http://web.stagram.com"

    r = requests.get(webstagram_base + url)

    soup = BeautifulSoup(r.content, "lxml")
Example #7
0
    # 'WeCnI8VjEiFg4AzX3BjOg4W2R6Q8D', '54.80.251.254', '27017', 'mobapi']
    # mongo_uri = 'mongodb://%s:%s@%s:%s/%s' % (username, password, host, port, db)

    # print "mongo uri: ", mongo_uri
    # client = MongoClient(mongo_uri)
    """ testing database """
    connection_string = "mongodb://192.168.4.86:27017/"
    client = MongoClient(connection_string)
    # db = client['mobapi']
    db = client["mobapi_live"]
    """ test db connection """
    print "user count: ", db.users.count()
    return db


app.config["MONGO_URI"] = "mongodb://192.168.4.86:27017/mobapi_live"
mongo = PyMongo(app, config_prefix="MONGO")


"""==================================================================================================================
    Api call for getStream which returns json
   ==================================================================================================================
"""


@app.route("/api/stream/getStreams.json", methods=["GET"])
@require_appkey
def get_stream():
    """ storing the start of time for api"""
    start_time = time.time()
    db = mongo.db
Example #8
0
File: hello.py Project: CMarth/OBET
from flask.ext.wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import Required

##################
#    Config      #
##################
app = Flask(__name__)
app.config["SECRET_KEY"] = "LSKFJDSLf84wi7rleIFdso8fsL9F87SDAOIFUSOH87FS70Q03958734LKdllkjdsflskjf"

###################
#    DB Config    #
###################

app.config["MONGO_URI"] = "mongodb://mikachama:Haruka10@ds033419.mongolab.com:33419/inventory"
app.config["MONGODB_HOST"] = "ds033419.mongolab.com"
app.config["MONGODB_PORT"] = 33419
app.config["MONGO_DBNAME"] = "inventory"
app.config["MONGODB_USERNAME"] = "mikachama"
app.config["MONGODB_PASSWORD"] = "Haruka10"
app.config["ADMIN_EMAIL"] = "admin@admin.com"
app.config["ADMIN_PASS"] = "testerpassword"
app.config["MONGODB_SETTINGS"] = {
    "db": "inventory",
    "host": "mongodb://mikachama:Haruka10@ds033419.mongolab.com:33419/inventory",
}


###############
#    Init     #
Example #9
0
# sockets module monkey-patches this to hook in to events
socket_push = lambda **kwargs: None


app = Flask(__name__)


CONFIGS = ("WEBAPP_URL", "AUTH_TOKEN", "CELL_NUM", "MONGOLAB_URI", "TWILIO_NUM")


# Set up the app
app = Flask(__name__)
app.config.update(DEBUG=(os.environ.get("DEBUG") == "TRUE"))
app.config.update(**{v: os.environ[v] for v in CONFIGS})
app.config["MONGO_URI"] = app.config["MONGOLAB_URI"]  # for flask-pymongo


# Initialize extensions
pymongo = PyMongo(app)


# Some constants
SMS_CODE_RESET = timedelta(minutes=10)
SMS_CODE_GRACE = timedelta(minutes=10)
USER_CHECKIN_EXPIRE = timedelta(minutes=15)
USER_POST_THROTTLE = timedelta(seconds=0)


"""Collection schemas
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 #11
0
import os
from flask import Flask

app = Flask(__name__)

app.config["MONGO_URI"] = "mongodb://farmspot:farmspot@troup.mongohq.com:10058/FarmSpot"


import farm.views
Example #12
0
"""

from flask import Flask, render_template
from flask.ext.pymongo import PyMongo
from bson.objectid import ObjectId
from calentic.scrappers import *

import calentic.scrappers
import json as _json
import os


APP = Flask(__name__)
if "MONGOHQ_URL" in os.environ.keys():
    APP.config["MONGO_URI"] = os.environ["MONGOHQ_URL"]
else:
    APP.config["MONGO_DB"] = "calentic"

MONGO = PyMongo(APP)


class JSONEncoder(_json.JSONEncoder):
    """
       Replacing
    """

    def default(self, o):
        if isinstance(o, ObjectId):
            return ""
        return _json.JSONEncoder.default(self, o)
Example #13
0
from pymongo.errors import OperationFailure

# Configure from the environment, global (immutable) variables (before submodules import)


class Config(object):
    SECRET_KEY = environ["SECRET_KEY"]
    SENDGRID_USERNAME = environ["SENDGRID_USERNAME"]
    SENDGRID_PASSWORD = environ["SENDGRID_PASSWORD"]
    MONGO_URI = environ["MONGOLAB_URI"]


# Create the app and mongo helper
app = Flask(__name__)

app.config["MONGO_URI"] = Config.MONGO_URI
app.config[
    "MONGO_CONNECT"
] = "False"  # http://api.mongodb.org/python/current/faq.html#using-pymongo-with-multiprocessing
mongo = PyMongo(app)

from .api import api
from .helpers import query_from_dict
from .tags import tags
from .json import NofussbmJSONEncoder, NofussbmJSONDecoder

app.json_encoder = NofussbmJSONEncoder
app.json_decoder = NofussbmJSONDecoder

# Register APIs blueprint and setup {before,teardown}_request
Example #14
0
from flask_pymongo import PyMongo
import redis


app = Flask(__name__)

# Set up logging
console_logger = logging.StreamHandler()
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
Example #15
0
__author__ = "nitishmehta"
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
import urllib2
import json
from flask.ext.pymongo import PyMongo
from pymongo import MongoClient
from User import *

app = Flask(__name__)
# You need to have a Mongo DB instance running on your computer having a database name as VC_FUND
app.config["MONGO_URI"] = "mongodb://localhost:27017/VC_FUND"
mongo = PyMongo(app)


@app.route("/")
def mainpage():
    # Please add the appropriate access token before running this code
    url = "https://api.angel.co/1/search?query=ucla&type=User&access_token="
    response = urllib2.urlopen(url)
    user = json.loads(response.read())

    client = MongoClient()
    db = client.VC_FUND
    posts = db.posts

    # Please add the appropriate access token before running this code
    for u in user:
        url = "https://api.angel.co/1/users/" + str(u["id"]) + "?access_token="
        response = urllib2.urlopen(url)
        job = json.loads(response.read())
        if mongo.db.posts.find_one({"id": job["id"]}) != None:
Example #16
0
from flask import Flask, jsonify
from flask.ext.pymongo import PyMongo
from flask.ext.cors import CORS
import os
import datetime

app = Flask(__name__)
CORS(app)

app.config["MONGO_URI"] = os.environ.get("MONGO_URI")
mongo = PyMongo(app)


@app.route("/cours/")
def cours():
    cours = parse_cours(mongo.db.planning.find())

    return jsonify(data=cours), 200


@app.route("/cours/prochain")
def prochain_cours():
    cours = parse_cours(
        mongo.db.planning.find({"horaire_debut": {"$gte": datetime.datetime.utcnow()}}).sort("horaire_debut").limit(1)
    )

    return jsonify(data=cours), 200


def parse_cours(donnees):
    cours = []
Example #17
0
#
# configure and instantiate Yelp Object
#
app.config.from_pyfile("config.py", silent=True)
app.config.from_envvar("foowoo_config", silent=True)
# check local environment for config data
if os.getenv("CONSUMER_KEY"):
    app.config["CONSUMER_KEY"] = os.getenv("CONSUMER_KEY")
if os.getenv("CONSUMER_SECRET"):
    app.config["CONSUMER_SECRET"] = os.getenv("CONSUMER_SECRET")
if os.getenv("TOKEN"):
    app.config["TOKEN"] = os.getenv("TOKEN")
if os.getenv("TOKEN_SECRET"):
    app.config["TOKEN_SECRET"] = os.getenv("TOKEN_SECRET")
if os.getenv("MONGO_URI"):
    app.config["MONGO_URI"] = os.getenv("MONGO_URI")
if os.getenv("MONGO_PORT"):
    app.config["MONGO_PORT"] = int(os.getenv("MONGO_PORT"))
if os.getenv("MONGO_USER"):
    app.config["MONGO_USER"] = os.getenv("MONGO_USER")
if os.getenv("MONGO_PASSWORD"):
    app.config["MONGO_PASSWORD"] = os.getenv("MONGO_PASSWORD")

yelp = Yelp(app.config["CONSUMER_KEY"], app.config["CONSUMER_SECRET"], app.config["TOKEN"], app.config["TOKEN_SECRET"])


#
# connect to MongoDB
#

Example #18
0
        # Saving in database
        client = MongoClient(host="mongodb://test:TestBuggl@ds041633.mongolab.com:41633/buggl")
        db = client.buggl

        result = db.entries.insert_one({"plan": plan, "trip_category": category, "email": email, "name": name})

        # return
        return (
            "Thank you "
            + name
            + ". We've sent an email to: "
            + email
            + ", informing you want "
            + category
            + " category and you want the  "
            + plan
            + " plan"
        )

    else:
        return render_template("form.html")


if __name__ == "__main__":
    app.debug = True

    app.config["MONGO_URI"] = "mongodb://test:TestBuggl@ds041633.mongolab.com:41633/buggl"
    app.run(host=os.getenv("IP", "0.0.0.0"), port=int(os.getenv("PORT", 8080)))
    # url_for('static/css', filename='buggl.css')

# app.run(host=os.getenv(IP, 0.0.0.0))
Example #19
0
from flask import Flask, render_template, redirect, abort, url_for
from bson import json_util
from flask_triangle import Triangle
from flask_pymongo import PyMongo
from datetime import datetime, timedelta
import persistence_manager as persist
import os

# If you get an error on the next line on Python 3.4.0, change to: Flask('app')
# where app matches the name of this file without the .py extension.

# Set up the application
app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb://localhost:27017/mydb"
Triangle(app)
mongo = PyMongo(app)

inserted_base_resources = True

from routes import *

# Make the WSGI interface available at the top level so wfastcgi can get it.
wsgi_app = app

if __name__ == "__main__":

    # host = os.environ.get('SERVER_HOST', 'localhost')
    try:
        port = int(os.environ.get("PORT", "5555"))
    except ValueError:
        port = 5555