Example #1
0
def init_app(mongo_url):
    app = Flask(__name__)

    api = flask_restful.Api(app)
    api.representations = {'application/json': output_json}

    app.config['MONGO_URI'] = mongo_url
    mongo.init_app(app)

    with app.app_context():
        ConfigService.init_config()

    app.add_url_rule('/', 'serve_home', serve_home)
    app.add_url_rule('/<path:static_path>', 'serve_static_file', serve_static_file)

    api.add_resource(Root, '/api')
    api.add_resource(Monkey, '/api/monkey', '/api/monkey/', '/api/monkey/<string:guid>')
    api.add_resource(LocalRun, '/api/local-monkey', '/api/local-monkey/')
    api.add_resource(ClientRun, '/api/client-monkey', '/api/client-monkey/')
    api.add_resource(Telemetry, '/api/telemetry', '/api/telemetry/', '/api/telemetry/<string:monkey_guid>')
    api.add_resource(MonkeyConfiguration, '/api/configuration', '/api/configuration/')
    api.add_resource(MonkeyDownload, '/api/monkey/download', '/api/monkey/download/',
                     '/api/monkey/download/<string:path>')
    api.add_resource(NetMap, '/api/netmap', '/api/netmap/')
    api.add_resource(Edge, '/api/netmap/edge', '/api/netmap/edge/')
    api.add_resource(Node, '/api/netmap/node', '/api/netmap/node/')
    api.add_resource(Report, '/api/report', '/api/report/')
    api.add_resource(TelemetryFeed, '/api/telemetry-feed', '/api/telemetry-feed/')

    return app
Example #2
0
def create_app(mongo_uri, debug=False, testing=False):
    app = Flask(__name__)
    app.config['DEBUG'] = debug
    app.config['TESTING'] = testing
    app.config['WTF_CSRF_ENABLED'] = not testing
    app.config['MONGO_URI'] = mongo_uri
    app.secret_key = os.environ.get('SECRET_KEY', 'clef pour les tests')
    Babel(default_locale='fr').init_app(app)
    Gravatar().init_app(app)
    mongo.init_app(app)
    login_manager.init_app(app)
    bcrypt.init_app(app)

    app.register_blueprint(auth)
    app.register_blueprint(bookmarks)
    app.register_blueprint(tools, url_prefix='/tools')
    app.register_blueprint(profil, url_prefix='/profil')

    @app.before_first_request
    def create_mongo_index():
        mongo.db.bookmarks.ensure_index('published', pymongo.DESCENDING, background=True)
        mongo.db.bookmarks.ensure_index('user._id', pymongo.DESCENDING, background=True)
        mongo.db.bookmarks.ensure_index('title', pymongo.ASCENDING, background=True)
        mongo.db.bookmarks.ensure_index('description', background=True)
        mongo.db.bookmarks.ensure_index('tags', pymongo.ASCENDING, background=True)
        mongo.db.bookmarks.ensure_index([('user._id', pymongo.ASCENDING), ('url', pymongo.ASCENDING)], background=True, unique=True)

        mongo.db.users.ensure_index('email', pymongo.ASCENDING, background=True, unique=True)
        mongo.db.users.ensure_index('nickname', pymongo.ASCENDING, background=True, unique=True)


    @environmentfilter
    def group_by_humanize_date(environment, value, attribute):
        sorted_collections = sorted(value, key=make_attrgetter(environment, attribute))
        return map(_GroupTuple, groupby(sorted_collections, _make_attr_getter_for_date(environment, attribute)))
    app.jinja_env.filters['group_by_humanize_date'] = group_by_humanize_date

    @app.template_filter()
    def group_by_first_letter(array_of_string):
        return groupby(array_of_string, key=operator.itemgetter(0))

    def _make_attr_getter_for_date(environment, attribute):
        def callback(x):
            return arrow.get(environment.getitem(x, attribute)).humanize(locale='FR_fr')

        return callback

    return app
