class ApiTestCase(unittest.TestCase):
    def setUp(self):
        app = Flask(__name__)
        self.api = Api(app)
        self.api.add_resource(ParseResource, '/parse')
        self.api.add_resource(UserResource, '/users/<int:user_id>')
        self.app = app.test_client()
        self.context = app.test_request_context()

    def test_get_spec_object(self):
        # Retrieve spec object
        with self.context:
            spec = self.api.get_swagger_doc()
            self.assertTrue('info' in spec)
            self.assertTrue('paths' in spec)
            self.assertTrue('definitions' in spec)
            self.assertEqual(spec['swagger'], '2.0')

    def test_get_spec(self):
        # Retrieve spec
        r = self.app.get('/api/swagger.json')
        self.assertEqual(r.status_code, 200)

        data = json.loads(r.data.decode('utf-8'))
        self.assertTrue('info' in data)
        self.assertTrue('paths' in data)
        self.assertTrue('definitions' in data)
        self.assertEqual(data['swagger'], '2.0')

    def test_parse_query_parameters(self):
        r = self.app.get('/parse?str=Test' +
                         '&date=2016-01-01' +
                         '&datetime=2016-01-01T12:00:00%2B00:00' +
                         '&bool=False' +
                         '&int=123' +
                         '&float=1.23')

        self.assertEqual(r.status_code, 200)

        data = json.loads(r.data.decode('utf-8'))
        self.assertEqual(data['str'], 'Test')
        self.assertEqual(data['date'], '2016-01-01T00:00:00')
        self.assertEqual(data['datetime'], '2016-01-01T12:00:00+00:00')
        self.assertEqual(data['bool'], False)
        self.assertEqual(data['int'], 123)
        self.assertEqual(data['float'], 1.23)

    def test_get_user(self):
        # Retrieve user
        r = self.app.get('/users/1?name=test')
        self.assertEqual(r.status_code, 200)

        data = json.loads(r.data.decode('utf-8'))
        self.assertEqual(data['id'], 1)
        self.assertEqual(data['name'], 'test')
 def setUp(self):
     app = Flask(__name__)
     self.api = Api(app)
     self.api.add_resource(ParseResource, '/parse')
     self.api.add_resource(UserResource, '/users/<int:user_id>')
     self.app = app.test_client()
     self.context = app.test_request_context()
import uuid
from functools import wraps

from flask import Flask, g, request, send_from_directory, abort, request_started
from flask_cors import CORS
from flask_restful import Resource, reqparse
from flask_restful_swagger_2 import Api, swagger, Schema

from neo4j.v1 import GraphDatabase, basic_auth, ResultError

from . import config


app = Flask(__name__)
app.config['SECRET_KEY'] = 'super secret guy'
api = Api(app, title='Neo4j Movie Demo API', api_version='0.0.10')
CORS(app)


driver = GraphDatabase.driver('bolt://localhost', auth=basic_auth(config.DATABASE_USERNAME, str(config.DATABASE_PASSWORD)))


def get_db():
    if not hasattr(g, 'neo4j_db'):
        g.neo4j_db = driver.session()
    return g.neo4j_db


@app.teardown_appcontext
def close_db(error):
    if hasattr(g, 'neo4j_db'):
Example #4
0
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
# pylint: disable=unused-argument
def auth(*args):
    """
    Space for your fancy authentication. Return True if access is granted,
    otherwise False
    """
    return True


swagger.auth = auth

API_URL = '/specs'  # Our API url (can of course be a local resource)

# api = Api(app, api_version='0.1', api_spec_url=API_URL)
api = Api(app, api_version='0.1', api_spec_url=API_URL)

DEFAULT_HOST = os.getenv('DEFAULT_LISTENER_HOST', 'localhost')
DEFAULT_PORT = int(os.environ.get('DEFAULT_LISTENER_PORT', '5000'))
DEBUG = os.environ.get('DEBUG', 'False') in (
    "yes", "y", "true", "True", "t", "1"
)

SWAGGER_URL = '/api/docs'  # URL for exposing Swagger UI (without trailing '/')

