Exemplo n.º 1
0
def test_parser():
    flask_app = Flask(__name__)
    api = Api(flask_app)
    api.add_resource(EntityAddResource, '/entities/')
    app = flask_app.test_client()
    context = flask_app.test_request_context()
    yield {"app": app, "api": api, "context": context}
 def __init__(self, sdn_controller, port=9998, host='0.0.0.0'):
     self.sdn_controller = sdn_controller
     self.port = port
     self.host = host
     self.thread = threading.Thread(target=self.flask_thread)
     self.http_server = Flask('sdn_controller_api_server')
     self.api = Api(self.http_server,
                    title='TPS Controller API',
                    description='APIs for some basic P4 CRUD operations')
     self.server_start = None
Exemplo n.º 3
0
def test_app():
    flask_app = Flask(__name__)
    api = Api(flask_app)
    api.add_resource(ParseResource, '/parse')
    api.add_resource(UserResource, '/users/<int:user_id>')
    app = flask_app.test_client()
    context = flask_app.test_request_context()
    yield {"app": app, "api": api, "context": context}
Exemplo n.º 4
0
def get_user_resources():
    """
    Returns user resources.
    :param app: The Flask instance
    :return: User resources
    """
    blueprint = Blueprint('user', __name__)

    api = Api(blueprint, add_api_spec_resource=False)

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

    return api
class SDNControllerServer:
    def __init__(self, sdn_controller, port=9998, host='0.0.0.0'):
        self.sdn_controller = sdn_controller
        self.port = port
        self.host = host
        self.thread = threading.Thread(target=self.flask_thread)
        self.http_server = Flask('sdn_controller_api_server')
        self.api = Api(self.http_server,
                       title='TPS Controller API',
                       description='APIs for some basic P4 CRUD operations')
        self.server_start = None

    def start(self):
        self.thread.start()
        self.api.add_resource(
            DataForward,
            '/dataForward',
            resource_class_kwargs={'sdn_controller': self.sdn_controller})
        self.api.add_resource(
            DataInspection,
            '/dataInspection',
            resource_class_kwargs={'sdn_controller': self.sdn_controller})
        self.api.add_resource(
            GwAttack,
            '/gwAttack',
            resource_class_kwargs={'sdn_controller': self.sdn_controller})
        self.api.add_resource(
            AggAttack,
            '/aggAttack',
            resource_class_kwargs={'sdn_controller': self.sdn_controller})
        self.api.add_resource(
            TelemetryReport,
            '/setupTelemRpt',
            resource_class_kwargs={'sdn_controller': self.sdn_controller})
        self.api.add_resource(
            TelemetryReportSampling,
            '/telemRptSample',
            resource_class_kwargs={'sdn_controller': self.sdn_controller})
        self.api.add_resource(
            DefaultPort,
            '/dfltPort',
            resource_class_kwargs={'sdn_controller': self.sdn_controller})
        self.api.add_resource(
            MulticastGroups,
            '/mcastPorts',
            resource_class_kwargs={'sdn_controller': self.sdn_controller})
        self.api.add_resource(Shutdown, '/shutdown')

    def stop(self):
        try:
            requests.post(
                url='http://{}:{}/shutdown'.format(self.host, self.port))
        except Exception as e:
            logger.warning('Trouble shutting down HTTP server - [%s]', e)

    def flask_thread(self):
        logger.info('Starting server on port [%s]', self.port)
        self.server_start = self.http_server.run(host=self.host,
                                                 port=self.port)
Exemplo n.º 6
0
from flask import Flask, request, g, render_template
from flask_restful import Resource, reqparse
from flask_restful_swagger_3 import Api
import os
from json import dumps
import application.endpoints as endpoints
import application.config as config
import logging

app = Flask(__name__)
api = Api(app,
          version='1',
          contact={"name": ""},
          license={"name": "Online Dienst Dokumentation"},
          api_spec_url='/api/swagger')
logging.basicConfig(level=logging.DEBUG)
api.add_resource(endpoints.RecipeList, '/api/v1/recipe/')
api.add_resource(endpoints.Images, '/api/v1/recipe/<string:id>/image')


@app.route("/")
def index():
    """serve the ui"""
    app.logger.info(f" request from {request.remote_addr}")
    return render_template("index.html")
Exemplo n.º 7
0
    }
}

# Apply the security globally to all operations
api_security = [
    # We don't JWT on all API, but just on some
    # See 'security' on @swagger.doc
    #{'BearerAuth': []}
]

# ------------------------------
# Flask initialization

app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "*"}})
api = Api(app, components=components, security=api_security)

app.config.from_pyfile('secrets.py')
emails.init(app)

# ------------------------------
# Generic error handlers


