예제 #1
0
from flask_restx import Api

api = Api()


@api.errorhandler
def default_error_handler(e):
    message = 'An unhandled exception occurred.'


# @api.errorhandler(Exception)
# def default_error_handler(e):
#     message = 'payment could not be proccessed.'
예제 #2
0
from flask_restx import Api
from flask import Blueprint

from .main.controller.user_controller import api as user_ns
from .main.controller.book_controller import api as book_ns
from .main.controller.auth_controller import api as auth_ns
from .main.controller.main_controller import api as main_ns

blueprint = Blueprint('api', __name__)

api = Api(blueprint,
          title='FLASK BOOK STORE',
          version='1.0',
          description='simple bookstore app')

api.add_namespace(main_ns, path='')
api.add_namespace(user_ns, path='/user')
api.add_namespace(book_ns, path='/book')
api.add_namespace(auth_ns, path='/auth')
예제 #3
0
from flask_restx import Api

from app.api.constants import AUTH_HEADER_KEY

title = 'FQM API'
description = 'Free Queue Manage API'
auth_config = {
    'apiKey': {
        'type': 'apiKey',
        'in': 'headers',
        'name': AUTH_HEADER_KEY
    }
}

api = Api(title=title,
          description=description,
          authorizations=auth_config,
          validate=True)
예제 #4
0
import jwt

from .resources.product import product_ns

v1_blueprint = Blueprint('v1_blueprint', __name__)
authorizations = {
    'apikey': {
        'type': 'apiKey',
        # 'scheme': 'bearer',
        'in': 'header',
        'name': 'Authorization'
    }
}
v1_api = Api(v1_blueprint,
             title='Demo API',
             version='1.0',
             description='',
             authorizations=authorizations)

# from .resources.auth import auth_ns

# from .resources.todo import todo_ns
# from .resources.user import user_ns


