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
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 #3
0
# Dependencies
from flask import Flask, render_template, jsonify, redirect
from flask_pymongo import PyMongo
import scrape_mars

app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb://localhost:27017/myDatabase"
mongo = PyMongo(app)    

@app.route("/")
def dashboard():
    mars_db = mongo.db.mars_db.find_one()
    return render_template("index.html", mars_db=mars_db)

@app.route("/scrape")
def scrape():
    mars_db = mongo.db.mars_db
    mars_data = scrape_mars.scrape()
    mars_db.update(
        {},
        mars_data,
        upsert=True
    )
    return redirect("http://localhost:5000/", code=302)

if __name__ == "__main__":
    app.run(debug=True)
Example #4
0
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
my_ip = get('https://api.ipify.org').text

def validateRDBConn():
    try:
        rdb.ping()
Example #5
0
        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 #6
0
import os
from flask import Flask
from flask.ext import restful
from flask.ext.pymongo import PyMongo
from flask import make_response
from bson.json_util import dumps

MONGO_URL = os.environ.get("MONGO_URL")
if not MONGO_URL:
    MONGO_URL = "mongodb://localhost:27017/library"

app = Flask(__name__)
app.config["MONGO_URI"] = MONGO_URL
mongo = PyMongo(app)


def output_json(obj, code, headers=None):
    resp = make_response(dumps(obj), code)
    resp.headers.extend(headers or {})
    return resp


DEFAULT_REPRESENTATIONS = {"application/json": output_json}
api = restful.Api(app)
api.representations = DEFAULT_REPRESENTATIONS

import library.resources
import library.views
Example #7
0
from flask import Flask, render_template, redirect
from flask_pymongo import PyMongo
from scrape_mars import scrape_mars

app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb://localhost:27017/mars_app"
mongo = PyMongo(app)


@app.route("/")
def index():
    mars = mongo.db.mars.find_one()
    if mars:
        return render_template("index.html", mars=mars)
    else:
        return redirect("/scrape", code=302)


@app.route("/scrape")
def scraper():
    mars = mongo.db.mars
    mars_data = scrape_mars()
    mars.update({}, mars_data, upsert=True)
    return redirect("/", code=302)


if __name__ == "__main__":
    app.run()
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 #9
0
from flask import Flask, jsonify
from flask_pymongo import PyMongo
import os

app = Flask(__name__)

app.config['MONGO_DBNAME'] = "resume"
app.config["MONGO_URI"] = "mongodb://"+ os.environ["USERNAME"] + ":" + os.environ["PASSWORD"] + "@ds015995.mlab.com:15995/resume"


mongo = PyMongo(app)

@app.route("/", methods=["GET"])
@app.route("/resume", methods=["GET"])
def complete_resume():
    frame_work = mongo.db.my_resume

    output = []
    for i in frame_work.find():
        output.append({"Contact Information" : i["contact_info"],
        "Education" : i["Education"],
        "Experience": i["Experience"],
        "Skills" : i["Skills"], 
        "Projects" : i["Projects"], 
        "Links" : i["Links"]})

    return jsonify({"Resume" : output})


@app.route("/resume/<param>", methods=["GET"])
def get_education(param):
Example #10
0
import matplotlib

matplotlib.use("agg")
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from dateutil.rrule import rrule, MONTHLY
from flask import Flask, render_template, send_from_directory, redirect, request
from flask_pymongo import PyMongo
from collections import OrderedDict

locale.setlocale(locale.LC_ALL, "sv_SE.UTF-8")

app = Flask(__name__, static_url_path="")
app.jinja_env.auto_reload = True
app.config["TEMPLATES_AUTO_RELOAD"] = True
app.config["MONGO_URI"] = "mongodb://mongodb:27017/banking"
mongo = PyMongo(app)


@app.route("/")
def index():
    return redirect(f"/{datetime.datetime.now().strftime('%Y-%m')}/")


@app.route("/<string:ym>/")
def monthtransactions(ym):
    year, month = [int(d) for d in ym.split("-")]
    lastd = calendar.monthrange(year, month)[1]
    start = datetime.datetime(year, month, 1)
    end = datetime.datetime(year, month, lastd)
    transactions = list(mongo.db.transactions.find({"tdate": {"$gte": start, "$lte": end}}).sort("tdate", -1))