@app.errorhandler(404)
def page_not_found(e):
    return error_page(str(e)), 404


@app.errorhandler(Exception)
def handle_exception(e):
Exemplo n.º 8
0
from flask import Flask
from flask_mongoengine import MongoEngine
from flask_restful_swagger_3 import Api, get_swagger_blueprint
from flask_cors import CORS
from resources import PredictToTakeOrder, ConsultToTakeOrder

app = Flask(__name__)
CORS(app)
app.config['MONGODB_SETTINGS'] = {
    "db": "orders",
    "host": "mongodb"
}
db = MongoEngine(app)

api = Api(app)

SWAGGER_URL = '/api/doc'  # URL for exposing Swagger UI (without trailing '/')
API_URL = 'swagger.json'  # Our API url (can of course be a local resource)

swagger_blueprint = get_swagger_blueprint(
    api.open_api_json,
    swagger_prefix_url=SWAGGER_URL,
    swagger_url=API_URL,
    title='Order Taking', version='1')

api.add_resource(PredictToTakeOrder, '/toTake')
api.add_resource(ConsultToTakeOrder, '/toTake/<order_id>')

app.register_blueprint(swagger_blueprint)

if __name__ == '__main__':
Exemplo n.º 9
0
#!/usr/bin/env python

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

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

from views import UserResource, UserItemResource, GroupResource

