Exemplo n.º 1
0
def create_manager(case_api_client=CaseApi):
    app = FlaskAPI(__name__)
    app.config.from_pyfile('config.py')

    manager = Manager(app)
    app.register_blueprint(helloworld.blueprint)
    app.register_blueprint(deed.blueprint(case_api_client()))

    db.init(app, manager)

    return manager
Exemplo n.º 2
0
def create_app(config_name):
    app = FlaskAPI(__name__)

    app.config.from_object(config[config_name])

    config[config_name].init_app(app)

    db.init_app(app)

    from api.v1 import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api/v1')

    return app
Exemplo n.º 3
0
def create_manager():
    app = FlaskAPI(__name__)

    app.config.from_pyfile('config.py')

    app.register_blueprint(helloworld.blueprint)
    app.register_blueprint(home.blueprint)
    app.register_blueprint(case.blueprint)
    app.register_blueprint(borrower.blueprint)
    app.register_blueprint(property.blueprint)
    app.register_blueprint(land_registry.blueprint)

    manager = Manager(app)
    db.init(app, manager)

    return manager
Exemplo n.º 4
0
def create_manager(deed_api_client=DeedApi):
    app = FlaskAPI(__name__)
    app.config.from_pyfile('config.py')

    app.register_blueprint(helloworld.blueprint)
    app.register_blueprint(key.blueprint)
    app.register_blueprint(sign.blueprint(deed_api_client()))

    manager = Manager(app)
    db.init(app, manager)

    return manager
Exemplo n.º 5
0
from flask import request
from flask.ext.api import FlaskAPI
from flask.ext.api.exceptions import ParseError

from marshmallow import ValidationError

import schema
import models


app = FlaskAPI(__name__)
models.db.init_app(app)

app.config.from_object("settings.Config")

app.config["DEFAULT_RENDERERS"] = [
    "flask.ext.api.renderers.JSONRenderer",
    "flask.ext.api.renderers.BrowsableAPIRenderer",
]


@app.route("/query", methods=["GET", "POST"])
def stocks():
    """Simplest possible implementation of this algorithm."""
    s = schema.QuerySetSchema(strict=True)

    try:
        q = s.load(request.data)
    except ValidationError as err:
        raise ParseError(detail="Bad fields: {}".format(err.field_names))
Exemplo n.º 6
0
# -*- coding: utf-8 -*-

from flask import Flask, redirect, url_for, request, jsonify, json, abort, g
import os
from flask.ext.api import FlaskAPI, status, exceptions
from flask.ext.basicauth import BasicAuth
from flask_cors import CORS
from parse_rest.connection import register
from parse_rest.datatypes import Object
from parse_rest.user import User as ParseUser
from parse_rest.core import ResourceRequestBadRequest, ResourceRequestForbidden,\
    ResourceRequestNotFound, ResourceRequestLoginRequired
from werkzeug.datastructures import MultiDict