# Call factory function to create our blueprint
swaggerui_blueprint = get_swaggerui_blueprint(
    # Swagger UI static files will be mapped to '{SWAGGER_URL}/assets/'
    SWAGGER_URL,
    API_URL + ".json",
    # config={ # Swagger UI config overrides
# set FLASK_DEBUG=1
# python -m flask run

# NOTE: Run with PYTHONPATH=. python example/app.py

from flask import Flask
# A Flask extension for handling Cross Origin Resource Sharing (CORS), making cross-origin AJAX possible.
from flask_cors import CORS
# Extract swagger specs from your flask-restful project.
from flask_restful_swagger_2 import Api, swagger

from fl_rest_api_views import UserResource, UserItemResource, GroupResource

app = Flask(__name__)
CORS(app)
api = Api(app, api_version='0.1')


def auth(api_key, endpoint, method):
    # Space for your fancy authentication. Return True if access is granted, otherwise False
    return True


swagger.auth = auth

api.add_resource(UserResource, '/api/users')
api.add_resource(UserItemResource, '/api/users/<int:user_id>')
api.add_resource(GroupResource, '/api/groups/')


@app.route('/')
Example #6
0
from flask_cors import CORS
from flask import Flask
from flask_restful_swagger_2 import Api

from resources.login.login import Login
from resources.sender.sender import Sender
from resources.register.register import Register
from resources.verify.verify import Verify
from resources.puzzle.puzzle import Puzzle
from resources.balance.balance import Balance
from utilities.logger import Logger

logger = Logger(__name__)

app = Flask(__name__)

CORS(app)
api = Api(app, api_version='0.1')

api.add_resource(Login, "/login")
api.add_resource(Register, "/register")
api.add_resource(Puzzle, "/puzzle")
api.add_resource(Verify, "/verify/<string:user>/<int:pin>")
api.add_resource(Sender, "/send")
api.add_resource(Balance, "/user/balance")

if __name__ == '__main__':
    logger.info('Starting API')
    app.run(host="0.0.0.0", port=5000)
Example #7
0
from flask import Flask
from flask_restful_swagger_2 import Resource, Api
from flask_cors import CORS
from endpoints import root, racks, rack, racksCloseBy
from datastore import Store

app = Flask(__name__)
CORS(app)
api = Api(app)

api.add_resource(root, '/<name>')
api.add_resource(racks, '/racks')
api.add_resource(rack, '/rack/<rackId>')
api.add_resource(racksCloseBy, '/racksCloseBy/<latitude>/<longitude>')

if __name__ == '__main__':
    app.store = Store('supportvelosigs.csv')
    app.run(debug=True, host='0.0.0.0')
Example #8
0
# coding: utf-8
from flask import Flask
from flask_restful_swagger_2 import Api
# The line below needs to be uncommented when debugging
from flask_cors import CORS
from routes import setup_routes

app = Flask(__name__)

api = Api(app, api_version='1.0', api_spec_url='/api/specs')
setup_routes(api)

from data_access.data_access_base import DataAccessBase
DataAccessBase.initialize()

CORS(app)

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True, port=5234)
Example #9
0
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
# pylint: disable=unused-argument
def auth(*args):
    """
    Space for your fancy authentication. Return True if access is granted,
    otherwise False
    """
    return True


swagger.auth = auth

API_URL = '/specs'  # Our API url (can of course be a local resource)

# api = Api(app, api_version='0.1', api_spec_url=API_URL)
api = Api(app, api_version='0.1', api_spec_url=API_URL)

DEFAULT_HOST = os.getenv('DEFAULT_LISTENER_HOST', 'localhost')
DEFAULT_PORT = int(os.environ.get('DEFAULT_LISTENER_PORT', '5000'))
DEBUG = os.environ.get('DEBUG', 'False') in (
    "yes", "y", "true", "True", "t", "1"
)

SWAGGER_URL = '/api/docs'  # URL for exposing Swagger UI (without trailing '/')