app = Flask(__name__)
CORS(app)
servers = [{"url": "http://*****:*****@app.route('/')
def index():
    return """<head>
Exemplo n.º 10
0
from flask import Flask
#from flask_restful import Resource, Api, reqparse, abort, marshal, fields
from flask_restful import marshal, reqparse, fields
from flask_restful_swagger_3 import  Resource, Api, swagger

# Initialize Flask
app = Flask(__name__)
api = Api(app)

# A List of Dicts to store all of the books
books = [{
    "id": 1,
    "title": "Zero to One",
    "author": "Peter Thiel",
    "length": 195,
    "rating": 4.17
},
    {
    "id": 2,
    "title": "Atomic Habits ",
    "author": "James Clear",
    "length": 319,
    "rating": 4.35
}
]

# Schema For the Book Request JSON
bookFields = {
    "id": fields.Integer,
    "title": fields.String,
    "author": fields.String,
Exemplo n.º 11
0
from flask import Flask
from flask_cors import CORS
from flask_restful_swagger_3 import Api

from resources.place_record import PlaceRecord, PlaceRecords

app = Flask(__name__)
CORS(app)
# Use the swagger Api class as you would use the flask restful class.
# It supports several (optional) parameters, these are the defaults:
api = Api(app, version='0.0', api_spec_url='/api/spec')

api.add_resource(PlaceRecords, '/placerecords/', methods=['POST'])
api.add_resource(PlaceRecord,
                 '/placerecords/<string:name>',
                 methods=['GET', 'PUT', 'DELETE'])

app.run(host='0.0.0.0', port=5000, debug=True)
# In the context of servers, 0.0.0.0 can mean "all IPv4 addresses on the local machine".
Exemplo n.º 12
0
from resources.FeirasLivres import FeiraList
from ApiDocumentation import Contact
from db import SessionLocal, engine
from models import Base

Base.metadata.create_all(bind=engine)

app = Flask(__name__)
#the line below will get SqlAlchemy Session and use it in the entire api, in this api we are not using Flask-SqlAlchemy
app.session = scoped_session(SessionLocal,
                             scopefunc=_app_ctx_stack.__ident_func__)
Base.session = app.session  #sharing session with models
Base.query = app.session.query_property()
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'llb'
api = Api(app,
          contact=Contact.dict_contact,
          title='MercadoBitcoinAvaliacao',
          version=0.1)

sentry_sdk.init(
    dsn=
    "https://[email protected]/5536196",
    integrations=[FlaskIntegration()],
    traces_sample_rate=1.0)

api.add_resource(FeiraLivre, '/feira-livre/<string:codigo>')
api.add_resource(FeiraList, '/feira-list/<string:name>')
#todo bairros crud

app.run(port=5000, debug=False)
Exemplo n.º 13
0
app.config['JWT_AUTH_URL_RULE'] = '/api/auth'
app.config['JWT_BLACKLIST_ENABLED'] = True
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access', 'refresh']
app.config['DATABASE'] = configuration['database']

if 'swagger' in configuration:
    app.config['SWAGGER_PROD_URL'] = configuration['swagger']['prod']['url']
else:
    app.config['SWAGGER_PROD_URL'] = 'http://localhost'

api = Api(app, version='0.1',
          api_spec_url="/v1/spec",
          servers=[{"url": app.config['SWAGGER_PROD_URL'], "description": "Production server"}],
          contact={"name": "Developper",
                   "url": "https://github.com/Whyrl35/sshportal-api",
                   "email": "*****@*****.**"},
          description="An API over the moul/sshportal project, SSH bastion.",
          license={"name": "MIT",
                   "url": "https://en.wikipedia.org/wiki/MIT_License"},
          components={"securitySchemes": {"bearerAuth": {"type": "http", "scheme": "bearer", "bearerFormat": "Bearer"}}},  # noqa
          # security={"bearerAuth": []},
          )
jwt = JWTManager(app)

from sshportal_api.resources import *  # noqa


@jwt.token_in_blacklist_loader
def check_if_token_in_blacklist(decrypted_token):
    import sshportal_api.models

    jti = decrypted_token['jti']
Exemplo n.º 14
0
from flask import Flask, request, jsonify
from flask_restful_swagger_3 import Api, get_swagger_blueprint
from flask_cors import CORS

from api import entrypoints
from api import handlerexception

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

api.add_resource(entrypoints.UserLogin, '/api/user/login')

handlerexception.register_error_handler(app)

servers = [{"url": "http://localhost:5000"}]
swagger_blueprint = get_swagger_blueprint(api.open_api_json,
                                          swagger_prefix_url='/api/doc',
                                          swagger_url='swagger.json',
                                          title='Example',
                                          version='1',
                                          servers=servers)

app.register_blueprint(swagger_blueprint)

app.run(debug=True)
Exemplo n.º 15
0
from flask import Flask
from flask_restful_swagger_3 import Api

from operator import itemgetter
import sys

sys.path.append("../config/")
sys.path.append("models/")
import config

app = Flask(__name__)
# api = Api(app)
api = Api(app, version="1.0", title="mtgggg", api_spec_url="/v1/api/swagger")

from api.resources.querysimilar import QuerySimilar
from api.resources.generaterandom import GenerateRandom
from api.resources.search import Search
from api.resources.list import List, ListSets, ListPage
from api.resources.swagger import ApiSwagger

# Main entrypoints
api.add_resource(QuerySimilar, "/v1/ml/similar/<int:card_id>/")
api.add_resource(GenerateRandom,
                 "/v1/ml/generate/random/",
                 methods=["GET", "POST", "DELETE"])
api.add_resource(Search, "/v1/search/")
api.add_resource(ListSets, "/v1/list/", methods=["GET"])
api.add_resource(List, "/v1/list/<string:keyrune_code>/", methods=["GET"])
api.add_resource(ListPage,
                 "/v1/list/<string:keyrune_code>/<int:page>/",
                 methods=["GET"])
Exemplo n.º 16
0
from flask import Flask
from flask_cors import CORS
from flask_restful_swagger_3 import Api
from endpoints import Articles, Article

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

api.add_resource(Articles, "/articles")
api.add_resource(Article, "/articles/<string:_id>")
Exemplo n.º 17
0
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_restful_swagger_3 import Api, get_swagger_blueprint
from flask_swagger_ui import get_swaggerui_blueprint

from config import Config, SwaggerConfig
app = Flask(__name__)
app.config.from_object(Config)

api = Api(app, add_api_spec_resource=True, title=SwaggerConfig.TITLE, description=SwaggerConfig.DESCRIPTION, version=SwaggerConfig.VERSION)
db = SQLAlchemy(app)

from app_resources.user_res import UserRes
from app_resources.tea_res import TeaRes
from app_resources.teas_res import TeasRes
from app_resources.order_res import OrderRes
from app_resources.orders_res import OrdersRes
from app_resources.login_res import LoginRes
from app_resources.photo_res import TeaPhotoRes
from app_resources.dev_tool import DevTools

api.add_resource(UserRes, '/user')
api.add_resource(TeaRes, '/tea')
api.add_resource(TeasRes, '/teas')
api.add_resource(OrderRes, '/order')
api.add_resource(OrdersRes, '/orders')
api.add_resource(LoginRes, '/login')
api.add_resource(DevTools, '/dev')
api.add_resource(TeaPhotoRes, '/photo/<int:tea_id>')

db.create_all()
Exemplo n.º 18
0
from flask import Flask, request, g, render_template
from flask_restful import Resource, reqparse
from flask_restful_swagger_3 import Api
from flask_cors import CORS
import os
from json import dumps
import application.endpoints as endpoints
import application.config as config
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
api = Api(app,
          version='1',
          contact={"name": ""},
          license={"name": "Online Dienst Dokumentation"},
          api_spec_url='/api/swagger')

api.add_resource(endpoints.PersonList, '/api/v1/person/<string:id>',
                 '/api/v1/person/')
api.add_resource(endpoints.Camera, '/api/v1/camera/<string:type>',
                 "/api/v1/camera/")


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