Example #11
0
from flask import Flask, jsonify
from flask_restful import reqparse, abort, Api, Resource, request
from flask_pymongo import PyMongo 
import os, json, simplejson

cur_dir = '/home/ubuntu/ugradproject/pythonserver/test0'
os.chdir(cur_dir)

app = Flask(__name__)
app.config["MONGO_DBNAME"] = "wifisniff_db"
app.config["MONGO_URI"] = "mongodb://amar:qwerty54321@ds031835.mlab.com:31835/wifisniff_db"
mongo = PyMongo(app, config_prefix="MONGO")
api = Api(app)

parser = reqparse.RequestParser()
parser.add_argument('data')

""" all files """

all_files = {
    "TEXT_FILES": [],
    "JSON_FILES": [],
    "CAP_FILES": [],
    "BASH_FILES": [],
    "PYTHON_FILES": [],
    "ZIP_FILES": []
}

MAP = {"txt": "TEXT_FILES", "json": "JSON_FILES", "cap": "CAP_FILES", "sh": "BASH_FILES", "py": "PYTHON_FILES", "zip": "ZIP_FILES"}

def file_ext(file_name):
Example #12
0
        },
       
    },
    "required": ["email", "password"],
    "additionalProperties": False
}


# Create instance of DatabaseConnector
databaseConnection = DatabaseConnector.DatabaseConnector()

# Create the Flask application and tell it where to look to serve HTML files
application = Flask(__name__, template_folder='react-frontend/templates', static_folder='react-frontend/static')

# Prepare the mongo instance
application.config["MONGO_URI"] = databaseConnection.getURI()
application.config['JWT_ACCESS_TOKEN_EXPIRES'] = datetime.timedelta(days=1)
application.config['PROPAGATE_EXCEPTIONS'] = True
application.config['SECRET_KEY'] = "'\xe9\xa5'"

# Create the Mongo object with our Flask application
mongo = PyMongo(application)
flask_bcrypt = Bcrypt(application)
jwt = JWTManager(application)

currentEmail = ""


# Extend the JSONEncoder class to support more stuff
class JSONEncoder(json.JSONEncoder):
Example #13
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 = []
    for planning in donnees:
        planning["_id"] = str(planning["_id"])
Example #14
0
import os
from flask import Flask, render_template, request
from flask.ext.pymongo import PyMongo

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


@app.route("/", methods=["GET", "POST"])
def index():
    name = None
    new = False
    if request.method == "POST" and "name" in request.form:
        name = request.form["name"]
        if mongo.db.names.find_one({"name": name}) is None:
            # this is a new name, add it to the database
            mongo.db.names.insert({"name": name})
            new = True
    return render_template("index.html", name=name, new=new)


if __name__ == "__main__":
    app.run(debug=True)
Example #15
0
# coding: utf-8

from datetime import datetime
import os

from gevent.wsgi import WSGIServer
from gevent import monkey
monkey.patch_all()

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

app = Flask(__name__)
app.config["MONGO_URI"] = os.environ.get('DBAAS_MONGODB_ENDPOINT', 'mongodb://localhost:27017/salalivre')
mongo = PyMongo(app)

MAX_EVENTS_PER_ROOM = 10
NUM_OF_LAST_EVENTS = 3
MAX_EVENTS_INTERVAL = 1 * 60  # seconds
ALIVE_INTERVAL = 3 * 60  # seconds

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


@app.route("/rooms", methods=['GET'])
def rooms():
    response = []
    rooms = mongo.db.rooms.find(sort=[('position', 1)]) or []
    for i, room in enumerate(rooms):
Example #16
0
import os
from flask import Flask, Response, request, json, render_template
from flask.ext.pymongo import PyMongo

# phone number is (424) 231-5779

app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb://user:password@ds039717.mongolab.com:39717/heroku_app8402029"

mongo = PyMongo(app)

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

@app.route("/json")
def votesAsJSON():
    data = {
        "A": mongo.db.votes.find({"to": "A"}).count(),
        "B": mongo.db.votes.find({"to": "B"}).count()
    }

    return Response(json.dumps(data), mimetype="application/json")

@app.route("/vote", methods=["post"])
def vote():
    msg = request.form["Body"]

    mongo.db.votes.insert({
        "to": request.form["Body"],
        "from": request.form["From"]