@v1_api.errorhandler(ValidationException)
def handle_validation_exception(error):
    return {
        'message': error.message,
        'errors': {
            error.error_field_name: error.message
예제 #5
0
from flask import Flask, Blueprint
from flask_restx import Api
from flask_cors import CORS

# Get the app initialized and set CORS rules
app = Flask(__name__)
blueprint = Blueprint("api", __name__, url_prefix="/api/v1.0")
api = Api(
    blueprint,
    title="Notes App API",
    version="v1.0",
    description="RESTful API for the Notes app",
    doc="/swagger",
)
app.register_blueprint(blueprint)
CORS(app, resources={r"/*": {"origins": "*"}})

from app import routes
예제 #6
0
"""API blueprint configuration."""
from flask import Blueprint
from flask_restx import Api

from src.flask_boilerplate.api.auth.endpoints import auth_ns

api_bp = Blueprint("api", __name__, url_prefix="/api/v1")
authorizations = {
    "Bearer": {
        "type": "apiKey",
        "in": "header",
        "name": "Authorization"
    }
}

api = Api(
    api_bp,
    version="1.0",
    title="Flask API with JWT-Based Authentication",
    description="Welcome to the Swagger UI documentation site!",
    doc="/ui",
    authorizations=authorizations,
)

api.add_namespace(auth_ns, path="/auth")
예제 #7
0
from flask_restx import Api
from flask import Blueprint

from app.main.collectors_item.controllers.collectors_item_controller import api as collectors_item_namespace

blueprint = Blueprint("api", __name__)

api = Api(blueprint,
          title="CollectorsItems at rest backend",
          version="0.1.0",
          description="RESTful API for managing collectors_items.")

api.add_namespace(collectors_item_namespace)
예제 #8
0
#!/usr/bin/python3
# testing code
from flask import Flask, render_template, redirect, url_for
from flask_restx import Api, Resource

import json
import random

with open('configs.json', 'r') as f:  # config file loading
    configs = json.load(f)

app = Flask(__name__)
api = Api(app)
const = ['1.jpeg', '2.jpeg', '3.jpeg', '4.jpeg', '5.jpeg']


# @app.route('/demo')
# def hello_world():
#    return 'Hello World!'
def img_select(const):
    return random.choice(const)


@app.route('/service')
def servoce():
    return render_template(
        'index.html',
        title='I love cats',
        # backend_url = 'http://localhost:8080',
        image_url=
        'https://raw.githubusercontent.com/John1Q84/pub_playground/main',
예제 #9
0
"""

from flask_restx import Api

from .meta import api as META_API
from .ops import api as OPS_API
from .notifications import api as NOTIFICATIONS_API
from .email import api as EMAIL_API

# This will add the Authorize button to the swagger docs
# TODO oauth2 & openid may not yet be supported by restplus <- check on this
AUTHORIZATIONS = {
    'apikey': {
        'type': 'apiKey',
        'in': 'header',
        'name': 'Authorization'
    }
}

API = Api(title='Notifications API',
          version='1.0',
          description='Notifications API for Service BC',
          prefix='/api/v1',
          security=['apikey'],
          authorizations=AUTHORIZATIONS)

API.add_namespace(OPS_API, path='')
API.add_namespace(META_API, path='')
API.add_namespace(NOTIFICATIONS_API, path='/notifications')
API.add_namespace(EMAIL_API, path='/notifications')
예제 #10
0
from flask import Flask
from flask_restx import Api, Resource, fields

# THIS CODE IS DERIVATED FROM THE EXAMPLE OF Flask-RESTX EXTENSION

app = Flask(__name__)
api = Api(
    app,
    version='1.0',
    title='TodoMVC API',
    description='A simple TodoMVC API',
)

ns = api.namespace('todos', description='TODO operations')

todo = api.model(
    'Todo', {
        'id':
        fields.Integer(readOnly=True,
                       description='The task unique identifier'),
        'task':
        fields.String(required=True, description='The task details')
    })


class TodoDAO(object):
    def __init__(self):
        self.counter = 0
        self.todos = []

    def get(self, id):
예제 #11
0
The current used providers are:
\n* GitHub
\n* GitLab
\n* Stack Exchange

Any new evaluator must follow the input/output behavior defined in '/evaluate' endpoint. 

### Endpoints  \n
\n* '/evaluate': Default evaluator used by Cuban Engineer platform
\n* '/data_mock': Provide mocked profiles data 
  
### Mocked data
The '/data_mock' endpoint provide a set of anonymous data stored on Cuban Engineer platform

The service purposes are:
\n* Provide a way to test custom evaluation services
\n* Give an estimated evaluation of each engineer to get an idea about how an evaluation service should behave 

In service documentation is provided a sorted result, from higher to lower, of provided profiles with some comments

Note: Any evaluator should return a similar result to presented in documentation 
"""

evaluator_api = Api(evaluator_blueprint,
                    version='1.0',
                    title='Skill Evaluator API',
                    description=description)

evaluator_api.add_namespace(evaluator_namespace, path='/')
예제 #12
0
from aw_query.exceptions import QueryException

from . import logger
from .api import ServerAPI
from .exceptions import BadRequest, Unauthorized


# SECURITY
# As we work our way through features, disable (while this is False, we should only accept connections from localhost)
SECURITY_ENABLED = False

# For the planned zeroknowledge storage feature
ZEROKNOWLEDGE_ENABLED = False

blueprint = Blueprint('api', __name__, url_prefix='/api')
api = Api(blueprint, doc='/')


# TODO: Clean up JSONEncoder code?
# Move to server.py
class CustomJSONEncoder(json.JSONEncoder):
    def __init__(self, *args, **kwargs):
        super().__init__()

    def default(self, obj, *args, **kwargs):
        try:
            if isinstance(obj, datetime):
                return obj.isoformat()
            if isinstance(obj, timedelta):
                return obj.total_seconds()
        except TypeError:
예제 #13
0
authorizations = {
    'token': {
        'type': 'apiKey',
        'in': 'header',
        'name': 'Authorization'
    }
}

api_doc = """
**API Documentation**

v1.0.0: First release of API. Only pihole, period and account endpoints.
v1.1.0: Added transactions namespace.
v1.2.0: Added AI namespace.
v1.3.0: Added basic GraphQL section of API. available at /v1/graphql.
"""

api = Api(blueprint,
          title="restberry-api",
          version="1.3.0",
          description=api_doc,
          authorizations=authorizations,
          security=["token"])

api.add_namespace(auth)
api.add_namespace(pihole)
api.add_namespace(periods)
api.add_namespace(accounts)
api.add_namespace(transactions)
api.add_namespace(ai)
예제 #14
0
#   http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import flask
from src import device
from src.device import kenmore
from flask_restx import Api, Resource  # type: ignore


bp = flask.Blueprint("api", __name__, url_prefix="/api")
api = Api(bp, prefix="/v1")


@api.route("/conditions")
class Conditions(Resource):
    def get(self):
        return


@api.route("/devices")
class Devices(Resource):
    def get(self):
        return device.Devices


@api.route("/device/kenmore/<prop>")
예제 #15
0
import werkzeug
werkzeug.cached_property = werkzeug.utils.cached_property
from flask_restx import Api
from flask import Blueprint
from .main.controller.vendor_controller import api as vendor_ns
from .main.controller.user_controller import api as user_ns

blueprint = Blueprint('api', __name__)

api = Api(blueprint,
          title='FOOD TRUCK TRACKER API BOILER-PLATE',
          version='1.0',
          description='a boilerplate for flask restplus web service')
api.add_namespace(vendor_ns, path='/vendor')
api.add_namespace(user_ns, path='/user')
예제 #16
0
from flask_restx import Api
from app.api.resources.goal import goals_ns as goal_namespace

api = Api(
    title="Kanban System API",
    version="1.0",
    description="API documentation for the backend of Kanban System. \n \n")
api.namespaces.clear()

# Adding namespaces
print(goal_namespace)
api.add_namespace(goal_namespace, path="/")
예제 #17
0
from flask import Blueprint
from flask_restx import Api

from api.stats.cpu import cpu
from api.stats.disk import disk
from api.stats.memory import memory
from api.stats.network import network
from api.stats.sensors import sensors
from api.stats.system import system

api = Api(Blueprint("api", __name__, url_prefix="/api"),
          # title='title',
          # version='1.0',
          # description='desc',
          )

api.add_namespace(cpu, path="/stats")
api.add_namespace(memory, path="/stats")
api.add_namespace(disk, path="/stats")
api.add_namespace(network, path="/stats")
api.add_namespace(sensors, path="/stats")
api.add_namespace(system, path="/stats")
예제 #18
0
import logging

from flask import Blueprint
from flask_restx import Api
from application.configuration import web_templates_dir, web_static_dir

logger = logging.getLogger("VahenWebsite.passions.travail_du_cuir")
travail_du_cuir_static_folder = web_static_dir + 'passions/travail_du_cuir'
travail_du_cuir_template_folder = web_templates_dir + 'passions/travail_du_cuir'

travail_du_cuir_bp = Blueprint('travail_du_cuir_bp',
                               __name__,
                               static_folder=travail_du_cuir_static_folder,
                               template_folder=travail_du_cuir_template_folder,
                               url_prefix="/passions/travail_du_cuir")

travail_du_cuir_api = Api(
    travail_du_cuir_bp,
    version="1.0",
    title="Leatherwork API",
    description=
    "Cette API permet de récupérer les informations sur travail du cuir",
    prefix="/api")

from application.passions.travail_du_cuir_api import routes
예제 #19
0
from flask import Flask, request
from flask_restx import Resource, Api, reqparse, fields

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

# @api.route('/hello')
# class HelloWorld(Resource):
#     def get(self):
#         return {'hello': 'world'}

todos = {}


@api.route('/todo<string:todo_id>')
class TodoSimple(Resource):
    def get(self, todo_id):
        return {todo_id: todos[todo_id]}

    def put(self, todo_id):
        todos[todo_id] = request.form['data']
        return {todo_id: todos[todo_id]}


@api.route('/t1')
class Todo1(Resource):
    def get(self):
        # Default to 200 OK
        return {'task': 'Hello world'}

예제 #20
0
from flask import Flask, Blueprint, render_template
from flask_cors import CORS
from flask_restx import Api, Resource, reqparse
import time
import json

deviceParser = reqparse.RequestParser()
deviceParser.add_argument('temp', type=float)
deviceParser.add_argument('key', type=str)
deviceParser.add_argument('n', type=int)

app = Flask(__name__)
CORS(app)

blueprint = Blueprint('api', __name__, url_prefix='/api')
api = Api(blueprint, doc='/doc/')
app.register_blueprint(blueprint)

key_map = {'hansnodemcu': '1234abcd'}

store = {'t': []}

try:
    with open('data.txt') as json_file:
        store = json.load(json_file)
except:
    print("data.txt not found - empty data")


@api.route('/<device>')
@api.doc(params={'device': 'device name', 'key': 'api key', 'n': 'number'})
예제 #21
0
from flask_restx import Api

from app.apis.namespace_environment_builds import api as ns_env_builds
from app.apis.namespace_environment_images import api as ns_env_images
from app.apis.namespace_jobs import api as ns_jobs
from app.apis.namespace_jupyter_builds import api as ns_jupyter_builds
from app.apis.namespace_pipelines import api as ns_pipelines
from app.apis.namespace_projects import api as ns_projects
from app.apis.namespace_runs import api as ns_runs
from app.apis.namespace_sessions import api as ns_sessions
from app.apis.namespace_validations import api as ns_validations

blueprint = Blueprint("api", __name__)

api = Api(
    blueprint,
    title="Orchest API",
    version="1.0",
    description="Back-end API for Orchest",
)

api.add_namespace(ns_env_builds)
api.add_namespace(ns_env_images)
api.add_namespace(ns_jobs)
api.add_namespace(ns_jupyter_builds)
api.add_namespace(ns_pipelines)
api.add_namespace(ns_projects)
api.add_namespace(ns_runs)
api.add_namespace(ns_sessions)
api.add_namespace(ns_validations)
예제 #22
0
import logging
from http import HTTPStatus

from flask import Blueprint, jsonify, request
from flask_restx import Api, Resource

from project.extensions import db

from project.modules.utils import authenticate_restful, is_admin

from .models import Users as UsersModel

log = logging.getLogger(__name__)

users_blueprint = Blueprint('users', __name__)
users_api = Api(users_blueprint)


class Users(Resource):
    @authenticate_restful
    def get(self, token: str):
        """Get single user details"""
        response_object = {'status': 'fail', 'message': 'User does not exist'}
        log.debug(token)
        try:
            user = UsersModel.query.filter_by(id=token).first()
            log.debug(user)
            if not user:
                return response_object, HTTPStatus.NOT_FOUND
            else:
                response_object = {'status': 'success', 'data': user.to_json()}
예제 #23
0
from flask import Blueprint
from flask_restx import Resource, Api

ping_blueprint = Blueprint('ping', __name__)
api = Api(ping_blueprint)


class Ping(Resource):
    def get(self):
        return {
            'status': 'success',
            'message': 'pong!'
        }


api.add_resource(Ping, '/ping')
예제 #24
0
    cuisine_ns,
    households_ns,
    ingredient_ns,
    recipe_ns,
    user_ns,
    diet_type_ns,
)

api_v1 = Blueprint("api_v1", __name__, url_prefix="/api/v1")
api = Api(
    api_v1,
    version="1.0",
    title="HouseChef.io API",
    authorizations={
        "apiKey": {
            "type": "apiKey",
            "in": "header",
            "name": "Authorization",
            "description": "Type in the *'Value'* input box below: **'Bearer &lt;JWT&gt;'**, where JWT is the token",
        }
    },
)

api.add_namespace(user_ns, path="/users")
api.add_namespace(recipe_ns, path="/recipes")
api.add_namespace(auth_ns, path="/auth")
api.add_namespace(ingredient_ns, path="/ingredients")
api.add_namespace(households_ns, path="/households")
api.add_namespace(cuisine_ns, path="/cuisines")
api.add_namespace(diet_type_ns, path="/diet_types")
예제 #25
0
파일: __init__.py 프로젝트: StuartsHome/api
# src/__init__.py


from flask import Flask, jsonify
from flask_restx import Resource, Api


# instantiate the app
app = Flask(__name__)

api = Api(app)


class Ping(Resource):
    def get(self):
        return {
            'status': 'success',
            'message': 'pong!'
        }


api.add_resource(Ping, '/ping')


예제 #26
0
from PIL import Image, UnidentifiedImageError
from expiringdict import ExpiringDict
from flask import Blueprint, current_app, jsonify, request, g
from flask_httpauth import HTTPTokenAuth
from flask_restx import Api, Resource, abort
from itsdangerous import (TimedJSONWebSignatureSerializer as Serializer,
                          BadSignature, SignatureExpired)

from .. import *
from ..models import *
from ..mojang import *

apiv1 = Blueprint("api_v1", __name__, url_prefix="/api/v1")

auth = HTTPTokenAuth()
api = Api(apiv1)


def gen_auth_token(user: User, expiration):
    s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration)
    return s.dumps({'id': user.id})


@auth.error_handler
def auth_failed():
    return abort(401, "Authentication failed")


@auth.verify_token
def verify_auth_token(token):
    s = Serializer(current_app.config['SECRET_KEY'])
예제 #27
0
import logging

from flask_restx import Api

log = logging.getLogger(__name__)

api = Api(version='1.0',
          title='3D-Beacons Client API',
          description='3D Beacon Client API')
예제 #28
0
from flask_restx import Api
from marshmallow import ValidationError

from db import db
from resources.user import UserInfo, UserLogin
from resources.submission import AdminForHidden, LeaderBoard, Submission, SubmissionList, HiddenSubmission, HiddenSubmissionList, HiddenLeaderBoard
from resources.download import Example, Expdirs

app = Flask(__name__)
load_dotenv()

app.config.from_object("flask_config")

jwt = JWTManager(app)
CORS(app, resource={r"/api/*": {"origin": "*"}})
api = Api(app)


@app.before_first_request
def create_tables():
    db.create_all()


@app.errorhandler(ValidationError)
def handle_marshmallow_validation(err):
    return jsonify(err.messages), 400


# public
api.add_resource(Submission, "/api/submission", methods=["POST"])
api.add_resource(Submission,
예제 #29
0
from flask_restx import Api

from app.apis.v1.concept import api as concept_api
from app.apis.v1.statistics import api as stats_api

# version
# api
api = Api(
    title='Patients info api',
    version='1.0',
    description='Notice: Patient info api is provided based on dummy data',
    contact_email='*****@*****.**',
)

# namespaces
api.add_namespace(stats_api, path='/v1/stats')
api.add_namespace(concept_api, path='/v1/concepts')
예제 #30
0
from flask import Flask
from flask_migrate import Migrate
from app.config import Configuration
from app.models import db
from flask_restx import Api
from flask_jwt_extended import JWTManager


from app.routes.games import api as game
from app.routes.moves import api as move

app = Flask(__name__)

app.config.from_object(Configuration)
db.init_app(app)
jwt = JWTManager(app)


api = Api(app)
api.add_namespace(game)
api.add_namespace(move, path="/drop_token/<int:gameId>")

migrate = Migrate(app, db)