# Call factory function to create our blueprint
swaggerui_blueprint = get_swaggerui_blueprint(
    # Swagger UI static files will be mapped to '{SWAGGER_URL}/assets/'
    SWAGGER_URL,
    API_URL + ".json",
    # config={ # Swagger UI config overrides
Example #10
0
from flask_cors import CORS
from flask_restful_swagger_2 import Api

__license__ = "Apache License, Version 2.0"
__author__     = "Soeren Gebbert"
__copyright__  = "Copyright 2018, Soeren Gebbert"
__maintainer__ = "Soeren Gebbert"
__email__      = "*****@*****.**"

flask_app = Flask(__name__)
CORS(flask_app)

flask_api = Api(flask_app,
                api_version='0.1pre-alpha',
                api_spec_url='/api/v0/swagger',
                title="OpenEO UDF API",
                description="The OpenEO UDF API specification",
                schemes=['http', 'https'],
                consumes=['application/json'])

flask_api._swagger_object["securityDefinitions"] = {"basicAuth": {"type": "basic"}}
flask_api._swagger_object["security"] = [{"basicAuth": []}]
flask_api._swagger_object["tags"] = [
    {
        "name": "UDF",
        "description": "Interfacing to execute user-defined functions at the provided data."
    }
]

flask_api._swagger_object["responses"] = {
    "auth_required": {
import logging
import os

from flask import Flask
from flask_cors import CORS
from flask_restful_swagger_2 import Api, swagger

from common.correctSkewness import CorrectSkewnessApi
from common.correctSkewnessBatch import CorrectSkewnessBatchApi

ENV_VAR_FLASK_DEBUG_MODE = 'FLASK_DEBUG_MODE'

app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
api = Api(app, api_version='0.1', api_spec_url='/api/swagger')


# This code gets run in the beginning of the first request
# Use this function to initialize services etc. if necessary.
@app.before_first_request
def initialize():
    logging.getLogger().setLevel(logging.DEBUG)


api.add_resource(CorrectSkewnessApi, '/api/correctSkewness')
api.add_resource(CorrectSkewnessBatchApi, '/api/correctSkewnessBatch')


@app.route('/')
def index():
Example #12
0
# local imports
from api.v1 import APP_V1, Index

##########################################################################
# BEGIN Flask Config
##########################################################################

APP = Flask(__name__)

# Limit overall size to 1 mb
APP.config['MAX_CONTENT_LENGTH'] = 1 * 1024 * 1024

API = Api(APP,
          api_version=None,
          api_spec_url='/docs/swagger',
          description='Eloqua Webhook Integration API',
          terms='Apache License',
          title='ELQ-WEBHOOK')

json.JSONEncoder(ensure_ascii=False)

##########################################################################
# END Flask Config
##########################################################################

##########################################################################
# BEGIN Blueprint Registration
##########################################################################

APP.register_blueprint(APP_V1, url_prefix='/api/v1')
Example #13
0
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
# pylint: disable=unused-argument
def auth(*args):
    """
    Space for your fancy authentication. Return True if access is granted,
    otherwise False
    """
    return True


swagger.auth = auth

API_URL = '/specs'  # Our API url (can of course be a local resource)

# api = Api(app, api_version='0.1', api_spec_url=API_URL)
api = Api(app, api_version='0.1', api_spec_url=API_URL)

DEFAULT_HOST = os.getenv('DEFAULT_LISTENER_HOST', 'localhost')
DEFAULT_PORT = int(os.environ.get('DEFAULT_LISTENER_PORT', '5000'))
DEBUG = os.environ.get('DEBUG', 'False') in (
    "yes", "y", "true", "True", "t", "1"
)

SWAGGER_URL = '/api/docs'  # URL for exposing Swagger UI (without trailing '/')

# Call factory function to create our blueprint
swaggerui_blueprint = get_swaggerui_blueprint(
    # Swagger UI static files will be mapped to '{SWAGGER_URL}/assets/'
    SWAGGER_URL,
    API_URL + ".json",
    # config={ # Swagger UI config overrides
Example #14
0
from flask import Blueprint

from flask_restful_swagger_2 import Api

from .home.routes import HomeAdmResource, HomeResource, HomeTeacherResource
from .auth.routes import AuthResource
from .registration.routes import RegistrationUser

bp = Blueprint("api", __name__, static_folder='static', url_prefix="/v1")
api = Api(bp)


def init_app(app):
    # Home
    api.add_resource(HomeAdmResource, "/home/adm/")
    api.add_resource(HomeTeacherResource, "/home/teacher/")
    api.add_resource(HomeResource, "/home/")

    # Auth
    api.add_resource(AuthResource, "/token/")

    # Cadastro de usuario
    api.add_resource(RegistrationUser, "/registration/")

    app.register_blueprint(bp)
 def setUp(self):
     app = Flask(__name__)
     api = Api(app)
     api.add_resource(TestResource, '/users/<int:user_id>')
     self.app = app.test_client()
Example #16
0
monkey_patch.patch_all()

from flask import Flask, jsonify
from flask_restful_swagger_2 import Api
from flask_swagger_ui import get_swaggerui_blueprint
from flask_cors import CORS
from mongoengine import connect
from appname import auth, error, config, \
        kakao, facebook, apitools, example-aws-s3, example-aws-ses, example-aws-iot
import os
from flask_restful.reqparse import Argument

app = Flask(__name__)
# cors ploblem
cors = CORS(app, supports_credentials=True)
api = Api(app, api_version='0.1', api_spec_url='/api/swagger')

# set app.config
app.config.from_object(config.DefaultConfig)

if 'CI' in os.environ:
    app.config.from_object(config.CiConfig)
elif 'TEST' in os.environ:
    app.config.from_object(config.TestConfig)
elif 'DEV_SERVER' in os.environ:
    app.config.from_object(config.DevServerConfig)

# set mongoDB
if 'MONGO_USERNAME' in app.config:
    connect(
        db=app.config['MONGO_DBNAME'],
Example #17
0
from lib.utils import json_dump, download_video_from_youtube
from lib.utils import get_node_ip
from lib.utils import validate_url
from lib.utils import url_fails
from lib.utils import get_video_duration
from dateutil import parser as date_parser
from mimetypes import guess_type

from settings import settings, DEFAULTS, CONFIGURABLE_SETTINGS, auth_basic
from werkzeug.wrappers import Request


app = Flask(__name__)
CORS(app)
api = Api(app, api_version="v1", title="Screenly OSE API")

SWAGGER_URL = '/api/docs'
API_URL = 'http://*****:*****@api.representation('application/json')
def output_json(data, code, headers=None):
    response = make_response(json_dump(data), code)
    response.headers.extend(headers or {})
    return response
from flask import Flask
from flask_restful_swagger_2 import Api
from flask_cors import CORS
from lib import crawlerTask, resourceLoader
from resources.crawlerResource import Crawler, CrawlerJob, CrawlerJobs
from resources.aggregationResource import Aggregation
from resources.resourceConfigResource import ResourceConfig
import configuration
import os

app = Flask(__name__)
CORS(app)  # this will allow cross-origin requests
api = Api(
    app,
    add_api_spec_resource=True,
    api_version='0.0',
    api_spec_url='/api/swagger')  # Wrap the Api and add /api/swagger endpoint

api.add_resource(Crawler, '/crawler', endpoint='crawler')
api.add_resource(CrawlerJobs, '/crawler/jobs', endpoint='jobs')
api.add_resource(CrawlerJob, '/crawler/jobs/<crawler_id>', endpoint='job')
api.add_resource(Aggregation,
                 '/aggregation/<crawler_id>',
                 endpoint='aggregation')
api.add_resource(ResourceConfig,
                 '/resources_config',
                 endpoint='resources_list')


@app.before_first_request
eventlet.monkey_patch()
import json
from flask import Flask
from flask_restful_swagger_2 import Api
from flask_cors import CORS
from resources.filtertaskResource import FilterJobs, FilterJob
from resources.aggregationtaskResource import AggregationTasks, AggregationTask
import configuration
import os
from rdb.rdb import create_base_db

app = Flask(__name__)
CORS(app)  # this will allow cross-origin requests
api = Api(
    app,
    add_api_spec_resource=True,
    api_version='0.0',
    api_spec_url='/api/swagger')  # Wrap the Api and add /api/swagger endpoint

api.add_resource(FilterJobs, '/filterTasks', endpoint='filterTasks')
api.add_resource(FilterJob, '/filterTasks/<task_id>', endpoint='filterTask')
api.add_resource(AggregationTasks,
                 '/aggregationTasks',
                 endpoint='aggregationTasks')
api.add_resource(AggregationTask,
                 '/aggregationTasks/<task_id>',
                 endpoint='aggregationTask')

create_base_db()

if __name__ == '__main__':
Example #20
0
from controller.event_controller import TextController, StickerController, ImageUrlController, ImageFileController

app = Flask(__name__)
CORS(app, resources={r"*": {"origins": "*", "supports_credentials": True}})

DOMAIN = os.environ.get('DOMAIN_NAME')
PORT = os.environ.get('PORT')


def is_local():
    return True if os.environ.get('LOCAL') else False


api = Api(app,
          host=f'localhost:{PORT}' if is_local() else DOMAIN,
          schemes=['http' if is_local() else 'https'],
          base_path='/',
          api_version='0.0.1',
          api_spec_url='/api/swagger')

api.add_resource(RootController, "/")
api.add_resource(CallbackController, "/callback")
api.add_resource(LinkController, "/notify/link")
api.add_resource(CodeChangeController, "/notify/change")
api.add_resource(RevokeTokenController, "/notify/revoke")
api.add_resource(TextController, "/notify/send")
api.add_resource(StickerController, "/notify/sticker")
api.add_resource(ImageUrlController, "/notify/url")
api.add_resource(ImageFileController, "/notify/file")

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=PORT, debug=True)
Example #21
0
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
# pylint: disable=unused-argument
def auth(*args):
    """
    Space for your fancy authentication. Return True if access is granted,
    otherwise False
    """
    return True


swagger.auth = auth

API_URL = '/specs'  # Our API url (can of course be a local resource)

# api = Api(app, api_version='0.1', api_spec_url=API_URL)
api = Api(app, api_version='0.1', api_spec_url=API_URL)

DEFAULT_HOST = os.getenv('DEFAULT_LISTENER_HOST', 'localhost')
DEFAULT_PORT = int(os.environ.get('DEFAULT_LISTENER_PORT', '5000'))
DEBUG = os.environ.get('DEBUG',
                       'False') in ("yes", "y", "true", "True", "t", "1")

SWAGGER_URL = '/api/docs'  # URL for exposing Swagger UI (without trailing '/')

# Call factory function to create our blueprint
swaggerui_blueprint = get_swaggerui_blueprint(
    # Swagger UI static files will be mapped to '{SWAGGER_URL}/assets/'
    SWAGGER_URL,
    API_URL + ".json",
    # config={ # Swagger UI config overrides
    # 'supportedSubmitMethods': ['get']
Example #22
0
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
# pylint: disable=unused-argument
def auth(*args):
    """
    Space for your fancy authentication. Return True if access is granted,
    otherwise False
    """
    return True


swagger.auth = auth

API_URL = '/specs'  # Our API url (can of course be a local resource)

# api = Api(app, api_version='0.1', api_spec_url=API_URL)
api = Api(app, api_version='0.1', api_spec_url=API_URL)

DEFAULT_HOST = os.getenv('DEFAULT_LISTENER_HOST', 'localhost')
DEFAULT_PORT = int(os.environ.get('DEFAULT_LISTENER_PORT', '5000'))
DEBUG = os.environ.get('DEBUG', 'False') in (
    "yes", "y", "true", "True", "t", "1"
)

SWAGGER_URL = '/api/docs'  # URL for exposing Swagger UI (without trailing '/')

# Call factory function to create our blueprint
swaggerui_blueprint = get_swaggerui_blueprint(
    # Swagger UI static files will be mapped to '{SWAGGER_URL}/assets/'
    SWAGGER_URL,
    API_URL + ".json",
    # config={ # Swagger UI config overrides
Example #23
0
__copyright__ = "Copyright 2016-2018, Sören Gebbert and mundialis GmbH & Co. KG"
__maintainer__ = "Sören Gebbert"
__email__ = "*****@*****.**"

API_VERSION = "v1"

# This is the URL prefix that must be used in the tests
URL_PREFIX = "/api/%s" % API_VERSION

flask_app = Flask(__name__)
CORS(flask_app)

flask_api = Api(flask_app,
                prefix=URL_PREFIX,
                api_version=API_VERSION,
                api_spec_url='/swagger',
                title=actinia_string,
                description=actinia_description,
                schemes=['https'],
                consumes=['application/gml+xml', 'application/json'])

# Set the security definition in an unconventional way
flask_api._swagger_object["securityDefinitions"] = {
    "basicAuth": {
        "type": "basic"
    }
}
flask_api._swagger_object["security"] = [{"basicAuth": []}]

auth = HTTPBasicAuth()
Example #24
0
# post new search
# get all queue
# update queue item
# refresh individual queue item

from flask_restful_swagger_2 import Api
from flask import Blueprint
from flask_restful.utils import cors
from os.path import dirname, abspath, split

from .search.resources import Search, SearchList
from .download.resources import Download, DownloadList

# from resources.downloadList import DownloadList

raw_name = split(dirname(abspath(__file__)))[-1]
name = raw_name.replace('_', ' ')
api_bp = Blueprint(name, __name__)
api = Api(api_bp, api_spec_url='/spec/%s' % name)

api.decorators = [
    cors.crossdomain(origin='*',
                     headers=['accept', 'Content-Type'],
                     methods=['HEAD', 'OPTIONS', 'GET', 'POST', 'DELETE'])
]

api.add_resource(Search, '/search/<int:search_id>')
api.add_resource(SearchList, '/search')
api.add_resource(Download, '/queue/<int:search_id>')
api.add_resource(DownloadList, '/queue')
from flask_cors import CORS
from resources.annotationTaskResource import AnnotationTaskResource, AnnotationTaskListResource, UserAnnotationTaskListResource
from resources.entryResource import AnnotationTaskEntryListResource, EntriesForAnnotatorResource
from resources.scaleEntryResource import AnnotationTaskScaleEntryListResource, AnnotationTaskScaleEntry
from resources.annotatorResource import AnnotationTaskAnnotatorListResource, AnnotatorResource
from resources.resultResource import AnnotationResultListResource, AnnotationTaskResultListResource, AnnotatorResultListResource
import json
import logging
import logging.config
logging.config.dictConfig(json.load(open("logging_config.json", "r")))

app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
api = Api(
    app,
    add_api_spec_resource=True,
    api_version='0.0',
    api_spec_url='/api/swagger')  # Wrap the Api and add /api/swagger endpoint

connect_to_db(app)
create_all()

CORS(app)

api.add_resource(AnnotationTaskResource,
                 '/annotation_tasks/<int:task_id>',
                 endpoint='annotation_task')
api.add_resource(AnnotationTaskListResource,
                 '/annotation_tasks',
                 endpoint='annotation_tasks')
api.add_resource(UserAnnotationTaskListResource,
Example #26
0
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
# pylint: disable=unused-argument
def auth(*args):
    """
    Space for your fancy authentication. Return True if access is granted,
    otherwise False
    """
    return True


swagger.auth = auth

API_URL = '/specs'  # Our API url (can of course be a local resource)

# api = Api(app, api_version='0.1', api_spec_url=API_URL)
api = Api(app, api_version='0.1', api_spec_url=API_URL)

DEFAULT_HOST = os.getenv('DEFAULT_LISTENER_HOST', 'localhost')
DEFAULT_PORT = int(os.environ.get('DEFAULT_LISTENER_PORT', '5000'))
DEBUG = os.environ.get('DEBUG',
                       'False') in ("yes", "y", "true", "True", "t", "1")

SWAGGER_URL = '/api/docs'  # URL for exposing Swagger UI (without trailing '/')

# Call factory function to create our blueprint
swaggerui_blueprint = get_swaggerui_blueprint(
    # Swagger UI static files will be mapped to '{SWAGGER_URL}/assets/'
    SWAGGER_URL,
    API_URL + ".json",
    # config={ # Swagger UI config overrides
    # 'supportedSubmitMethods': ['get']
Example #27
0
from lib import backup_helper
from lib import db
from lib import diagnostics
from lib import queries

from lib.utils import get_node_ip
from lib.utils import get_video_duration
from lib.utils import download_video_from_youtube, json_dump
from lib.utils import url_fails
from lib.utils import validate_url

from settings import auth_basic, CONFIGURABLE_SETTINGS, DEFAULTS, LISTEN, PORT, settings, ZmqPublisher

app = Flask(__name__)
CORS(app)
api = Api(app, api_version="v1", title="Screenly OSE API")

################################
# Utilities
################################


@api.representation('application/json')
def output_json(data, code, headers=None):
    response = make_response(json_dump(data), code)
    response.headers.extend(headers or {})
    return response


def api_error(error):
    return make_response(json_dump({'error': error}), 500)
Example #28
0
from flask import Flask
from flask_restful_swagger_2 import Api
from flask_cors import CORS
from api.hello import Hello

app = Flask(__name__)

CORS(app)
api = Api(app, title='Blockchain', api_version='1.0.0')
api.add_resource(Hello, '/')
Example #29
0
from flask_restful import Resource, reqparse
from flask_restful_swagger_2 import Api, swagger, Schema
from flask_json import FlaskJSON, json_response

from neo4j import GraphDatabase, basic_auth
from neo4j.exceptions import Neo4jError
import neo4j.time

load_dotenv(find_dotenv())

app = Flask(__name__)

CORS(app)
FlaskJSON(app)

api = Api(app, title='Neo4j Movie Demo API', api_version='0.0.10')


@api.representation('application/json')
def output_json(data, code, headers=None):
    return json_response(data_=data, headers_=headers, status_=code)


def env(key, default=None, required=True):
    """
    Retrieves environment variables and returns Python natives. The (optional)
    default will be returned if the environment variable does not exist.
    """
    try:
        value = os.environ[key]
        return ast.literal_eval(value)
Example #30
0
from flask_cors import CORS
from flask import Flask
from flask_restful_swagger_2 import Api

from resources.login.login import Login
from resources.match.products import Match
from resources.products.products import Products, ProductsLikes
from resources.users import Users

app = Flask(__name__)
CORS(app)
api = Api(app, api_version='0.1')

api.add_resource(ProductsLikes, "/products/<int:product_id>/<int:like>")
api.add_resource(Products, "/products")
api.add_resource(Match, "/match")
api.add_resource(Users, "/users")
api.add_resource(Login, "/login")

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8080)
Example #31
0
from lib.utils import get_active_connections, remove_connection
from lib.utils import get_node_ip, get_node_mac_address
from lib.utils import get_video_duration
from lib.utils import download_video_from_youtube, json_dump
from lib.utils import url_fails
from lib.utils import validate_url
from lib.utils import is_balena_app, is_demo_node

from settings import auth_basic, CONFIGURABLE_SETTINGS, DEFAULTS, LISTEN, PORT, settings, ZmqPublisher, ZmqCollector

HOME = getenv('HOME', '/home/pi')

app = Flask(__name__)
CORS(app)
api = Api(app, api_version="v1", title="Screenly OSE API")


################################
# Utilities
################################

@api.representation('application/json')
def output_json(data, code, headers=None):
    response = make_response(json_dump(data), code)
    response.headers.extend(headers or {})
    return response


def api_error(error):
    return make_response(json_dump({'error': error}), 500)
Example #32
0
from flask import Flask
from flask_cors import CORS
from flask_restful_swagger_2 import swagger, Api, Resource, request
# Swagger라는 멋진 API 관리 툴이 있는데, flask-restful-swagger 패키지를 이용해서 자동화 가능하다
# from flask_restful import Api 대신 위의 import 방식을 사용하자

app = Flask(__name__)
CORS(app)
api = Api(app, api_version='1.0')


class Sample(Resource):
    @swagger.doc({
        'tags': ['user'],
        # 태그를 기준으로 API 정리할 수 있다
        'description':
        'Returns hello world!',
        # API description
        'parameters': [
            # 파라미터 리스트
            {
                'name': 'id',
                # 파라미터의 key name
                'description': 'Identifier',
                # 파라미터 description
                'in': 'path',
                # 파라미터가 들어갈 곳
                # must be path, query, header, body or formData
                'type': 'int'
                # 타입
            },