Example #3
0
def init_app(mongo_url):
    app = Flask(__name__)

    api = flask_restful.Api(app)
    api.representations = {'application/json': output_json}

    app.config['MONGO_URI'] = mongo_url

    app.config['SECRET_KEY'] = os.urandom(32)
    app.config['JWT_AUTH_URL_RULE'] = '/api/auth'
    app.config['JWT_EXPIRATION_DELTA'] = env.get_auth_expiration_time()

    init_jwt(app)
    mongo.init_app(app)

    with app.app_context():
        database.init()
        ConfigService.init_config()

    app.add_url_rule('/', 'serve_home', serve_home)
    app.add_url_rule('/<path:static_path>', 'serve_static_file', serve_static_file)

    api.add_resource(Root, '/api')
    api.add_resource(Monkey, '/api/monkey', '/api/monkey/', '/api/monkey/<string:guid>')
    api.add_resource(LocalRun, '/api/local-monkey', '/api/local-monkey/')
    api.add_resource(ClientRun, '/api/client-monkey', '/api/client-monkey/')
    api.add_resource(Telemetry, '/api/telemetry', '/api/telemetry/', '/api/telemetry/<string:monkey_guid>')
    api.add_resource(MonkeyConfiguration, '/api/configuration', '/api/configuration/')
    api.add_resource(MonkeyDownload, '/api/monkey/download', '/api/monkey/download/',
                     '/api/monkey/download/<string:path>')
    api.add_resource(NetMap, '/api/netmap', '/api/netmap/')
    api.add_resource(Edge, '/api/netmap/edge', '/api/netmap/edge/')
    api.add_resource(Node, '/api/netmap/node', '/api/netmap/node/')
    api.add_resource(Report, '/api/report', '/api/report/')
    api.add_resource(TelemetryFeed, '/api/telemetry-feed', '/api/telemetry-feed/')
    api.add_resource(Log, '/api/log', '/api/log/')

    return app
Example #4
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 #5
0
import json
import copy
import unittest
from flask import Flask
from flask.ext.pymongo import PyMongo
from handlers.user import user
from handlers.transfers import transfer
from db_utils.db_utils import mongo

MONGO_URL = "mongodb://localhost:27017/testfakebutton"
test_application = Flask(__name__)
#register all of the handlers with this app
test_application.register_blueprint(user)
test_application.register_blueprint(transfer)
test_application.config['MONGO_URI'] = MONGO_URL
test_application.config['MONGO_AUTO_START_REQUEST'] = False
test_application.config['TESTING'] = True
test_application.config['DEBUG'] = True
mongo.init_app(test_application)
test_app = test_application.test_client()

def response_success(response, code=None):
    if code is None:
        assert 200 <= response.status_code < 300, 'Received %d response: %s' % (response.status_code, response.data)
    else:
        assert code == response.status_code, 'Received %d response: %s' % (response.status_code, response.data)

def response_error(response, code=None):
    if code is None:
        assert 400 <= response.status_code < 500, 'Received %d response: %s' % (response.status_code, response.data)
    else:
Example #6
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 #7
0
import os
from flask import Flask, request, g, send_from_directory
from flask.ext import restful

from pymongo.errors import OperationFailure
from flask_pymongo import PyMongo
from functools import wraps
from bson.json_util import dumps

app = Flask(__name__, template_folder='../templates', static_folder='../static')
api = restful.Api(app)
app.config['MONGO_URI'] = os.environ.get('MONGOSOUP_URL', 'mongodb://localhost/sensor')
mongo = PyMongo(app)
app.debug = True

def remove_id(data):
        if '_id' in data:
            del data['_id']
        return data


def prepare_response(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        data = f(*args, **kwargs)
        return remove_id(data)
    return decorated

@app.route('/bower_components/<path:filename>')
def custom_static(filename):
    return send_from_directory(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'bower_components')), filename)
Example #8
0
import os
import pymongo

from bson.json_util import dumps
from flask import Flask, request, jsonify
from flask_pymongo import PyMongo
from datetime import datetime

app = Flask(__name__)

app.config['MONGO_URI'] = 'mongodb://{host}:{port}/{database}'.format(
    host=os.environ.get('MONGODB_HOST', 'localhost'),
    port=os.environ.get('MONGODB_PORT', 27017),
    database=os.environ.get('MONGODB_DB', 'movieweb')
)