app = FlaskAPI(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
app.config['BASIC_AUTH_USERNAME'] = os.environ.get('AUTH_U', 'spam')
app.config['BASIC_AUTH_PASSWORD'] = os.environ.get('AUTH_P', 'eggs')

basic_auth = BasicAuth(app)

port = int(os.environ.get('PORT', 5000))

if port == 5000:
    app.debug = True

# Load up args from env and hop on to parse
# Load up from .env for foreman on heroku
register(os.environ.get('PARSE_APP_ID'), os.environ.get(
    'PARSE_APP_KEY'), master_key=os.environ.get('PARSE_SECRET_KEY'))
Exemplo n.º 7
0
from flask import request, url_for, jsonify, send_from_directory
from flask.ext.api import FlaskAPI, status, exceptions

app = FlaskAPI(__name__)

mem = {}


def solve(eq):
    total = int(eq[0])
    i = 1
    while True:
        if eq[i] == '+':
            total += int(eq[i + 1])
            i += 2
        elif eq[i] == '-':
            total -= int(eq[i + 1])
            i += 2
        elif eq[i] == '=':
            summ = int(eq[i + 1])
            break
        else:
            raise ValueError("Invalid equation: %s" % eq)
    return total == summ


def find_matches(l, total):
    """
    Takes a list of consecutive integers, i.e [1,2,3,4] and a total, i.e 100.
    Uses dynamic programming to recursivly find arrangments of '-' and '+' that, when inserted into the list,
    create an equation that is correct.
Exemplo n.º 8
0
from werkzeug.routing import ValidationError
from flask import send_file

from omas import meiinfo
from omas import meislicer
from omas.exceptions import CannotReadMEIException
from omas.exceptions import BadApiRequest
from omas.exceptions import CannotWriteMEIException
from omas.exceptions import CannotAccessRemoteMEIException
from omas.exceptions import UnknownMEIReadException
from omas.exceptions import UnsupportedEncoding

from flask.ext.cors import CORS


app = FlaskAPI(__name__)
CORS(app)

app.config['DEFAULT_RENDERERS'] = [
    'flask.ext.api.renderers.JSONRenderer',
    'flask.ext.api.renderers.BrowsableAPIRenderer',
]

app.config['DEFAULT_PARSERS'] = [
    'flask.ext.api.parsers.JSONParser',
]


# CONVERTERS
class MeasuresConverter(BaseConverter):
Exemplo n.º 9
0
from flask.ext.api import FlaskAPI
from flask import request
from flask.ext.cors import CORS
import sys

if "m" not in sys.argv:
    from memorydb.DB import *
else:
    from mongoDB.DB import *

app = FlaskAPI(__name__)
CORS(app)


@app.route("/api/prices", methods=["GET"])
def prices():
    id = request.args.get("id")
    return DB.getprices(id)


@app.route("/api/prices", methods=["POST"])
def upsertprices():
    data = request.data
    DB.upsertprices(data)
    return ""


@app.route("/api/sales", methods=["POST"])
def upsertsales():
    data = request.data
    DB.upsertsales(data)
Exemplo n.º 10
0
import argparse
import re
import subprocess


parser = argparse.ArgumentParser()
parser.add_argument('--host', default='localhost')
parser.add_argument('--port', default=5000, type=int)
parser.add_argument(
    '--debug',
    default=False,
    action='store_true',
    help='Set the server in debug mode'
)

app = FlaskAPI(__name__)


def _tab_list_str_to_dict(tab_str, request):
    matches = re.search(
        r'^\[(?P<window_id>\d+):(?P<tab_id>\d+)\](?P<tab_title>.+)$', tab_str
    )
    if matches is None:
        return {}
    tab = {
        'id': matches.group('tab_id'),
        'title': matches.group('tab_title'),
        'window': matches.group('window_id'),
    }
    tab['tab_view_url'] = '%stabs/%s' % (request.url_root, tab['id'])
    tab['title'] = tab['title'].strip()
Exemplo n.º 11
0
from webargs.flaskparser import FlaskParser
from webargs import Arg

from modularodm import Q

from neurotrends.config import (
    stats_collection,
    tag_counts_collection,
)
from neurotrends import model

from . import serializers, settings, utils


app = FlaskAPI(__name__)
app.config['CORS_HEADERS'] = 'Content-Type'
cors = CORS(app)

parser = FlaskParser()


ARTICLE_PAGE_NUM_DEFAULT  = 1
ARTICLE_PAGE_SIZE_DEFAULT = 20
ARTICLE_PAGE_SIZE_OPTIONS = [10, 20, 50]
ARTICLE_SORT_DEFAULT      = 'title'

AUTHOR_PAGE_NUM_DEFAULT   = 1
AUTHOR_PAGE_SIZE_DEFAULT  = 20
AUTHOR_PAGE_SIZE_OPTIONS  = [10, 20, 50]
AUTHOR_SORT_DEFAULT       = 'lastname'
Exemplo n.º 12
0
#           |  Nombre del elemento  |     Responsabilidad     |      Propiedades       |
#           +-----------------------+-------------------------+------------------------+
#           |                       |  - Ofrecer una interfaz | - Comunicarce con los  |
#           |      API Gateway      |    para la comunicacion |   microservicios       |
#           |                       |   con los microservicios|   sv_information,      |
#           |                       |    del sistema          |   sv_gestor_tweets y   |
#           |                       |                         |   sv:information       |
#           +-----------------------+-------------------------+------------------------+
#

import os
import requests
from flask import request, render_template
from flask.ext.api import FlaskAPI

app = FlaskAPI(__name__)


# Ruta que llama al microservicio sv_information para que busque información
# por medio de la API de OMDb acerca de la serie o película cuyo título se
# recibe como parámetro y devuelve un JSON con los resultados.
@app.route("/api/movie/information", methods=['GET'])
def obtener_information():
    url = 'http://localhost:8087/information'
    response = requests.get(url, request.args)
    return response.json(), response.status_code


# Ruta que llama al microservicio sv_gestor_tweets para que busque los tweets
# acerca de la serie o película cuyo título se recibe como parámetro y
# devuelva un JSON con los resultados.
Exemplo n.º 13
0
from flask.ext.api import FlaskAPI, exceptions
from flask import request, send_file
from gif_factory import GifFactory
from fileremover import FileRemover
import giphy

app = FlaskAPI(__name__)
factory = GifFactory()
file_remover = FileRemover()


@app.route('/', methods=['GET', 'POST'])
def giffer():
    if request.method == 'POST':
        data = request.data
        if 'gif' in data and 'search' in data:
            raise exceptions.ParseError
        if 'gif' not in data and 'search' not in data:
            raise exceptions.ParseError

        if 'search' in data:
            if 'search_type' in data and data['search_type'] == 'translate':
                data['gif'] = giphy.translate(data['search'])
            else:
                data['gif'] = giphy.search(data['search'])
            data.pop('search')
            data.pop('search_type', None)

        gif_file = factory.create(**data)
        resp = send_file(gif_file)
        # delete the file after it's sent
Exemplo n.º 14
0
#!/usr/bin/python
# coding=utf-8

from flask.ext.api import FlaskAPI
from conf.config import LocalConfig
from modules.authentication import authentication, auth
from modules.authors import authors
from modules import mongo

application = FlaskAPI(__name__)
application.config.from_object(LocalConfig)

application.register_blueprint(authentication, url_prefix='/authentication')
application.register_blueprint(authors, url_prefix='/authors')

mongo.init_app(application)


@application.route('/')
@auth.login_required
def index_testing():
    return {'status': 'OK'}


if __name__ == "__main__":
    application.run(
        host=application.config['HOST'],
        debug=application.config['DEBUG'],
        port=application.config['PORT'],
    )
Exemplo n.º 15
0
from flask import request, url_for
from flask.ext.api import FlaskAPI, status, exceptions
import subprocess
import yaml
from werkzeug import secure_filename
import codecs
import json
import time

app = FlaskAPI(__name__)
ALLOWED_EXTENSIONS = set(['txt', 'pdf'])


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


def translate(text):
    start_time = time.time()
    """
    Run translation model using config
    """
    with open('/home/moses/Downloads/moses-api/config.yaml', 'r') as f:
        doc = yaml.load(f)
    fileIn = doc['sample-models']['in']
    fileOut = doc['sample-models']['out']
    homeDir = doc['sample-models']['homeDir']
    runCommand = doc['sample-models']['command']
    status = 'Files successfully read'
    subprocess.call(['rm %s && rm %s' % (fileIn, fileOut)], shell=True)
Exemplo n.º 16
0
from flask.ext.api import FlaskAPI
from flask import request, current_app, abort
from functools import wraps

app = FlaskAPI(__name__)
app.config.from_object('settings')


def token_auth(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if request.headers.get('X-API-TOKEN',
                               None) != current_app.config['API_TOKEN']:
            abort(403)
        return f(*args, **kwargs)

    return decorated_function


@app.route('/score', methods=['POST'])
@token_auth
def score():
    from engine import content_engine
    item = request.data.get('item')
    num_scores = request.data.get('num', 10)
    if not item:
        return []
    return content_engine.score(str(item), num_scores)


@app.route('/train')
Exemplo n.º 17
0
import logging

import status
import trafaret as t
from flask import redirect, request
from flask.ext.api import FlaskAPI
from flask_debugtoolbar import DebugToolbarExtension
from flask_swagger import swagger
from graphql.core.error import GraphQLError, format_error

from factories import *
from models import *
from ql import schema
from utils import *

app = FlaskAPI(__name__, static_url_path='/static')
app.config.from_object('settings.DevConfig')

toolbar = DebugToolbarExtension(app)

logger = logging.getLogger(__package__)


@app.route('/ui')
def ui():
    return redirect('/static/index.html')


@app.route('/graph-query', methods=['POST'])
def query():
    """
from flask.ext.api import FlaskAPI
from flask import request, current_app
import listingPrediction
app = FlaskAPI(__name__)

classifier = listingPrediction.Classifier()


@app.route("/classify", methods=['POST'])
def classify():
    toClassify = request.args.get('link')  #request.data['link']
    return '{0}({1})'.format("resp",
                             classifier.predictionFromLink(toClassify)[0])


if __name__ == "__main__":
    listingPrediction.jsonDump()
    classifier.csvDump()
    classifier.train()
    app.run(debug=True)
Exemplo n.º 19
0
__author__ = 'Alec Nunn'

import sqlite3

from flask.ext.api import FlaskAPI
from flask import _app_ctx_stack, stream_with_context, Response
import time
from common import *

app = FlaskAPI(__name__)


def get_db():
    """
    Opens a connection to the database and returns the database as an object

    Don't forget to close the connection when you are finished please and
    thank you
    """
    sqlite_db = sqlite3.connect('test.db')
    sqlite_db.row_factory = sqlite3.Row
    sqlite_db.create_function('inet_ntoa', 1, get_ip)
    sqlite_db.create_function('inet_aton', 1, get_dec)
    return sqlite_db


def stream_query(q, args):
    """
    Queries the DB
    Returns a generator that "streams" the query results.
    Useful for streaming large data-sets.
Exemplo n.º 20
0
import random
import sys
import uuid

from flask import render_template, url_for, abort, send_file
from flask.ext.api import FlaskAPI
from flask.ext.api.decorators import set_renderers
from flask.ext.api.renderers import HTMLRenderer
from helpers.parsers import CoOccurrenceMatrixParser, JsonParser
# Data from external modules
from data import dendrogram
from examples import example_types

app = FlaskAPI(__name__)


@app.route("/data/score-display/")
def data_score_display():
    """
    Missing docstring.
    """
    return send_file("../data/scores/Absalon-fili-mi_Josquin-Des-Prez_file5.mei")


@app.route("/data/pie-chart/")
def data_pie_chart():
    """
    Missing DOCSTRING.
    Please tell me what this function does...
    """
    return [
Exemplo n.º 21
0
# Demo application that notify a message coming from REST API to a message bus (rabbitmq)

from flask.ext.api import FlaskAPI, status
from flask import request
from postman import Postman
app = FlaskAPI(__name__)

# Msg bus configuration
postman = Postman('app/config.ini')

@app.route('/notify', methods=['POST'])
def notify():
	msg = request.form['msg']
	postman.send_message(msg)
	return '', status.HTTP_201_CREATED

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)
Exemplo n.º 22
0
from flask import request
from flask.ext.api import FlaskAPI, status
import psycopg2
from psycopg2.extras import RealDictCursor
import random
import urlparse
import json


app = FlaskAPI(__name__)
app.config['SECRET_KEY'] = 'JDas8dj123e&&@0h';

urlparse.uses_netloc.append("postgres")
url = urlparse.urlparse('postgres://*****:*****@ec2-107-20-178-83.compute-1.amazonaws.com:5432/d4neua8lk9eb55')

print "\n---Starting app.py"

db = psycopg2.connect(
	database=url.path[1:],
	user=url.username,
	password=url.password,
	host=url.hostname,
	port=url.port
)
print " + Opened database successfully"
cur = db.cursor(cursor_factory=RealDictCursor)

cur.execute("CREATE TABLE IF NOT EXISTS dataunits (id SERIAL PRIMARY KEY, username CHAR(20), comment CHAR(100), dataunit CHAR(256));")
print " + Table created successfully (or already existed)"
db.commit()
Exemplo n.º 23
0
from flask.ext.api import FlaskAPI, exceptions
from flask import request, send_file
from gif_factory import GifFactory
from fileremover import FileRemover
import giphy

app = FlaskAPI(__name__)
factory = GifFactory()
file_remover = FileRemover()

@app.route('/', methods = ['GET', 'POST'])
def giffer():
    if request.method == 'POST':
        data = request.data
        if 'gif' in data and 'search' in data:
            raise exceptions.ParseError
        if 'gif' not in data and 'search' not in data:
            raise exceptions.ParseError

        if 'search' in data:
            if 'search_type' in data and data['search_type'] == 'translate':
                data['gif'] = giphy.translate(data['search'])
            else:
                data['gif'] = giphy.search(data['search'])
            data.pop('search')
            data.pop('search_type', None)

        gif_file = factory.create(**data)
        resp = send_file(gif_file)
        # delete the file after it's sent
        # http://stackoverflow.com/questions/13344538/how-to-clean-up-temporary-file-used-with-send-file
from flask.ext.api import FlaskAPI
from application.main.controllers import main
from application.admin.controllers import admin

app = FlaskAPI(__name__)

app.register_blueprint(main, url_prefix='/')
app.register_blueprint(admin, url_prefix='/admin')
Exemplo n.º 25
0
#!/usr/bin/python
import os

from flask.ext.api import FlaskAPI, status, exceptions
from src.configuration import Configuration
from src.validation.validation_handler import initialize_validators as hook_validators

# Initialize Flask API.
app = FlaskAPI(__name__.split('.')[0], static_url_path='/')

# Get routes.
from src.routes import route

# Acquire controllers.
from src.controllers import (Controllers)

# Get configuration.
config = Configuration()

# Set routes for flask application.
route(app, Controllers, config)

# Set debugging if necessary.
if config.ENVIRONMENT == config.ConfigurationConstants.DEVELOPMENT:
    app.debug = True

# Set JSON schemas
app.config['JSONSCHEMA_DIR'] = os.path.join(app.root_path, 'DTO/schemas')

# Set request level validators.
hook_validators(app)
Exemplo n.º 26
0
from flask import Flask, request, render_template
from flask.ext.api import FlaskAPI, status
from flask.ext.cors import CORS


#when we have secret keys and such turn this back on
import config

app = FlaskAPI(__name__)
app.config['SECRET_KEY'] = 'super-secret'
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
# will pull config options from config.py
#app.config.from_object(config)
Exemplo n.º 27
0
from flask import request, url_for
from flask.ext.api import FlaskAPI, status, exceptions
from flask import abort
from Crypto.Cipher import AES
from Crypto.Hash import SHA512
from Crypto.PublicKey import RSA
import requests
import json
from keys import *
from Crypto import Random

app = FlaskAPI(__name__)

@app.route("/start", methods=["POST"])

def start():
	if not request.json:
		abort(400)

	if not request.json.has_key('pi') and request.json.has_key('authrequest'):
		return 'error'

	if request.json['authrequest'] != 'hi this guy wants to transact':
		return 'error'

	return {'authresponse': 'cool, here is my certificate', 'bankcertificate': 'hello'}


@app.route("/password", methods=["POST"])
def password():
	if not request.json:
Exemplo n.º 28
0
from flask.ext.api import FlaskAPI
import os
import boto
import boto.s3.connection
access_key = os.environ['AWS_ACCESS_KEY']
secret_key = os.environ['AWS_SECRET_KEY']

conn = boto.connect_s3(
        aws_access_key_id = access_key,
        aws_secret_access_key = secret_key,
        #is_secure=False,               # uncomment if you are not using ssl
        calling_format = boto.s3.connection.OrdinaryCallingFormat(),
        )


app = FlaskAPI(__name__)



@app.route('/get_job/<id>')
def example():
    return {'hello': 'world'}

app.run(host=os.environ['HOST'], post=int(os.environ['PORT']), debug=True)
Exemplo n.º 29
0
#!/usr/bin/python
#query = 'Fist Fight'
#print(youtubeSearch(query))

from flask.ext.api import FlaskAPI
from flask import jsonify, request
from ytsearch import youtubeSearch


#initialize server
app = FlaskAPI(__name__)


@app.route('/')
def index():
    all_args = request.args.lists()
    query = request.args['q']
    video = youtubeSearch(query)
    return jsonify(video)

app.run('0.0.0.0', 5000)
Exemplo n.º 30
0
from flask.ext.api.renderers import HTMLRenderer
from flask.ext.api.exceptions import APIException
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager, login_user, logout_user, current_user, login_required
from flask.ext.wtf import Form

from wtforms import TextField, BooleanField
from wtforms.validators import Required
from sqlalchemy import Column, Integer, String, DateTime, Boolean, desc, ForeignKey
from unipath import Path
import bleach
import filters

TEMPLATE_DIR = Path(__file__).ancestor(1).child("templates")

app = FlaskAPI(__name__, template_folder=TEMPLATE_DIR)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
app.config['SECRET_KEY'] = 'you-will-never-guess'
db = SQLAlchemy(app)

lm = LoginManager()
lm.init_app(app)
lm.login_view = 'login'

filters.init_app(app)


class LoginForm(Form):
    username = TextField('username', validators = [Required()])

Exemplo n.º 31
0
from flask.ext.api import FlaskAPI
import couchdb

server = couchdb.Server()

update = False

try:
    db = server['peleton-db']
except:
    db = server.create('peleton-db')
    update = True

if update:
    db.update([{"_id": "A", "list": [2, 3, 8], "idx": 0}, {"_id": "B", "list": [4, 5, 6], "idx": 0}])
    db.update([{"_id": "merge"}])

app = FlaskAPI(__name__)

from app import routes

from routes import quiz

app.register_blueprint(quiz)
Exemplo n.º 32
0
from sources import Sources
from mining_job import MiningJob
from score import Score
from webhook import Webhook
import unicodedata
import os
from company_db import *
from jigsaw import Jigsaw
import bugsnag
from bugsnag.flask import handle_exceptions

from rq import Queue
from worker import conn
q = Queue(connection=conn)

app = FlaskAPI(__name__)
bugsnag.configure(
  api_key = "2556d33391f9accc8ea79325cd78ab62",
)

handle_exceptions(app)
  
@app.route('/v1/jigsaw_search', methods=['GET','OPTIONS','POST'])
@crossdomain(origin='*')
def jigsaw_search():
    company_name = request.args['company_name']
    q.enqueue(Sources()._jigsaw_search, company_name)
    #Sources()._jigsaw_search(company_name)
    return {'started': True}

@app.route('/v1/companies/streaming', methods=['GET','OPTIONS','POST'])
Exemplo n.º 33
0
from flask.ext.api import FlaskAPI
from flask import request, current_app, abort
from functools import wraps
import csv

app = FlaskAPI(__name__)
app.config.from_object("settings")


def token_auth(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if request.headers.get("X-API-TOKEN", None) != current_app.config["API_TOKEN"]:
            abort(403)
        return f(*args, **kwargs)

    return decorated_function


def toUTF(text):
    return text.encode("utf-8")


@app.route("/predict", methods=["POST"])
@token_auth
def predict():
    from engines import content_engine

    item = request.data.get("item")
    realID = item
    # if item == -1, means prediction for the last row.
Exemplo n.º 34
0
from flask.ext.api import FlaskAPI

app = FlaskAPI(__name__)

@app.route('/')
def hello_world():
    return {'hello': 'world'}

if __name__ == "__main__":
    app.run(debug=True, port=3000, host='0.0.0.0')
Exemplo n.º 35
0
from flask.ext.api import FlaskAPI
import os
from flask import request
from werkzeug import secure_filename
import subprocess
import json
import requests

app = FlaskAPI(__name__)
UPLOAD_FOLDER = '/home/miguel/'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


@app.route('/send-image', methods=['POST', 'GET'])
def process_image():
    print "Processing image!"
    if request.method == 'POST':
        file = request.files['file']
        if file:
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            print "imagen guardada con nombre {}".format(filename)
            # imagen = open(filename, 'rb')
            command = "alpr /home/miguel/{} -n 1 -j".format(filename)
            process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
            print "comando ejecutado"
            output = json.loads(process.communicate()[0])
            print "Despues del output"
            true_plate = output['results'][0]['plate']
            print true_plate
            response = requests.get('http://greenheadapi.azurewebsites.net/api/place/getzone/{}'.format(true_plate))
Exemplo n.º 36
0
from ConfigFiles import *

######################################################################################################
# Global Variables.
######################################################################################################

VM_IMAGES = {} # Stores all the VM images given as input.
PM_ADDRS = {}  # Stores the IPs of all available Physical Machines
VM_RUNNING = {} # Stores all the running VMs.

######################################################################################################
# Flask Application Initializer.
######################################################################################################

app = FlaskAPI(__name__)

######################################################################################################
# Homepage.
######################################################################################################

@app.route("/", methods=['GET'])
def homepage():
    homeString = {}
    homeString["Cloud Orchestration Layer"] = [
        {
            "Author" : "Mohit Jain", 
            "ver" : "1.0", 
            "Options" : 
                {
                    "List VM Types" : "http://localhost:5000/vm/types",
Exemplo n.º 37
0
from bs4 import BeautifulSoup
from flask import json, Response
from flask.ext.api import FlaskAPI
import requests

app = FlaskAPI(__name__)

@app.route('/feeds')
def feeds_list():
    feeds = []
    page = requests.get('http://www.cresol.com.br/site/rss/news2.php?l=20').text
    soup = BeautifulSoup(page, "html.parser")

    for item in soup.find_all('item'):
        feed = {}
        feed['id'] = item.id.string
        feed['title'] = item.title.string
        feed['content'] = str(item.content).replace('<content>', '').replace('</content>', '')
        feed['description'] = item.description.string
        feed['image'] = item.image.string
        feed['link'] = item.link.string
        feed['pubDate'] = item.pubdate.string
        if item.video is not None:
            feed['video'] = item.video.string
        feeds.append(feed)

    return Response(json.dumps(feeds),  mimetype='application/json')

if __name__ == '__main__':
    #app.run(debug=True)
    app.run(host='0.0.0.0')
Exemplo n.º 38
0
from flask import request, url_for
from flask.ext.api import FlaskAPI, status, exceptions
import handlers as h
import tournament as tour
import rq
import os
from database import R
app = FlaskAPI(__name__)

# define api:
#    tournament
#       teams
#       session
#           add, remove, stage next games, get ranking
#           teams
#               add, get
#               team_id
#            games
#               add game
#               game
#                   score, teams
#

#   Teams
#        team
#           members
#           id
#           name
#   Games
#       game
#           teams
Exemplo n.º 39
0
from flask import request, url_for, render_template, escape, Markup
from flask.ext.api import FlaskAPI, status, exceptions
from flask.ext.api.decorators import set_renderers
from flask.ext.api.renderers import HTMLRenderer
from flask.ext.api.exceptions import APIException
from flask.ext.sqlalchemy import SQLAlchemy

from sqlalchemy import Column, Integer, String, DateTime, Boolean, desc
from unipath import Path

import bleach
import tweepy

TEMPLATE_DIR = Path(__file__).ancestor(1).child("templates")

app = FlaskAPI(__name__, template_folder=TEMPLATE_DIR)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
db = SQLAlchemy(app)

CONSUMER_KEY = os.environ['CONSUMER_KEY']
CONSUMER_SECRET = os.environ['CONSUMER_SECRET']
ACCESS_KEY  = os.environ['ACCESS_KEY']
ACCESS_SECRET = os.environ['ACCESS_SECRET']
TWITTER_USER = os.environ['TWITTER_USER']

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)


class Note(db.Model):
Exemplo n.º 40
0
from flask.ext.api import FlaskAPI  # importa la clase de flaskapi
from conf.config import LocalConfig  # importa la configuracion la clase que se le da
from modules.authentication import authentication, auth
from modules.authors import authors
from modules.enera import enera
from modules import mongo
import os
from flask import Flask, url_for
from flask import Flask, render_template, url_for
from werkzeug.routing import Map, Rule, NotFound, RequestRedirect, BaseConverter
from flask.ext.script import Manager
from flask import Flask, jsonify

application = FlaskAPI(__name__)
# manager = Manager(application)

if 'Hacker' in os.environ:
    application.config.from_object(DevelopConfig)
else:
    application.config.from_object(LocalConfig)

# Blueprint
application.register_blueprint(authentication, url_prefix='/authentication')
application.register_blueprint(authors, url_prefix='/authors')
application.register_blueprint(enera, url_prefix='/enera')

# we are going to start mongo whit this application
mongo.init_app(application)


@application.route('/')
Exemplo n.º 41
0
from flask import request, url_for
from flask.ext.api import FlaskAPI, status, exceptions

app = FlaskAPI(__name__)

notes = {
	0: 'do the shoppping',
	1: 'build the codez',
	2: 'paint the door',
}

def note_repr(key):
	return {
		'url': request.host_url.rstrip('/') + url_for('notes_detail', key=key),
		'text': notes[key]
	}

@app.route("/", methods=['GET', 'POST'])
def notes_list():
	"""
	List or create notes.
	"""
	if request.method == 'POST':
		note = str(request.data.get('text', ''))
		idx = max(notes.keys()) + 1
		notes[idx] = note
		return note_repr(idx), status.HTTP_201_CREATED

	# request.method == 'GET'
	return [note_repr(idx) for idx in sorted(notes.keys())]
Exemplo n.º 42
0
import arrow

from flask import request
from flask.ext.api import FlaskAPI
from flask.ext.api import status

from schematics.exceptions import ValidationError

from nymms.state import sdb_state
from nymms.suppress import sdb_suppress
from nymms.config import config
from nymms import schemas

logger = logging.getLogger(__name__)

nymms_api = FlaskAPI(__name__)

DEFAULT_RESULT_LIMIT = 1000
DEFAULT_SUPPRESSION_LIMIT = 1000
DEFAULT_STATE_LIMIT = 1000


@nymms_api.route('/state', methods=['GET'])
def state():
    """
    List current states.

    Query Params:
    - limit (default 1000)
    """
    region = config.settings['region']