mongo = PyMongo(app)


@app.route('/ratings/<int:movieid>', methods=['POST'])
def update_movie_rating(movieid):
    user = request.headers.get('user', None)
    if not user:
        return dumps('unauthorized'), 401
    
    query = {
        'userid': user,
        'movieid': movieid
    }
    update = {'$set': {
        'rating': int(request.form['rating']),
Example #9
0
app.config['BOOTSTRAP_GOOGLE_ANALYTICS_ACCOUNT'] = conf('BOOTSTRAP_GOOGLE_ANALYTICS_ACCOUNT')
Bootstrap(app)

oauth = OAuth()
meetup_oauth = 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'),
)
meetup = Meetup(meetup_oauth)

app.config['MONGO_URI'] = conf('MONGOHQ_URL', 'mongodb://localhost/meetups')
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,
Example #10
0
import os
from flask import Flask, render_template, make_response, request, Response
from flask.ext.pymongo import PyMongo
import pusher


app = Flask("app18297361")
app.debug = True
app.config['PORT'] = 5000
app.config['MONGO_URI'] = os.getenv("MONGOHQ_URL", "mongodb://localhost:27017/sms-mailing-list")
mongo = PyMongo(app)

p = pusher.Pusher(
  app_id='54995',
  key='81830a54c2d8b0878390',
  secret='750dcc0203a9094075bc'
)


@app.route("/graph")
def showGraph():
    return render_template("landing.html")

def broadcastVote(vote):
    p['vote_channel'].trigger("vote_event", {"message" : vote})

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

@app.route('/', methods=['POST'])
Example #11
0
from flask import Flask,jsonify,request
from flask_pymongo import PyMongo,pymongo
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

app.config['MONGO_DBNAME'] = 'api_data'
app.config['MONGO_URI'] = 'mongodb://siddharth:jain@ds223760.mlab.com:23760/api_data'

mongo = PyMongo(app)

@app.route('/api')
def get_all():
	photos = mongo.db.photos
	output = []

	offset = int(request.args['offset'])
	limit = int(request.args['limit'])

	start = photos.find().sort('_id', pymongo.ASCENDING)
	last = start[offset]['_id']

	pid = photos.find({'_id' : {'$gte' : last}}).sort('_id', pymongo.ASCENDING).limit(limit)

	for q in pid:
		output.append({'title' : q['title'], 'url' : q['url'] })

	next_url = '/api?limit=' +str(limit)+ '&offset=' +str(offset+limit)
	prev_url = '/api?limit=' +str(limit)+ '&offset=' +str(offset-limit)
Example #12
0
# -*- coding: utf-8 -*-

from flask.ext.pymongo import PyMongo
from flask_wtf.csrf import CsrfProtect
from flask import Flask, flash, request, redirect, render_template, url_for
from bson.objectid import ObjectId

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


@app.route("/")
def index():
    series = mongo.db.series.find()
    return render_template("index.html", series=series)


@app.route("/series/add/")
def serie_add_form():
    return render_template("add.html")


@app.route("/series/add/", methods=['POST'])
def serie_add():
    mongo.db.series.insert(request.form.to_dict())
    return redirect('/')


@app.route("/series/<serie_id>/edit/")
def series_edit_form(serie_id):
Example #13
0
from flask.ext.pymongo import PyMongo
from flask import Flask, request, render_template, redirect, url_for, session, jsonify, g
from bson.objectid import ObjectId

VENMO_OAUTH_CLIENT_ID = "1601"
VENMO_OAUTH_CLIENT_SECRET = "kS6Xwrd9rzzkSd3C2BcjhJFMAxH3Kv3P"
VENMO_ACCESS_TOKEN = "eSN3Z3A2KeRbcnNTqgLu6mRA4K9uED9V"
VENMO_OAUTH_URL = "https://venmo.com/oauth/authorize?client_id=%s&scope=make_payments,access_profile,access_phone,access_friends,access_balance&response_type=code" % VENMO_OAUTH_CLIENT_ID

TWITTER_OAUTH_URL = "https://api.twitter.com/oauth/authorize"


MATCHMAKING_TIMEOUT = 5 # seconds

app = Flask(__name__)
app.config['MONGO_URI'] = "mongodb://ludacris:moneymaker@ds033499.mongolab.com:33499/betson"
app.secret_key = 'zgzQQCCn50mDwScfOyQ9'
app.debug = True
mongo = PyMongo(app)
# oauth = OAuth()

# twitter = oauth.remote_app('twitter',
#     base_url='https://api.twitter.com/1/',
#     request_token_url='https://api.twitter.com/oauth/request_token',
#     access_token_url='https://api.twitter.com/oauth/access_token',
#     authorize_url='https://api.twitter.com/oauth/authenticate',
#     consumer_key='7DEWbqXHmfrZGz9LMtIIgA',
#     consumer_secret='1Qt315xblwCCDbsSWRN2jaYCZzzsM6wACZrtPTyXWs'
# )
# 
# request_token, request_token_secret = twitter.get_request_token()
Example #14
0
#  import for flask
from flask import Flask, render_template, request, session, redirect, url_for
from flask_pymongo import PyMongo

app = Flask(__name__)

database_file = open('db.txt', 'U')
db_host = database_file.readline().strip() #URL and port
dbname = database_file.readline().strip()
user = database_file.readline().strip()
password = database_file.readline().strip()
database_file.close()
app.config['MONGO_DBNAME'] = dbname
app.config['MONGO_URI'] = 'mongodb://' + user + ':' + password + '@' + db_host + '/' + dbname
app.config['MONGO_CONNECT'] = False

mongo = PyMongo()
with app.app_context():
	mongo.init_app(app)

import json

#Copy from StackOverflow-----------------------------
from os import path
import os

extra_dirs = ['static','templates']
extra_files = extra_dirs[:]
for extra_dir in extra_dirs:
    for dirname, dirs, files in os.walk(extra_dir):
        for filename in files:
Example #15
0
from utils import CATEGORIES


COLORS = [
    '#D93B3B', '#7cb5ec', '#90ed7d', '#f7a35c',
    '#8085e9', '#c015e9', '#2B9658', '#b2b2b2'
]
LIMIT = 30


app = Flask(__name__)
moment = Moment(app)
# Mongo setup
# mongodb://mongo:27017/hn_demo
app.config['MONGO_URI'] = os.environ['MONGO_URI']
mongo = PyMongo(app)


def get_statistics(posts):
    data = {}

    # Generate time intervals used to filter posts
    now = datetime.datetime.now()
    time_intervals = [(
        (now-datetime.timedelta(hours=i)).replace(
            minute=0,
            second=0,
            microsecond=0),
        (now-datetime.timedelta(hours=i-1)).replace(
            minute=0,
Example #16
0
import json

from bson import json_util





app = Flask(__name__)



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

app.config['MONGO_URI'] =  'mongodb://admin:admin@ds017185.mlab.com:17185/beautybeatdata'



mongo = PyMongo(app)



@app.route('/add')

def maxExampleAdd():
    
    product = mongo.db.products
    
    product.insert({'No':'1','productName': 'Anthony Green  Cream Foundation','imageURL': 'http://imagebbdev4.s3.amazonaws.com/1.png'})
    product.insert({'No':'2','productName': 'Anthony Green Hi-Def Liquid Foundation','imageURL': 'http://imagebbdev4.s3.amazonaws.com/2.png'})
Example #17
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 #18
0
from flask.ext.pymongo import PyMongo
from flask.ext.mail import Mail, Message
from bson.objectid import ObjectId
import sys
from HTMLParser import HTMLParser
from datetime import datetime
import json

import mailer

app = Flask(__name__)
app.config['MAIL_SERVER'] = "smtp.sendgrid.net"
app.config['MAIL_PORT'] = 587
app.config['MAIL_USERNAME'] = ""
app.config['MAIL_PASSWORD'] = ""
app.config['MONGO_URI'] = "mongodb://:@ds043338.mongolab.com:43338/grubhero-dev"
app.secret_key = '<this was removed, smartass>' # cookie-session
mongo = PyMongo(app)
mail = Mail(app)

JQUERY_TIME_FORMAT = "%m/%d/%Y %I:%M %p"

VENMO_OAUTH_CLIENT_ID = "1354"
VENMO_OAUTH_CLIENT_SECRET = "<this was removed, smartass>"
VENMO_ACCESS_TOKEN = "<this was removed, smartass>"
VENMO_OAUTH_URL = "https://venmo.com/oauth/authorize?client_id=%s&scope=make_payments,access_profile&response_type=code" % VENMO_OAUTH_CLIENT_ID

def logged_in():
    return 'venmo_id' in session

# http://stackoverflow.com/a/925630
Example #19
0
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':
        users = mongo.db.users
Example #20
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
    """ import for the view fuction"""
    # from ast import literal_eval
Example #21
0
from flask_pymongo import PyMongo

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

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

# @app.before_request
Example #22
0
from flask import Flask
from flask.ext.pymongo import PyMongo

app = Flask(__name__)

# connect to MongoDB with the defaults

app.config['MONGO_URI'] = 'mongodb://test:TestBuggl@ds041633.mongolab.com:41633/buggl'
mongo1 = PyMongo(app,config_prefix="MONGO")

@app.route('/')
def plan():
    user = mongo1.db.entries.find_one_or_404({'plan': "plan1"})
    return user

# user = mongo1.db.users.find_one_or_404({'plan': "plan1"})
Example #23
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}
    return obj
Example #24
0
# from flask_celery import make_celery
# from flask.ext.mongoalchemy import MongoAlchemy


class JSONEncoder(json.JSONEncoder): 
    def default(self, o):
        if isinstance(o, ObjectId):
            return str(o)
        return json.JSONEncoder.default(self, o)




app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'star_wars_db'
app.config['MONGO_URI'] = 'mongodb://isaiasgomes:isaiasgomes0@ds239931.mlab.com:39931/star_wars_db' #URI MLAB

# app.config['CELERY_BROKER_URL'] = 'ampq://localhost//'
# app.config['CELERY_BACKEND'] = 'mongodb://isaiasgomes:isaiasgomes0@ds239931.mlab.com:39931/star_wars_db' #URI MLAB
# app.config['MONGOALCHEMY_CONNECTION_STRING']= 'mongodb://isaiasgomes:isaiasgomes0@ds239931.mlab.com:39931/star_wars_db' #URI MLAB

# celery = make_celery(app)
mongo = PyMongo(app)

@app.route('/planeta', methods=['GET'])
def get_all(): 
    return jsonify({'planetas' : get_all_planets()})
    

@app.route('/planeta/id/<ObjectId:_id>', methods=['GET'])
@app.route('/planeta/id/<int:id>', methods=['GET'])
Example #25
0
from flask import Flask, render_template, json, request, Response, jsonify
from flask.ext.pymongo import PyMongo
from mongoengine import connect
from flask.ext.mongoengine import MongoEngine
import subprocess

app = Flask(__name__)

# app.config['MONGO_HOST'] = '127.10.85.2'
# app.config['MONGO_PORT'] = 27017
# app.config['MONGO_DBNAME'] = 'runlinux'
app.config['MONGO_URI'] = 'mongodb://127.10.85.2:27017/runlinux'
app.config['MONGO_USERNAME'] = 'admin'
app.config['MONGO_PASSWORD'] = 'dp53nstHebqE'
mongo = PyMongo(app, config_prefix='MONGO')

# mongo = PyMongo(app) #for local MongDB

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

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

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

@app.route('/linuxCommand')
Example #26
0
# -*- coding: utf-8 -*-

import os
from flask import Flask
# from flask.ext.pymongo import PyMongo
from flask.ext.assets import Environment, Bundle
from flask.ext.mongoengine import MongoEngine

from momentjs import momentjs

import re
from jinja2 import evalcontextfilter, Markup, escape


app = Flask(__name__)
app.config['MONGO_URI'] = os.getenv('MONGOHQ_URI', 'mongodb://dev:dev@localhost/federation')
app.config['MONGODB_SETTINGS'] = {'db': 'federation', 'host': app.config['MONGO_URI']}
app.config['FACEBOOK_AUTH'] = os.getenv('FACEBOOK_AUTH')

app.config['SECURITY_PASSWORD_HASH'] = 'bcrypt'
app.config['SECURITY_PASSWORD_SALT'] = os.getenv('SECURITY_PASSWORD_SALT', '')
app.config['SECURITY_CHANGEABLE'] = True
app.config['SECURITY_TRACKABLE'] = True

app.secret_key = os.getenv('SECRET_KEY', '')

app.jinja_env.globals['momentjs'] = momentjs
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True

Example #27
0
import os
from flask import Flask, request, render_template, redirect, url_for, g
from flask_pymongo import PyMongo
import flask_pymongo
from flask_babel import Babel
from storyzer import storyze, format_story
from bson.objectid import ObjectId


app = Flask(__name__)
app.debug = True
babel = Babel(app)
app.config['MONGO_URI'] = os.environ.get('MONGOLAB_URI')
app.config['GSE_API_KEY'] = os.environ.get('GSE_API_KEY')
app.config['GSE_CX_ID'] = os.environ.get('GSE_CX_ID')
mongo = PyMongo(app)


@app.before_request
def before():
    if request.view_args and 'lang_code' in request.view_args:
        g.current_lang = request.view_args['lang_code']
        request.view_args.pop('lang_code')


@babel.localeselector
def get_locale():
    return g.get('current_lang', 'en')


@app.route('/')
Example #28
0
__author__ = 'jay'

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

app = Flask(__name__)
app.config['MONGO_DBNAME'] = '99movies'
app.config['MONGO_URI'] = 'mongodb://jayesh:jayesh@kahana.mongohq.com:10008/99movies'
api = Api(app)
mongo = PyMongo(app)

VERSION = 'v1'
Example #29
0
	resp.headers.extend(headers or {})
	return resp

DEFAULT_REPRESENTATIONS = {'application/json': output_json}

app = Flask(__name__)

app.secret_key = 'heroku_gfp8zr4k:mu22sv8pm9q3b5o286vfjjq870@ds015335'
login_manager = LoginManager()
login_manager.init_app(app)

MONGO_URI = os.environ.get('MONGO_URL')
if not MONGO_URI:
	MONGO_URI = "mongodb://heroku_gfp8zr4k:mu22sv8pm9q3b5o286vfjjq870@ds015335.mlab.com:15335/heroku_gfp8zr4k"

app.config['MONGO_URI'] = MONGO_URI
mongo = PyMongo(app)
api = Api(app)
api.representations = DEFAULT_REPRESENTATIONS

@login_manager.user_loader
def load_user(user_id):
	return User.get(user_id)

class index(Resource):
	def get(self):
		return {"Hello": "World"}

class parseAllPage(Resource):
	def get(self):
		page = 1 if not 'page' in request.headers else int(request.headers['page'])
from flask import Flask, request, jsonify, make_response, url_for,render_template, abort
from flask_pymongo import PyMongo
from flask_triangle import Triangle
from bson import json_util, objectid
from datetime import datetime, timedelta
import re#regular expression
import os

app = Flask(__name__)
Triangle(app)
app.debug = True


app.config['MONGO_URI'] = "mongodb://agriapp:simplePassword@ds043057.mongolab.com:43057/heroku_app24455461";
# app.config['MONGO_URI'] = "mongodb://localhost/agrinet";
mongo = PyMongo(app)



#Helper/Utility functions
def convert_compatible_json(crop):
	crop["date"] = crop["date"].strftime('%Y-%m-%dT%H:%M:%S')	#convert the date object to a string
	crop["id"] = str(crop["_id"])								#convert mongodb id to a string
	del crop["_id"] 											#remove original key
	return crop


def process_results(cursor):
	res = []
	for c in cursor:
		res.append(convert_compatible_json(c))